/* meetings.js — 생산회의록 목록 */

let canEdit = false;

document.addEventListener('DOMContentLoaded', async () => {
    const ok = await initAuth();
    if (!ok) return;
    document.querySelector('.fade-in').classList.add('visible');

    const role = currentUser?.role || '';
    canEdit = ['support_team', 'admin', 'system', 'system admin'].includes(role);
    if (canEdit) document.getElementById('btnNewMeeting').classList.remove('hidden');

    // Year filter
    const yearSel = document.getElementById('yearFilter');
    const now = new Date();
    for (let y = now.getFullYear() - 2; y <= now.getFullYear() + 1; y++) {
        const opt = document.createElement('option');
        opt.value = y; opt.textContent = y + '년';
        if (y === now.getFullYear()) opt.selected = true;
        yearSel.appendChild(opt);
    }
    document.getElementById('monthFilter').value = String(now.getMonth() + 1);

    yearSel.addEventListener('change', loadMeetings);
    document.getElementById('monthFilter').addEventListener('change', loadMeetings);
    document.getElementById('searchInput').addEventListener('input', debounce(loadMeetings, 300));
    document.getElementById('btnNewMeeting').addEventListener('click', () => {
        location.href = '/pages/work/meeting-detail.html';
    });

    await Promise.all([loadMeetings(), loadActionItems()]);
});

async function loadMeetings() {
    try {
        const year = document.getElementById('yearFilter').value;
        const month = document.getElementById('monthFilter').value;
        const search = document.getElementById('searchInput').value.trim();
        let url = `/meetings?year=${year}`;
        if (month) url += `&month=${month}`;
        if (search) url += `&search=${encodeURIComponent(search)}`;
        const res = await api(url);
        renderMeetings(res.data || []);
    } catch (err) {
        showToast('회의록 목록 로드 실패: ' + err.message, 'error');
    }
}

function renderMeetings(meetings) {
    const list = document.getElementById('meetingList');
    const empty = document.getElementById('emptyState');

    if (meetings.length === 0) {
        list.innerHTML = '';
        empty.classList.remove('hidden');
        return;
    }
    empty.classList.add('hidden');

    list.innerHTML = meetings.map(m => {
        const statusBadge = m.status === 'published'
            ? '<span class="badge badge-green">발행</span>'
            : '<span class="badge badge-gray">초안</span>';
        return `
            <a href="/pages/work/meeting-detail.html?id=${m.meeting_id}" class="block bg-white rounded-xl shadow-sm p-4 hover:shadow-md transition-shadow">
                <div class="flex items-start justify-between gap-3">
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-1">
                            <span class="text-sm text-gray-500">${formatDate(m.meeting_date)}</span>
                            ${statusBadge}
                        </div>
                        <h3 class="font-semibold text-gray-800 truncate">${escapeHtml(m.title)}</h3>
                        <div class="flex items-center gap-4 mt-2 text-xs text-gray-500">
                            <span><i class="fas fa-user mr-1"></i>${escapeHtml(m.created_by_name || '-')}</span>
                            <span><i class="fas fa-users mr-1"></i>참석 ${m.attendee_count || 0}명</span>
                            <span><i class="fas fa-list mr-1"></i>안건 ${m.agenda_count || 0}건</span>
                            ${m.open_action_count > 0 ? `<span class="text-amber-600 font-semibold"><i class="fas fa-exclamation-circle mr-1"></i>미완료 ${m.open_action_count}건</span>` : ''}
                        </div>
                    </div>
                    <i class="fas fa-chevron-right text-gray-300 mt-2"></i>
                </div>
            </a>
        `;
    }).join('');
}

async function loadActionItems() {
    try {
        const res = await api('/meetings/action-items?status=open');
        const items = res.data || [];
        if (items.length === 0) return;

        document.getElementById('actionSummary').classList.remove('hidden');
        document.getElementById('actionCount').textContent = items.length;

        document.getElementById('actionList').innerHTML = items.slice(0, 5).map(item => `
            <div class="flex items-center gap-2 p-1.5 bg-white rounded">
                <span class="text-amber-600"><i class="fas fa-circle text-[6px]"></i></span>
                <span class="flex-1 truncate">${escapeHtml(item.content)}</span>
                ${item.responsible_name ? `<span class="text-gray-400 text-xs">${escapeHtml(item.responsible_name)}</span>` : ''}
                ${item.due_date ? `<span class="text-xs ${new Date(item.due_date) < new Date() ? 'text-red-500 font-semibold' : 'text-gray-400'}">${formatDate(item.due_date)}</span>` : ''}
            </div>
        `).join('') + (items.length > 5 ? `<div class="text-xs text-gray-400 text-center mt-1">외 ${items.length - 5}건</div>` : '');
    } catch {}
}
