/* ===== Projects CRUD ===== */
let projects = [], projectsLoaded = false, productTypesCache = [];

function statusBadge(status, isActive) {
    if (!isActive || isActive === 0 || isActive === false) return '<span class="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-400">비활성</span>';
    if (status === 'completed') return '<span class="px-1.5 py-0.5 rounded text-xs bg-blue-50 text-blue-600">완료</span>';
    return '<span class="px-1.5 py-0.5 rounded text-xs bg-emerald-50 text-emerald-600">진행중</span>';
}

async function loadProductTypes() {
    try {
        const r = await api('/projects/product-types');
        productTypesCache = r.data || [];
        ['newProductType', 'editProductType'].forEach(id => {
            const sel = document.getElementById(id); if (!sel) return;
            const val = sel.value;
            sel.innerHTML = '<option value="">선택</option>';
            productTypesCache.forEach(pt => { const o = document.createElement('option'); o.value = pt.id; o.textContent = `${pt.code} - ${pt.name}`; sel.appendChild(o); });
            sel.value = val;
        });
    } catch(e) { console.warn('제품유형 로드 실패:', e); }
}

async function loadProjects() {
    try {
        await loadProductTypes();
        const r = await api('/projects'); projects = r.data || r;
        projectsLoaded = true;
        displayProjects();
    } catch (err) {
        document.getElementById('projectList').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">${escapeHtml(err.message)}</p></div>`;
    }
}

function displayProjects() {
    const c = document.getElementById('projectList');
    if (!projects.length) { c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">등록된 프로젝트가 없습니다.</p>'; return; }
    c.innerHTML = projects.map(p => `
        <div class="flex items-center justify-between p-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors">
            <div class="flex-1 min-w-0">
                <div class="text-sm font-medium text-gray-800 truncate"><i class="fas fa-folder mr-1.5 text-gray-400 text-xs"></i>${escapeHtml(p.project_name)}</div>
                <div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5 flex-wrap">
                    <span class="font-mono">${escapeHtml(p.job_no)}</span>
                    ${p.product_type_code?`<span class="px-1.5 py-0.5 rounded bg-indigo-50 text-indigo-600 font-medium">${escapeHtml(p.product_type_code)}</span>`:''}
                    ${p.site?`<span class="px-1.5 py-0.5 rounded bg-amber-50 text-amber-600">${escapeHtml(p.site)}</span>`:''}
                    ${p.pm?`<span class="px-1.5 py-0.5 rounded bg-slate-50 text-slate-500">${escapeHtml(p.pm)}</span>`:''}
                    ${statusBadge(p.project_status, p.is_active)}
                    ${p.due_date?`<span class="text-gray-400">${formatDate(p.due_date)}</span>`:''}
                </div>
            </div>
            <div class="flex gap-1 ml-2 flex-shrink-0">
                <button onclick="editProject(${p.project_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>
                ${p.is_active?`<button onclick="deactivateProject(${p.project_id},'${escapeHtml(p.project_name).replace(/'/g,"\\'")}')" class="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-100 rounded" title="비활성화"><i class="fas fa-ban text-xs"></i></button>`:''}
            </div>
        </div>`).join('');
}

document.getElementById('addProjectForm').addEventListener('submit', async e => {
    e.preventDefault();
    try {
        await api('/projects', { method: 'POST', body: JSON.stringify({
            job_no: document.getElementById('newJobNo').value.trim(),
            project_name: document.getElementById('newProjectName').value.trim(),
            contract_date: document.getElementById('newContractDate').value || null,
            due_date: document.getElementById('newDueDate').value || null,
            site: document.getElementById('newSite').value.trim() || null,
            pm: document.getElementById('newPm').value.trim() || null,
            product_type_id: document.getElementById('newProductType').value ? parseInt(document.getElementById('newProductType').value) : null
        })});
        showToast('프로젝트가 추가되었습니다.'); document.getElementById('addProjectForm').reset(); await loadProjects();
    } catch(e) { showToast(e.message, 'error'); }
});

function editProject(id) {
    const p = projects.find(x => x.project_id === id); if (!p) return;
    document.getElementById('editProjectId').value = p.project_id;
    document.getElementById('editJobNo').value = p.job_no;
    document.getElementById('editProjectName').value = p.project_name;
    document.getElementById('editContractDate').value = formatDate(p.contract_date);
    document.getElementById('editDueDate').value = formatDate(p.due_date);
    document.getElementById('editSite').value = p.site || '';
    document.getElementById('editPm').value = p.pm || '';
    document.getElementById('editProductType').value = p.product_type_id || '';
    document.getElementById('editProjectStatus').value = p.project_status || 'active';
    document.getElementById('editIsActive').value = p.is_active ? '1' : '0';
    document.getElementById('editProjectModal').classList.remove('hidden');
}
function closeProjectModal() { document.getElementById('editProjectModal').classList.add('hidden'); }

document.getElementById('editProjectForm').addEventListener('submit', async e => {
    e.preventDefault();
    try {
        await api(`/projects/${document.getElementById('editProjectId').value}`, { method: 'PUT', body: JSON.stringify({
            job_no: document.getElementById('editJobNo').value.trim(),
            project_name: document.getElementById('editProjectName').value.trim(),
            contract_date: document.getElementById('editContractDate').value || null,
            due_date: document.getElementById('editDueDate').value || null,
            site: document.getElementById('editSite').value.trim() || null,
            pm: document.getElementById('editPm').value.trim() || null,
            product_type_id: document.getElementById('editProductType').value ? parseInt(document.getElementById('editProductType').value) : null,
            project_status: document.getElementById('editProjectStatus').value,
            is_active: document.getElementById('editIsActive').value === '1'
        })});
        showToast('수정되었습니다.'); closeProjectModal(); await loadProjects();
    } catch(e) { showToast(e.message, 'error'); }
});

async function deactivateProject(id, name) {
    if (!confirm(`"${name}" 프로젝트를 비활성화?`)) return;
    try { await api(`/projects/${id}`, { method: 'DELETE' }); showToast('프로젝트 비활성화 완료'); await loadProjects(); } catch(e) { showToast(e.message, 'error'); }
}
