/* ===== Departments CRUD ===== */
let departments = [], departmentsLoaded = false;

const APPROVAL_TYPE_LABELS = { VACATION: '휴가', PURCHASE: '구매', DOCUMENT: '문서' };

async function loadDepartments() {
    try {
        const r = await api('/departments'); departments = r.data || r;
        departmentsLoaded = true;
        displayDepartments();
    } catch (err) {
        document.getElementById('departmentList').innerHTML = `<div class="text-red-500 text-center py-6"><i class="fas fa-exclamation-triangle text-xl"></i><p class="text-sm mt-2">${err.message}</p></div>`;
    }
}

let selectedDeptForMembers = null;

function displayDepartments() {
    const c = document.getElementById('departmentList');
    if (!departments.length) { c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">등록된 부서가 없습니다.</p>'; return; }
    c.innerHTML = departments.map(d => `
        <div class="flex items-center justify-between p-2.5 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer ${selectedDeptForMembers === d.department_id ? 'bg-blue-50 ring-1 ring-blue-200' : 'bg-gray-50'}" onclick="showDeptMembers(${d.department_id})">
            <div class="flex-1 min-w-0">
                <div class="text-sm font-medium text-gray-800 truncate"><i class="fas fa-sitemap mr-1.5 text-gray-400 text-xs"></i>${escHtml(d.department_name)}</div>
                <div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5 flex-wrap">
                    <span class="text-gray-400">순서: ${d.display_order || 0}</span>
                    <span class="text-gray-400">| 팀장: ${d.leader_name ? escHtml(d.leader_name) : '<span class="text-gray-300">미지정</span>'}</span>
                </div>
            </div>
            <div class="flex gap-1 ml-2 flex-shrink-0" onclick="event.stopPropagation()">
                <button onclick="editDepartment(${d.department_id})" class="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded" title="편집"><i class="fas fa-pen-to-square text-xs"></i></button>
                <button onclick="deleteDepartment(${d.department_id},'${(d.department_name||'').replace(/'/g,"\\'")}')" class="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-100 rounded" title="삭제"><i class="fas fa-trash text-xs"></i></button>
            </div>
        </div>`).join('');
}

async function showDeptMembers(deptId) {
    selectedDeptForMembers = deptId;
    displayDepartments();
    const panel = document.getElementById('deptMembersPanel');
    const list = document.getElementById('deptMembersList');
    panel.classList.remove('hidden');
    list.innerHTML = '<div class="text-gray-400 text-center py-4"><i class="fas fa-spinner fa-spin"></i></div>';

    let deptUsers = users;
    if (!deptUsers || !deptUsers.length) {
        try {
            const r = await api('/users');
            deptUsers = r.data || r;
        } catch (e) {
            list.innerHTML = `<p class="text-red-500 text-sm">${e.message}</p>`;
            return;
        }
    }

    const members = deptUsers.filter(u => u.department_id === deptId);
    const dept = departments.find(d => d.department_id === deptId);
    const title = panel.querySelector('h3');
    if (title) title.innerHTML = `<i class="fas fa-users text-slate-400 mr-1.5"></i>소속 인원 — ${dept ? escHtml(dept.department_name) : ''}`;

    if (!members.length) {
        list.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">소속 인원이 없습니다</p>';
    } else {
        list.innerHTML = members.map(u => `
            <div class="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
                <div class="flex items-center gap-2">
                    <div class="w-7 h-7 bg-slate-200 rounded-full flex items-center justify-center text-xs font-semibold text-slate-600">${(u.name || u.username).charAt(0)}</div>
                    <div>
                        <div class="text-sm font-medium text-gray-800">${u.name || u.username}</div>
                        <div class="text-xs text-gray-500">${u.username}</div>
                    </div>
                </div>
                <div class="flex items-center gap-1.5">
                    <span class="px-1.5 py-0.5 rounded text-xs ${u.role === 'admin' ? 'bg-red-50 text-red-600' : 'bg-slate-50 text-slate-500'}">${u.role === 'admin' ? '관리자' : '사용자'}</span>
                    ${u.is_active === 0 || u.is_active === false ? '<span class="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-400">비활성</span>' : '<span class="px-1.5 py-0.5 rounded text-xs bg-emerald-50 text-emerald-600">활성</span>'}
                </div>
            </div>`).join('');
    }

    loadApprovalAuthorities(deptId);
}

document.getElementById('addDepartmentForm').addEventListener('submit', async e => {
    e.preventDefault();
    try {
        await api('/departments', { method: 'POST', body: JSON.stringify({
            department_name: document.getElementById('newDeptName').value.trim(),
            description: document.getElementById('newDeptDescription').value.trim() || null,
            display_order: parseInt(document.getElementById('newDeptOrder').value) || 0
        })});
        showToast('부서가 추가되었습니다.'); document.getElementById('addDepartmentForm').reset(); await loadDepartments();
    } catch(e) { showToast(e.message, 'error'); }
});

async function editDepartment(id) {
    const d = departments.find(x => x.department_id === id); if (!d) return;
    document.getElementById('editDeptId').value = d.department_id;
    document.getElementById('editDeptName').value = d.department_name;
    document.getElementById('editDeptDescription').value = d.description || '';
    document.getElementById('editDeptOrder').value = d.display_order || 0;

    // Populate leader dropdown
    const leaderSel = document.getElementById('editDeptLeader');
    leaderSel.innerHTML = '<option value="">미지정</option>';
    let deptUsers = users;
    if (!deptUsers || !deptUsers.length) {
        try { const r = await api('/users'); deptUsers = r.data || r; } catch(e) { /* ignore */ }
    }
    const activeUsers = (deptUsers || []).filter(u => u.is_active !== 0 && u.is_active !== false);
    const byDept = {};
    activeUsers.forEach(u => {
        const dName = deptLabel(u.department, u.department_id);
        if (!byDept[dName]) byDept[dName] = [];
        byDept[dName].push(u);
    });
    const currentDeptName = d.department_name;
    const sortedKeys = Object.keys(byDept).sort((a, b) => {
        if (a === currentDeptName) return -1;
        if (b === currentDeptName) return 1;
        return a.localeCompare(b, 'ko');
    });
    sortedKeys.forEach(dName => {
        const grp = document.createElement('optgroup');
        grp.label = dName;
        byDept[dName].forEach(u => {
            const o = document.createElement('option');
            o.value = u.user_id;
            o.textContent = u.name || u.username;
            if (d.leader_user_id && d.leader_user_id === u.user_id) o.selected = true;
            grp.appendChild(o);
        });
        leaderSel.appendChild(grp);
    });

    document.getElementById('editDepartmentModal').classList.remove('hidden');
}
function closeDepartmentModal() { document.getElementById('editDepartmentModal').classList.add('hidden'); }

document.getElementById('editDepartmentForm').addEventListener('submit', async e => {
    e.preventDefault();
    try {
        const leaderId = document.getElementById('editDeptLeader').value;
        await api(`/departments/${document.getElementById('editDeptId').value}`, { method: 'PUT', body: JSON.stringify({
            department_name: document.getElementById('editDeptName').value.trim(),
            description: document.getElementById('editDeptDescription').value.trim() || null,
            display_order: parseInt(document.getElementById('editDeptOrder').value) || 0,
            leader_user_id: leaderId ? parseInt(leaderId) : null
        })});
        showToast('수정되었습니다.'); closeDepartmentModal(); await loadDepartments();
        await loadDepartmentsForSelect();
    } catch(e) { showToast(e.message, 'error'); }
});

async function deleteDepartment(id, name) {
    if (!confirm(`"${name}" 부서를 삭제하시겠습니까? 소속 인원은 부서 미지정으로 변경됩니다.`)) return;
    try { await api(`/departments/${id}`, { method: 'DELETE' }); showToast('부서가 삭제되었습니다'); await loadDepartments(); } catch(e) { showToast(e.message, 'error'); }
}

/* ===== Approval Authorities ===== */
async function loadApprovalAuthorities(deptId) {
    const section = document.getElementById('deptApprovalSection');
    if (!section) return;
    try {
        const r = await api(`/departments/${deptId}/approval-authorities`);
        const data = r.data || r;
        section.classList.remove('hidden');
        renderApprovalAuthorities(deptId, data);
    } catch (e) {
        section.classList.add('hidden');
    }
}

function renderApprovalAuthorities(deptId, data) {
    const list = document.getElementById('deptApprovalList');
    if (!data || !data.length) {
        list.innerHTML = '<p class="text-gray-400 text-center py-3 text-xs">등록된 승인권한이 없습니다</p>';
        return;
    }
    list.innerHTML = `<table class="w-full text-sm"><thead><tr>
        <th class="text-left px-2 py-1 text-xs font-semibold text-gray-500">유형</th>
        <th class="text-left px-2 py-1 text-xs font-semibold text-gray-500">승인자</th>
        <th class="text-center px-2 py-1 text-xs font-semibold text-gray-500">순서</th>
        <th class="px-2 py-1 w-10"></th>
    </tr></thead><tbody>${data.map(a => `<tr class="border-t border-gray-100">
        <td class="px-2 py-1.5"><span class="px-1.5 py-0.5 rounded text-xs bg-slate-50 text-slate-600">${APPROVAL_TYPE_LABELS[a.approval_type] || a.approval_type}</span></td>
        <td class="px-2 py-1.5 text-sm">${escHtml(a.approver_name || '')}</td>
        <td class="px-2 py-1.5 text-center text-xs text-gray-400">${a.approval_order || 1}</td>
        <td class="px-2 py-1.5 text-center"><button onclick="deleteApprovalAuthority(${deptId},${a.id})" class="p-1 text-red-300 hover:text-red-500" title="삭제"><i class="fas fa-trash-alt text-xs"></i></button></td>
    </tr>`).join('')}</tbody></table>`;
}

function openApprovalModal() {
    if (!selectedDeptForMembers) return;
    document.getElementById('approvalDeptId').value = selectedDeptForMembers;
    document.getElementById('approvalAuthorityForm').reset();
    document.getElementById('approvalOrder').value = '1';

    // Populate approver dropdown
    const sel = document.getElementById('approvalUserId');
    sel.innerHTML = '<option value="">선택</option>';
    let availUsers = users;
    if (availUsers && availUsers.length) {
        availUsers.filter(u => u.is_active !== 0 && u.is_active !== false).forEach(u => {
            sel.innerHTML += `<option value="${u.id}">${escHtml(u.name || u.username)}</option>`;
        });
    }

    document.getElementById('approvalAuthorityModal').classList.remove('hidden');
}
function closeApprovalModal() { document.getElementById('approvalAuthorityModal').classList.add('hidden'); }

document.getElementById('approvalAuthorityForm').addEventListener('submit', async e => {
    e.preventDefault();
    const deptId = document.getElementById('approvalDeptId').value;
    try {
        await api(`/departments/${deptId}/approval-authorities`, { method: 'POST', body: JSON.stringify({
            approval_type: document.getElementById('approvalType').value,
            approver_user_id: parseInt(document.getElementById('approvalUserId').value),
            approval_order: parseInt(document.getElementById('approvalOrder').value) || 1
        })});
        showToast('승인권한이 추가되었습니다.');
        closeApprovalModal();
        await loadApprovalAuthorities(parseInt(deptId));
    } catch (e) { showToast(e.message, 'error'); }
});

async function deleteApprovalAuthority(deptId, authId) {
    if (!confirm('이 승인권한을 삭제하시겠습니까?')) return;
    try {
        await api(`/departments/${deptId}/approval-authorities/${authId}`, { method: 'DELETE' });
        showToast('삭제되었습니다.');
        await loadApprovalAuthorities(deptId);
    } catch (e) { showToast(e.message, 'error'); }
}
