// ====== SERVICES MODAL ======
async function openServicesModal() {
    const data = await api.getServices();
    state.services = data.services || [];
    renderServicesList();
    const m = document.getElementById('servicesModal');
    m.classList.remove('hidden');
    setTimeout(() => { m.classList.remove('opacity-0'); m.querySelector('.glass-panel').classList.remove('scale-95'); }, 10);
}

function closeServicesModal() {
    const m = document.getElementById('servicesModal');
    resetServiceForm();
    m.classList.add('opacity-0');
    m.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => m.classList.add('hidden'), 300);
}

function renderServicesList() {
    const container = document.getElementById('servicesListContainer');
    if (state.services.length === 0) {
        container.innerHTML = `<p class="text-gray-500 text-sm italic text-center py-8">${escapeHtml(t('services.empty'))}</p>`;
        return;
    }
    queueTranslationRefresh(state.services.flatMap((s) => [s.name, s.description, s.ideal_client, s.deliverables]));
    container.innerHTML = state.services.map(s => `
        <div class="glass-panel p-5 rounded-2xl border border-white/5 bg-black/40 hover:bg-white/5 transition group">
            <div class="flex items-start justify-between gap-4">
                <div class="flex items-center gap-4">
                    <div class="w-12 h-12 rounded-xl bg-white/5 border border-white/10 flex items-center justify-center text-indigo-400 shrink-0">
                        <i class="fas ${escapeAttr(s.icon || 'fa-box')} text-base leading-none w-5 h-5 flex items-center justify-center"></i>
                    </div>
                    <div>
                        <h4 class="font-bold text-white text-lg">${escapeHtml(getCachedTranslation(s.name))}</h4>
                        <p class="text-sm text-gray-400 mt-0.5">${escapeHtml(getCachedTranslation(s.description))}</p>
                        <p class="text-xs text-gray-500 mt-1"><i class="fas fa-user text-xs mr-1"></i>${escapeHtml(getCachedTranslation(s.ideal_client))}</p>
                    </div>
                </div>
                <div class="text-right shrink-0">
                    <div class="text-2xl font-extrabold text-white">${escapeHtml(formatServicePrice(s))}</div>
                    <div class="text-[10px] text-gray-500 mt-1 uppercase tracking-[0.2em]">${escapeHtml((s.currency || 'EUR').toUpperCase())}</div>
                    <div class="flex gap-2 mt-2 justify-end opacity-0 group-hover:opacity-100 transition">
                        <button onclick="editService(${s.id})" class="text-xs text-blue-400 hover:text-white bg-blue-500/10 px-3 py-1 rounded-lg transition"><i class="fas fa-edit mr-1"></i>${escapeHtml(t('common.edit'))}</button>
                        <button onclick="deleteServiceItem(${s.id})" class="text-xs text-red-400 hover:text-white bg-red-500/10 px-3 py-1 rounded-lg transition"><i class="fas fa-trash mr-1"></i>${escapeHtml(t('common.deleteShort'))}</button>
                    </div>
                </div>
            </div>
            ${s.deliverables ? `<p class="text-xs text-gray-500 mt-3 border-t border-white/5 pt-3"><i class="fas fa-check-circle text-green-400/50 mr-1"></i>${escapeHtml(getCachedTranslation(s.deliverables))}</p>` : ''}
        </div>`).join('');
}

function updateServiceIconPreview(icon = 'fa-box') {
    const normalizedIcon = icon || 'fa-box';
    const input = document.getElementById('svcIcon');
    const preview = document.getElementById('svcIconPreview');
    const label = document.getElementById('svcIconLabel');
    if (input) input.value = normalizedIcon;
    if (preview) preview.className = `fas ${normalizedIcon} text-base text-indigo-300`;
    if (label) label.textContent = normalizedIcon;
}

function openServiceIconPicker() {
    openSharedIconPicker({
        title: 'Choose Service Icon',
        selectedIcon: document.getElementById('svcIcon')?.value || 'fa-box',
        onPick: updateServiceIconPreview
    });
}

function resetServiceForm() {
    state.editingServiceId = null;
    ['svcName','svcDesc','svcPrice','svcDeliverables','svcIdealClient','svcIcon'].forEach(id => {
        const input = document.getElementById(id);
        if (input) input.value = '';
    });
    const currencyInput = document.getElementById('svcCurrency');
    if (currencyInput) currencyInput.value = 'EUR';

    const addBtn = document.getElementById('addServiceBtn');
    const cancelBtn = document.getElementById('cancelServiceEditBtn');
    if (addBtn) addBtn.innerHTML = `<i class="fas fa-plus"></i> ${escapeHtml(t('services.addAction'))}`;
    if (cancelBtn) cancelBtn.classList.add('hidden');
    updateServiceIconPreview('fa-box');
}

function editService(id) {
    const service = state.services.find(s => s.id === id);
    if (!service) return;

    state.editingServiceId = id;
    document.getElementById('svcName').value = service.name || '';
    document.getElementById('svcDesc').value = service.description || '';
    document.getElementById('svcPrice').value = service.price || '';
    document.getElementById('svcCurrency').value = service.currency || 'EUR';
    document.getElementById('svcDeliverables').value = service.deliverables || '';
    document.getElementById('svcIdealClient').value = service.ideal_client || '';
    updateServiceIconPreview(service.icon || 'fa-box');

    const addBtn = document.getElementById('addServiceBtn');
    const cancelBtn = document.getElementById('cancelServiceEditBtn');
    if (addBtn) addBtn.innerHTML = `<i class="fas fa-save"></i> ${escapeHtml(t('services.saveAction'))}`;
    if (cancelBtn) cancelBtn.classList.remove('hidden');
    document.getElementById('svcName').focus();
}

async function saveNewService() {
    const name = document.getElementById('svcName').value.trim();
    if (!name) return showToast(t('services.nameRequired'), 'warning');
    const payload = {
        name,
        description:  document.getElementById('svcDesc').value.trim(),
        price:        document.getElementById('svcPrice').value.trim(),
        currency:     document.getElementById('svcCurrency').value,
        deliverables: document.getElementById('svcDeliverables').value.trim(),
        ideal_client: document.getElementById('svcIdealClient').value.trim(),
        icon:         document.getElementById('svcIcon').value.trim() || 'fa-box'
    };

    const isEditing = Boolean(state.editingServiceId);
    if (isEditing) await api.updateService(state.editingServiceId, payload);
    else await api.addService(payload);

    resetServiceForm();
    const data = await api.getServices();
    state.services = data.services;
    renderServicesList();
    if (state.activeDashboardDivId === 1) {
        await refreshDiv1WorkData();
        renderDiv1Work();
    } else if (state.activeDashboardDivId === 2) {
        await refreshDiv2WorkData();
        renderDiv2Work();
    } else if (state.activeDashboardDivId === 3) {
        await refreshDiv3WorkData();
        renderDiv3Work();
    } else if (state.activeDashboardDivId === 4) {
        await refreshDiv4WorkData();
        renderDiv4Work();
    } else if (state.activeDashboardDivId === 5) {
        await refreshDiv5WorkData();
        renderDiv5Work();
    } else if (state.activeDashboardDivId === 6) {
        await refreshDiv6WorkData();
        renderDiv6Work();
    }
    showToast(isEditing ? t('services.updatedToast', { name }) : t('services.addedToast', { name }), 'success');
}

async function deleteServiceItem(id) {
    customConfirm(t('services.deleteConfirm'), async () => {
        await api.deleteService(id);
        const data = await api.getServices();
        state.services = data.services;
        renderServicesList();
        if (state.activeDashboardDivId === 1) {
            await refreshDiv1WorkData();
            renderDiv1Work();
        } else if (state.activeDashboardDivId === 2) {
            await refreshDiv2WorkData();
            renderDiv2Work();
        } else if (state.activeDashboardDivId === 3) {
            await refreshDiv3WorkData();
            renderDiv3Work();
        } else if (state.activeDashboardDivId === 4) {
            await refreshDiv4WorkData();
            renderDiv4Work();
        } else if (state.activeDashboardDivId === 5) {
            await refreshDiv5WorkData();
            renderDiv5Work();
        } else if (state.activeDashboardDivId === 6) {
            await refreshDiv6WorkData();
            renderDiv6Work();
        }
        showToast(t('services.deletedToast'), 'info');
    });
}

async function initBoard(maintainFocus = false) {
    let focusedElementId = null;
    let focusedElementSelectionStart = 0;
    
    if (maintainFocus && document.activeElement && document.activeElement.tagName === 'INPUT') {
        focusedElementId = document.activeElement.dataset.inputId;
        focusedElementSelectionStart = document.activeElement.selectionStart;
    }

    const [data, ordersData] = await Promise.all([api.getBoard(), api.getExecutiveOrders()]);
    state.divisions = data.divisions;
    state.executiveOrders = ordersData.orders || [];
    await syncBoardHistoryState();
    
    renderBoard();
    updateGlobalHealth();

    if (state.activeDashboardDivId !== null) {
        if (state.activeDashboardDivId === 1) {
            await refreshDiv1WorkData();
            renderDiv1Work();
        } else if (state.activeDashboardDivId === 2) {
            await refreshDiv2WorkData();
            renderDiv2Work();
        } else if (state.activeDashboardDivId === 3) {
            await refreshDiv3WorkData();
            renderDiv3Work();
        } else if (state.activeDashboardDivId === 4) {
            await refreshDiv4WorkData();
            renderDiv4Work();
        } else if (state.activeDashboardDivId === 5) {
            await refreshDiv5WorkData();
            renderDiv5Work();
        } else if (state.activeDashboardDivId === 6) {
            await refreshDiv6WorkData();
            renderDiv6Work();
        } else if (state.activeDashboardDivId === 8) {
            await refreshEdWorkData();
            renderEdWork();
        } else if (state.activeDashboardDivId === 7) {
            await refreshDiv7WorkData();
            renderDiv7Work();
        }
        renderDashboardKanban(state.activeDashboardDivId);
    }

    if (maintainFocus && focusedElementId) {
        setTimeout(() => {
            const input = document.querySelector(`[data-input-id="${focusedElementId}"]`);
            if (input) {
                input.focus();
                input.setSelectionRange(focusedElementSelectionStart, focusedElementSelectionStart);
            }
        }, 10);
    }
}

// ====== CUSTOM MODALS ======
function customPrompt(title, placeholder, onConfirm) {
    document.getElementById('bpModalTitle').textContent = title;
    const input = document.getElementById('bpInputText');
    input.value = '';
    input.placeholder = placeholder;
    const modal = document.getElementById('bpInputModal');
    
    // Clear old listeners
    const confirmBtn = document.getElementById('confirmBpInputBtn');
    const newConfirm = confirmBtn.cloneNode(true);
    confirmBtn.parentNode.replaceChild(newConfirm, confirmBtn);
    
    newConfirm.addEventListener('click', () => {
        const val = input.value.trim();
        if (val) onConfirm(val);
        closeBpInputModal();
    });

    document.getElementById('cancelBpInputBtn').onclick = closeBpInputModal;
    document.getElementById('closeBpInputModal').onclick = closeBpInputModal;
    
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('.glass-panel').classList.remove('scale-95'); input.focus(); }, 10);
}

function closeBpInputModal() {
    const modal = document.getElementById('bpInputModal');
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => modal.classList.add('hidden'), 300);
}

function customConfirm(text, onConfirm) {
    document.getElementById('confirmModalText').textContent = text;
    const modal = document.getElementById('confirmModal');
    
    const confirmBtn = document.getElementById('acceptConfirmBtn');
    const newConfirm = confirmBtn.cloneNode(true);
    confirmBtn.parentNode.replaceChild(newConfirm, confirmBtn);
    
    newConfirm.addEventListener('click', () => {
        onConfirm();
        closeConfirmModal();
    });

    document.getElementById('cancelConfirmBtn').onclick = closeConfirmModal;
    
    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0'); modal.querySelector('.glass-panel').classList.remove('scale-95'); }, 10);
}

function closeConfirmModal() {
    const modal = document.getElementById('confirmModal');
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => modal.classList.add('hidden'), 300);
}
// ====== END CUSTOM MODALS ======
