function getDiv3CaseMeta(stage) {
    const map = {
        deposit_pending: { label: 'Deposit Pending', badge: 'border-amber-400/20 bg-amber-500/10 text-amber-100' },
        invoiced: { label: 'Invoiced', badge: 'border-blue-400/20 bg-blue-500/10 text-blue-100' },
        follow_up: { label: 'Follow-Up', badge: 'border-orange-400/20 bg-orange-500/10 text-orange-100' },
        paid: { label: 'Paid', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' },
        overdue: { label: 'Overdue', badge: 'border-red-400/20 bg-red-500/10 text-red-100' }
    };
    return map[stage] || map.deposit_pending;
}

function getDiv3InvoiceStatusMeta(status) {
    const map = {
        draft: { label: 'Draft', badge: 'border-white/10 bg-white/[0.03] text-gray-200' },
        sent: { label: 'Sent', badge: 'border-blue-400/20 bg-blue-500/10 text-blue-100' },
        paid: { label: 'Paid', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' }
    };
    return map[status] || map.draft;
}

function getDiv3WorkflowOptions() {
    return state.divisions
        .filter((div) => ![7, 8].includes(div.id))
        .flatMap((div) => (div.items || []).map((item) => ({
            id: item.id,
            divisionId: div.id,
            divisionName: getDivisionCopy(div).name,
            title: item.title
        })));
}

function resetDiv3InvoiceDraft() {
    state.div3EditingInvoiceId = null;
    state.div3InvoiceDraftLines = [{ description: '', amount: '' }];
}

function loadDiv3InvoiceDraft(invoice) {
    state.div3EditingInvoiceId = invoice.id;
    state.div3InvoiceDraftLines = (invoice.items || []).map((item) => ({
        description: item.description || '',
        amount: item.amount ?? ''
    }));
}

function renderDiv3InvoiceLineRows() {
    const container = document.getElementById('div3InvoiceLines');
    if (!container) return;
    container.innerHTML = state.div3InvoiceDraftLines.map((line, index) => `
        <div class="grid grid-cols-[1fr_120px_40px] gap-3 items-center">
            <input type="text" class="div3-line-input bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" data-line-index="${index}" data-field="description" value="${escapeAttr(line.description || '')}" placeholder="Line item description">
            <input type="number" step="0.01" min="0" class="div3-line-input bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" data-line-index="${index}" data-field="amount" value="${escapeAttr(line.amount || '')}" placeholder="0.00">
            <button class="div3-remove-line-btn h-11 rounded-xl border border-red-400/20 bg-red-500/10 text-red-200 hover:bg-red-500/20 transition" data-line-index="${index}">
                <i class="fas fa-times"></i>
            </button>
        </div>
    `).join('');

    container.querySelectorAll('.div3-line-input').forEach((input) => {
        input.addEventListener('input', () => {
            const index = Number(input.dataset.lineIndex);
            const field = input.dataset.field;
            if (!state.div3InvoiceDraftLines[index]) return;
            state.div3InvoiceDraftLines[index][field] = input.value;
            updateDiv3InvoiceDraftSummary();
        });
    });

    container.querySelectorAll('.div3-remove-line-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
            const index = Number(btn.dataset.lineIndex);
            state.div3InvoiceDraftLines.splice(index, 1);
            if (!state.div3InvoiceDraftLines.length) state.div3InvoiceDraftLines = [{ description: '', amount: '' }];
            renderDiv3InvoiceLineRows();
            updateDiv3InvoiceDraftSummary();
        });
    });
}

function updateDiv3InvoiceDraftSummary() {
    const subtotal = state.div3InvoiceDraftLines.reduce((sum, line) => sum + (Number(line.amount || 0) || 0), 0);
    const subtotalEl = document.getElementById('div3InvoiceSubtotal');
    const depositEl = document.getElementById('div3InvoiceSuggestedDeposit');
    if (subtotalEl) subtotalEl.textContent = formatServicePrice({ price: subtotal.toFixed(2), currency: document.getElementById('div3InvoiceCurrency')?.value || 'EUR' });
    if (depositEl) depositEl.textContent = formatServicePrice({ price: (subtotal / 2).toFixed(2), currency: document.getElementById('div3InvoiceCurrency')?.value || 'EUR' });
}

function renderDiv3Work() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 3 || !state.div3WorkData) return;

    const cases = state.div3WorkData.cases || [];
    const invoices = state.div3WorkData.invoices || [];
    const profile = state.div3WorkData.invoiceProfile || {};
    const openOrders = getTargetDivisionOrders(3, { includeDone: true });
    const workflowOptions = getDiv3WorkflowOptions();
    const linkedCaseMap = new Map(cases.filter((entry) => entry.item_id).map((entry) => [Number(entry.item_id), entry]));
    const overdueCases = cases.filter((entry) => entry.stage === 'overdue' || (entry.due_date && entry.stage !== 'paid' && entry.due_date < new Date().toISOString().slice(0, 10)));
    const openCases = cases.filter((entry) => entry.stage !== 'paid');
    const paidCases = cases.filter((entry) => entry.stage === 'paid');
    const subtotalOpen = openCases.reduce((sum, entry) => sum + Number(entry.amount_due || 0), 0);
    const subtotalPaid = paidCases.reduce((sum, entry) => sum + Number(entry.amount_due || 0), 0);
    const latestInvoiced = getLatestMetricValue(3, 'invoiced') ?? 0;
    const latestCollected = getLatestMetricValue(3, 'collected') ?? 0;
    const derivedInvoiced = invoices.reduce((sum, invoice) => sum + Number(invoice.subtotal || 0), 0);
    const derivedCollected = invoices.reduce((sum, invoice) => {
        if (invoice.status !== 'paid') return sum;
        return sum + Number(invoice.deposit_required || invoice.subtotal || 0);
    }, 0);
    const displayInvoiced = derivedInvoiced > 0 ? derivedInvoiced : latestInvoiced;
    const displayCollected = derivedCollected > 0 ? derivedCollected : latestCollected;
    const workTabs = [
        ['cashflow', 'Cashflow', 'fa-wallet'],
        ['collections', 'Collections', 'fa-file-invoice-dollar'],
        ['invoices', 'Invoice Maker', 'fa-receipt'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['handoffs', 'Handoffs', 'fa-right-left'],
        ['reserves', 'Reserves', 'fa-piggy-bank'],
        ['approvals', 'Approvals', 'fa-shield-halved']
    ];

    container.innerHTML = `
        <div class="flex flex-col gap-8">
            <section class="glass-panel rounded-[2rem] border border-white/10 bg-black/40 p-6">
                <div class="flex flex-col xl:flex-row xl:items-start xl:justify-between gap-6">
                    <div>
                        <p class="text-[11px] uppercase tracking-[0.28em] text-gray-500">Division 3 Work Console</p>
                        <h3 class="text-3xl font-bold text-white mt-2">Treasury, Collections, and Invoice Control</h3>
                        <p class="text-sm text-gray-400 mt-3 max-w-3xl">Division 3 converts closed work into protected cash. It owns invoice creation, deposit control, collection follow-up, and the visibility ED needs on money already promised versus money already received.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 min-w-0 xl:min-w-[420px]">
                        ${[
                            ['Invoiced', formatServicePrice({ price: displayInvoiced, currency: 'EUR' }), derivedInvoiced > 0 ? 'Derived from stored invoices.' : 'Real metrics total logged in Treasury.'],
                            ['Collected', formatServicePrice({ price: displayCollected, currency: 'EUR' }), derivedCollected > 0 ? 'Derived from paid invoice deposits.' : 'Cash confirmed in real metrics.'],
                            ['Open Cases', openCases.length, 'Cases still waiting on invoice or payment action.'],
                            ['Invoices', invoices.length, 'Invoices stored and attached to workflows.']
                        ].map(([label, value, body]) => `
                            <div class="rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-4">
                                <p class="text-[10px] uppercase tracking-[0.2em] text-gray-500">${label}</p>
                                <p class="text-2xl font-bold text-white mt-2">${escapeHtml(String(value))}</p>
                                <p class="text-xs text-gray-500 mt-2">${body}</p>
                            </div>
                        `).join('')}
                    </div>
                </div>
                <div class="flex flex-wrap gap-2 mt-6">
                    ${workTabs.map(([id, label, icon]) => `
                        <button class="div3-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeDiv3WorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-div3-work-tab="${id}">
                            <i class="fas ${icon} mr-2"></i>${label}
                        </button>
                    `).join('')}
                </div>
            </section>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'cashflow' ? '' : 'hidden'}" data-div3-work-panel="cashflow">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Cash Position</p>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-4">
                            ${[
                                ['Open Exposure', formatServicePrice({ price: subtotalOpen.toFixed(2), currency: 'EUR' }), 'Treasury cases still outstanding.'],
                                ['Paid Through Cases', formatServicePrice({ price: subtotalPaid.toFixed(2), currency: 'EUR' }), 'Confirmed paid cases tracked in Treasury.'],
                                ['Overdue Cases', overdueCases.length, 'Cases currently demanding collection pressure.'],
                                ['Deals Closed Upstream', getLatestMetricValue(2, 'deals') ?? 0, 'Closed demand coming from Div 2.']
                            ].map(([label, value, body]) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">${label}</p>
                                    <p class="text-2xl font-bold text-white mt-2">${escapeHtml(String(value))}</p>
                                    <p class="text-sm text-gray-400 mt-2">${body}</p>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Collection Reading</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${openCases.slice(0, 5).map((entry) => {
                                const stageMeta = getDiv3CaseMeta(entry.stage);
                                return `
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                        <div class="flex items-center justify-between gap-3">
                                            <h4 class="text-sm font-bold text-white">${escapeHtml(entry.client_name)}</h4>
                                            <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${stageMeta.badge}">${stageMeta.label}</span>
                                        </div>
                                        <p class="text-sm text-gray-400 mt-2">${entry.item_title ? `Linked to ${escapeHtml(entry.item_title)}.` : 'Not linked to a workflow yet.'} ${entry.due_date ? `Due ${escapeHtml(entry.due_date)}.` : 'No due date set.'}</p>
                                    </div>
                                `;
                            }).join('') || '<p class="text-sm text-gray-500">No open treasury cases yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'collections' ? '' : 'hidden'}" data-div3-work-panel="collections">
                <div class="grid grid-cols-1 xl:grid-cols-[0.9fr_1.25fr] gap-6">
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Treasury Case Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div3CaseItemId" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                <option value="">Link to workflow (optional)</option>
                                ${workflowOptions.map((option) => `<option value="${option.id}" data-client="${escapeAttr(option.title)}">${escapeHtml(option.divisionName)} · ${escapeHtml(option.title)}</option>`).join('')}
                            </select>
                            <input id="div3CaseClientName" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Client / case name">
                            <div class="grid grid-cols-2 gap-3">
                                <select id="div3CaseStage" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                    <option value="deposit_pending">Deposit Pending</option>
                                    <option value="invoiced">Invoiced</option>
                                    <option value="follow_up">Follow-Up</option>
                                    <option value="overdue">Overdue</option>
                                    <option value="paid">Paid</option>
                                </select>
                                <select id="div3CaseChannel" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="stripe">Stripe</option>
                                    <option value="cash">Cash</option>
                                    <option value="custom">Custom</option>
                                </select>
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3CaseAmountDue" type="number" step="0.01" min="0" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Amount due">
                                <input id="div3CaseDueDate" type="date" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                            </div>
                            <textarea id="div3CaseNotes" rows="4" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)] resize-y" placeholder="Payment notes, contact status, bank/payment details"></textarea>
                            <button id="createDiv3CaseBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Treasury Case</button>
                        </div>
                    </div>
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Collections Queue</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${cases.length ? cases.map((entry) => {
                                const stageMeta = getDiv3CaseMeta(entry.stage);
                                return `
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-5">
                                        <div class="flex flex-col md:flex-row md:items-start justify-between gap-4">
                                            <div>
                                                <div class="flex flex-wrap items-center gap-2">
                                                    <h4 class="text-lg font-bold text-white">${escapeHtml(entry.client_name)}</h4>
                                                    <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${stageMeta.badge}">${stageMeta.label}</span>
                                                    <span class="px-2 py-1 rounded-full bg-black/30 border border-white/10 text-[10px] uppercase tracking-[0.18em] text-gray-300">${escapeHtml(entry.channel.replace('_', ' '))}</span>
                                                </div>
                                                <p class="text-sm text-gray-300 mt-3">${escapeHtml(formatServicePrice({ price: Number(entry.amount_due || 0).toFixed(2), currency: 'EUR' }))}</p>
                                                <p class="text-sm text-gray-400 mt-2">${entry.item_title ? `Linked to ${escapeHtml(entry.item_title)}.` : 'No workflow link.'} ${entry.notes ? escapeHtml(entry.notes) : ''}</p>
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                ${entry.stage !== 'follow_up' ? `<button class="div3-case-stage-btn px-3 py-2 rounded-xl bg-orange-500/10 hover:bg-orange-500/20 border border-orange-400/20 text-xs text-orange-100" data-id="${entry.id}" data-stage="follow_up">Follow-Up</button>` : ''}
                                                ${entry.stage !== 'overdue' ? `<button class="div3-case-stage-btn px-3 py-2 rounded-xl bg-red-500/10 hover:bg-red-500/20 border border-red-400/20 text-xs text-red-100" data-id="${entry.id}" data-stage="overdue">Overdue</button>` : ''}
                                                ${entry.stage !== 'paid' ? `<button class="div3-case-stage-btn px-3 py-2 rounded-xl bg-emerald-500/10 hover:bg-emerald-500/20 border border-emerald-400/20 text-xs text-emerald-100" data-id="${entry.id}" data-stage="paid">Paid</button>` : ''}
                                                <button class="div3-case-delete-btn px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white" data-id="${entry.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No treasury cases yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'invoices' ? '' : 'hidden'}" data-div3-work-panel="invoices">
                <div class="grid grid-cols-1 xl:grid-cols-[0.82fr_1.18fr] gap-6">
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Invoice Profile</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <input id="div3ProfileDisplayName" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.display_name || '')}" placeholder="Display name / brand">
                            <input id="div3ProfileTagline" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.tagline || '')}" placeholder="Tagline">
                            <input id="div3ProfileLegalName" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.legal_name || '')}" placeholder="Legal name">
                            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                <div class="flex items-center justify-between gap-4">
                                    <div>
                                        <p class="text-sm font-semibold text-white">Invoice Logo</p>
                                        <p class="text-xs text-gray-500 mt-1">Upload once. It will be saved in the project root as <code>mine.*</code>.</p>
                                    </div>
                                    ${profile.logo_url ? `<img src="${escapeAttr(profile.logo_url)}" alt="Invoice logo" class="max-w-[120px] max-h-16 object-contain rounded-lg border border-white/10 bg-black/20 p-2">` : '<span class="text-xs text-gray-500">No logo uploaded</span>'}
                                </div>
                                <input id="div3ProfileLogoFile" type="file" accept="image/png,image/jpeg,image/webp,image/svg+xml" class="mt-4 block w-full text-sm text-gray-300 file:mr-4 file:rounded-xl file:border-0 file:bg-white/10 file:px-4 file:py-2 file:font-semibold file:text-white hover:file:bg-white/15">
                            </div>
                            <input id="div3ProfileAddress1" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.address_line1 || '')}" placeholder="Address line 1">
                            <input id="div3ProfileAddress2" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.address_line2 || '')}" placeholder="Address line 2">
                            <input id="div3ProfileCityLine" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.city_postcode_country || '')}" placeholder="City / postcode">
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3ProfileCountry" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.country || '')}" placeholder="Country">
                                <input id="div3ProfileWebsite" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.website || '')}" placeholder="Website">
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3ProfileUTR" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.utr || '')}" placeholder="UTR / Tax ID">
                                <input id="div3ProfileNationalId" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.national_id || '')}" placeholder="National Insurance / Extra ID">
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3ProfileBankHolder" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.bank_holder || '')}" placeholder="Bank account holder">
                                <input id="div3ProfileBankAccount" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.bank_account || '')}" placeholder="Bank account / IBAN">
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3ProfileBankSwift" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.bank_swift || '')}" placeholder="SWIFT">
                                <input id="div3ProfileBankBic" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(profile.bank_bic || '')}" placeholder="BIC">
                            </div>
                            <textarea id="div3ProfileBankAddress" rows="3" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)] resize-y" placeholder="Bank address">${escapeHtml(profile.bank_address || '')}</textarea>
                            <button id="saveDiv3InvoiceProfileBtn" class="mt-2 px-5 py-3 rounded-xl bg-white/10 text-white font-bold hover:bg-white/15 transition">Save Invoice Profile</button>
                        </div>
                    </div>
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <div class="flex items-center justify-between gap-4">
                            <div>
                                <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Invoice Maker</p>
                                <p class="text-sm text-gray-400">Create invoices attached to a specific workflow/client, then open the printable invoice layout in a new tab.</p>
                            </div>
                            ${state.div3EditingInvoiceId ? `<button id="div3CancelInvoiceEditBtn" class="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white">Cancel Edit</button>` : ''}
                        </div>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div3InvoiceItemId" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                <option value="">Attach to workflow/client</option>
                                ${workflowOptions.map((option) => `<option value="${option.id}" ${state.div3EditingInvoiceId && invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.item_id === option.id ? 'selected' : ''}>${escapeHtml(option.divisionName)} · ${escapeHtml(option.title)}</option>`).join('')}
                            </select>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3InvoiceClientName" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Client name" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.client_name || '') : '')}">
                                <input id="div3InvoiceNumber" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Invoice number" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.invoice_number || '') : '')}">
                            </div>
                            <textarea id="div3InvoiceClientAddress" rows="3" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)] resize-y" placeholder="Client address">${escapeHtml(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.client_address || '') : '')}</textarea>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3InvoiceClientTaxId" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Client tax ID / VAT" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.client_tax_id || '') : '')}">
                                <input id="div3InvoiceClientCode" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Client code / SDI" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.client_code || '') : '')}">
                            </div>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div3InvoiceDate" type="date" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.invoice_date || '') : new Date().toISOString().slice(0, 10))}">
                                <input id="div3InvoiceDueDate" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Due date text" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.due_date || '') : 'Upon Completion')}">
                            </div>
                            <div class="grid grid-cols-3 gap-3">
                                <select id="div3InvoiceCurrency" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                    ${['EUR', 'GBP', 'USD', 'CAD'].map((currency) => `<option value="${currency}" ${(state.div3EditingInvoiceId ? invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.currency : 'EUR') === currency ? 'selected' : ''}>${currency}</option>`).join('')}
                                </select>
                                <input id="div3InvoiceDeposit" type="number" step="0.01" min="0" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Deposit required" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.deposit_required || '') : '')}">
                                <select id="div3InvoiceStatus" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                    ${['draft', 'sent', 'paid'].map((status) => `<option value="${status}" ${(state.div3EditingInvoiceId ? invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.status : 'draft') === status ? 'selected' : ''}>${status}</option>`).join('')}
                                </select>
                            </div>
                            <input id="div3InvoicePaymentReference" type="text" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]" placeholder="Payment reference" value="${escapeAttr(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.payment_reference || '') : '')}">
                            <textarea id="div3InvoiceTerms" rows="4" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)] resize-y" placeholder="One term per line">${escapeHtml(state.div3EditingInvoiceId ? (invoices.find((invoice) => invoice.id === state.div3EditingInvoiceId)?.terms || '') : '')}</textarea>
                            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                <div class="flex items-center justify-between gap-3 mb-4">
                                    <p class="text-sm font-semibold text-white">Line Items</p>
                                    <button id="div3AddInvoiceLineBtn" class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white">Add Line</button>
                                </div>
                                <div id="div3InvoiceLines" class="flex flex-col gap-3"></div>
                                <div class="grid grid-cols-2 gap-3 mt-4">
                                    <div class="rounded-xl border border-white/10 bg-black/30 px-4 py-3">
                                        <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Subtotal</p>
                                        <p id="div3InvoiceSubtotal" class="text-lg font-bold text-white mt-2">${escapeHtml(formatServicePrice({ price: '0.00', currency: 'EUR' }))}</p>
                                    </div>
                                    <div class="rounded-xl border border-white/10 bg-black/30 px-4 py-3">
                                        <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Suggested 50% Deposit</p>
                                        <p id="div3InvoiceSuggestedDeposit" class="text-lg font-bold text-white mt-2">${escapeHtml(formatServicePrice({ price: '0.00', currency: 'EUR' }))}</p>
                                    </div>
                                </div>
                            </div>
                            <button id="saveDiv3InvoiceBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">${state.div3EditingInvoiceId ? 'Update Invoice' : 'Create Invoice'}</button>
                        </div>
                        <div class="mt-6 flex flex-col gap-4">
                            ${invoices.length ? invoices.map((invoice) => {
                                const meta = getDiv3InvoiceStatusMeta(invoice.status);
                                return `
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-5">
                                        <div class="flex flex-col md:flex-row md:items-start justify-between gap-4">
                                            <div>
                                                <div class="flex flex-wrap items-center gap-2">
                                                    <h4 class="text-lg font-bold text-white">${escapeHtml(invoice.invoice_number)}</h4>
                                                    <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${meta.badge}">${meta.label}</span>
                                                </div>
                                                <p class="text-sm text-gray-300 mt-3">${escapeHtml(invoice.client_name)}${invoice.item_title ? ` · linked to ${escapeHtml(invoice.item_title)}` : ''}</p>
                                                <p class="text-sm text-gray-400 mt-2">${escapeHtml(formatServicePrice({ price: Number(invoice.subtotal || 0).toFixed(2), currency: invoice.currency || 'EUR' }))} subtotal · ${escapeHtml(invoice.due_date || '')}</p>
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                <button class="div3-print-invoice-btn px-3 py-2 rounded-xl bg-blue-500/10 hover:bg-blue-500/20 border border-blue-400/20 text-xs text-blue-100" data-id="${invoice.id}">Print</button>
                                                <button class="div3-edit-invoice-btn px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white" data-id="${invoice.id}">Edit</button>
                                                <button class="div3-delete-invoice-btn px-3 py-2 rounded-xl bg-red-500/10 hover:bg-red-500/20 border border-red-400/20 text-xs text-red-100" data-id="${invoice.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No invoices created yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'battleplans' ? '' : 'hidden'}" data-div3-work-panel="battleplans">
                <div class="glass-panel p-4 mb-6 rounded-xl border border-white/5 bg-black/40 flex flex-wrap items-center gap-4 justify-between shadow-lg">
                    <div>
                        <div class="flex items-center gap-2 text-purple-400 font-bold"><i class="fas fa-magic"></i> Division 3 Strat-Gen</div>
                        <p class="text-sm text-gray-400 mt-1">Use this to set deposit discipline, invoice cadence, and reserve protection priorities.</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <button class="div3-ai-bp-gen-btn bg-white/5 hover:bg-white/10 text-gray-300 px-4 py-2 rounded-lg text-sm font-medium transition flex items-center gap-2" data-period="yearly"><i class="fas fa-calendar"></i> Yearly</button>
                        <button class="div3-ai-bp-gen-btn bg-white/5 hover:bg-white/10 text-gray-300 px-4 py-2 rounded-lg text-sm font-medium transition flex items-center gap-2" data-period="monthly"><i class="fas fa-calendar-alt"></i> Monthly</button>
                        <button class="div3-ai-bp-gen-btn bg-white/5 hover:bg-white/10 text-gray-300 px-4 py-2 rounded-lg text-sm font-medium transition flex items-center gap-2" data-period="weekly"><i class="fas fa-calendar-week"></i> Weekly</button>
                        <button class="div3-ai-bp-gen-btn bg-[var(--dash-accent)] text-white px-4 py-2 rounded-lg text-sm font-bold shadow-[0_0_15px_var(--dash-accent)] hover:brightness-110 transition flex items-center gap-2" data-period="daily"><i class="fas fa-bolt"></i> Generate Daily Tasks</button>
                    </div>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6" id="div3BattlePlanGrid"></div>
            </div>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'handoffs' ? '' : 'hidden'}" data-div3-work-panel="handoffs">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Upstream Sales Handoffs</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${getDivisionItems(2).map((item) => {
                                const linkedCase = linkedCaseMap.get(item.id);
                                return `
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                        <div class="flex items-center justify-between gap-3">
                                            <h4 class="text-sm font-bold text-white">${escapeHtml(item.title)}</h4>
                                            <span class="text-xs ${linkedCase ? 'text-emerald-200' : 'text-amber-200'}">${linkedCase ? getDiv3CaseMeta(linkedCase.stage).label : 'No treasury case yet'}</span>
                                        </div>
                                        <p class="text-sm text-gray-400 mt-2">${linkedCase ? `Treasury case linked for ${escapeHtml(linkedCase.client_name)}.` : 'This closed demand still needs a treasury case / invoice decision.'}</p>
                                    </div>
                                `;
                            }).join('') || '<p class="text-sm text-gray-500">No active Div 2 workflows.</p>'}
                        </div>
                    </div>
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Downstream Delivery Protection</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${getDivisionItems(4).map((item) => {
                                const linkedCase = linkedCaseMap.get(item.id);
                                return `
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                        <div class="flex items-center justify-between gap-3">
                                            <h4 class="text-sm font-bold text-white">${escapeHtml(item.title)}</h4>
                                            <span class="text-xs ${linkedCase && linkedCase.stage === 'paid' ? 'text-emerald-200' : 'text-amber-200'}">${linkedCase ? getDiv3CaseMeta(linkedCase.stage).label : 'No linked payment case'}</span>
                                        </div>
                                        <p class="text-sm text-gray-400 mt-2">${linkedCase && linkedCase.stage === 'paid' ? 'Treasury shows payment confirmed for this workflow.' : 'Delivery should not outrun treasury control on this workflow.'}</p>
                                    </div>
                                `;
                            }).join('') || '<p class="text-sm text-gray-500">No active Div 4 workflows.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'reserves' ? '' : 'hidden'}" data-div3-work-panel="reserves">
                <div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
                        ${[
                            ['Visible Invoiced', displayInvoiced, derivedInvoiced > 0 ? 'Using invoice-derived value until manual metrics catch up.' : 'Current Treasury metric for invoiced amount.'],
                            ['Visible Collected', displayCollected, derivedCollected > 0 ? 'Using paid invoice deposits until manual metrics catch up.' : 'Current Treasury metric for collected amount.'],
                            ['Gap', displayInvoiced - displayCollected, 'Difference between invoiced and collected visibility.']
                        ].map(([label, value, body]) => `
                        <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 p-5">
                            <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">${label}</p>
                            <p class="text-3xl font-bold text-white mt-3">${escapeHtml(formatServicePrice({ price: Number(value || 0).toFixed(2), currency: 'EUR' }))}</p>
                            <p class="text-sm text-gray-400 mt-2">${body}</p>
                        </div>
                    `).join('')}
                </div>
                <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6 mt-6">
                    <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Reserve Reading</p>
                    <p class="text-sm text-gray-400 mt-4">Use this to keep Treasury honest: what has been invoiced, what has actually been collected, and what exposure is still floating in follow-up or overdue status.</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-5">
                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Open Exposure From Cases</p>
                            <p class="text-xl font-bold text-white mt-2">${escapeHtml(formatServicePrice({ price: subtotalOpen.toFixed(2), currency: 'EUR' }))}</p>
                        </div>
                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Paid Through Cases</p>
                            <p class="text-xl font-bold text-white mt-2">${escapeHtml(formatServicePrice({ price: subtotalPaid.toFixed(2), currency: 'EUR' }))}</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="div3-work-panel ${state.activeDiv3WorkTab === 'approvals' ? '' : 'hidden'}" data-div3-work-panel="approvals">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Incoming Executive Orders</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${openOrders.length ? openOrders.map((order) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-5">
                                    <div class="flex flex-wrap items-center gap-2">
                                        <h4 class="text-lg font-bold text-white">${escapeHtml(order.title)}</h4>
                                        <span class="px-2 py-1 rounded-full bg-black/30 border border-white/10 text-[10px] uppercase tracking-[0.18em] text-gray-300">${escapeHtml(String(order.status).replace('_', ' '))}</span>
                                    </div>
                                    <p class="text-sm text-gray-400 mt-3">${escapeHtml(order.body || '')}</p>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No ED orders currently assigned to Treasury.</p>'}
                        </div>
                    </div>
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Approval / Control Gaps</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${[
                                { label: 'Treasury metric logged today', ok: getDivisionMetricStatus(3) === 'Current', body: getDivisionMetricStatus(3) === 'Current' ? 'Div 3 metrics are current today.' : 'Div 3 metrics are missing today.' },
                                { label: 'Open cases all linked', ok: openCases.every((entry) => entry.item_id), body: openCases.every((entry) => entry.item_id) ? 'Every open case is attached to a workflow/client.' : 'Some open cases are not attached to a workflow yet.' },
                                { label: 'Invoices have profile data', ok: !invoices.length || !!(profile.legal_name && profile.bank_account), body: !invoices.length || !!(profile.legal_name && profile.bank_account) ? 'Invoice profile is ready.' : 'Invoice profile still lacks legal/bank details.' },
                                { label: 'Overdue pressure contained', ok: overdueCases.length === 0, body: overdueCases.length === 0 ? 'No overdue cases right now.' : `${overdueCases.length} overdue case(s) need collection action.` }
                            ].map((check) => `
                                <div class="rounded-2xl border ${check.ok ? 'border-emerald-400/20 bg-emerald-500/5' : 'border-amber-400/20 bg-amber-500/5'} p-4">
                                    <div class="flex items-center justify-between gap-3">
                                        <p class="text-sm font-semibold text-white">${check.label}</p>
                                        <span class="text-xs ${check.ok ? 'text-emerald-200' : 'text-amber-200'}">${check.ok ? 'Stable' : 'Needs attention'}</span>
                                    </div>
                                    <p class="text-sm text-gray-400 mt-2">${check.body}</p>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    container.querySelectorAll('[data-div3-work-tab]').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeDiv3WorkTab = btn.dataset.div3WorkTab;
            renderDiv3Work();
        });
    });

    document.getElementById('div3CaseItemId')?.addEventListener('change', (event) => {
        const option = event.target.selectedOptions?.[0];
        const nameInput = document.getElementById('div3CaseClientName');
        if (option?.dataset?.client && nameInput && !nameInput.value.trim()) nameInput.value = option.dataset.client;
    });

    document.getElementById('createDiv3CaseBtn')?.addEventListener('click', async () => {
        const clientName = document.getElementById('div3CaseClientName')?.value.trim();
        if (!clientName) return showToast('Client name is required for a treasury case.', 'warning');
        await api.addTreasuryCase({
            division_id: 3,
            item_id: document.getElementById('div3CaseItemId')?.value || null,
            client_name: clientName,
            stage: document.getElementById('div3CaseStage')?.value || 'deposit_pending',
            channel: document.getElementById('div3CaseChannel')?.value || 'bank_transfer',
            amount_due: document.getElementById('div3CaseAmountDue')?.value || 0,
            due_date: document.getElementById('div3CaseDueDate')?.value || '',
            notes: document.getElementById('div3CaseNotes')?.value || ''
        });
        await refreshDiv3WorkData();
        await refreshDiv2WorkData();
        renderDiv3Work();
        showToast('Treasury case created.', 'success');
    });

    container.querySelectorAll('.div3-case-stage-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.updateTreasuryCase(btn.dataset.id, { stage: btn.dataset.stage });
            await refreshDiv3WorkData();
            await refreshDiv2WorkData();
            renderDiv3Work();
        });
    });

    container.querySelectorAll('.div3-case-delete-btn').forEach((btn) => {
        btn.addEventListener('click', () => customConfirm('Delete this treasury case?', async () => {
            await api.deleteTreasuryCase(btn.dataset.id);
            await refreshDiv3WorkData();
            await refreshDiv2WorkData();
            renderDiv3Work();
        }));
    });

    document.getElementById('saveDiv3InvoiceProfileBtn')?.addEventListener('click', async () => {
        await api.saveInvoiceProfile({
            display_name: document.getElementById('div3ProfileDisplayName')?.value || '',
            tagline: document.getElementById('div3ProfileTagline')?.value || '',
            legal_name: document.getElementById('div3ProfileLegalName')?.value || '',
            address_line1: document.getElementById('div3ProfileAddress1')?.value || '',
            address_line2: document.getElementById('div3ProfileAddress2')?.value || '',
            city_postcode_country: document.getElementById('div3ProfileCityLine')?.value || '',
            country: document.getElementById('div3ProfileCountry')?.value || '',
            website: document.getElementById('div3ProfileWebsite')?.value || '',
            utr: document.getElementById('div3ProfileUTR')?.value || '',
            national_id: document.getElementById('div3ProfileNationalId')?.value || '',
            bank_holder: document.getElementById('div3ProfileBankHolder')?.value || '',
            bank_account: document.getElementById('div3ProfileBankAccount')?.value || '',
            bank_swift: document.getElementById('div3ProfileBankSwift')?.value || '',
            bank_bic: document.getElementById('div3ProfileBankBic')?.value || '',
            bank_address: document.getElementById('div3ProfileBankAddress')?.value || ''
        });
        await refreshDiv3WorkData();
        renderDiv3Work();
        showToast('Invoice profile saved.', 'success');
    });

    document.getElementById('div3ProfileLogoFile')?.addEventListener('change', async (event) => {
        const file = event.target.files?.[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = async () => {
            try {
                await api.uploadInvoiceLogo(reader.result);
                await refreshDiv3WorkData();
                renderDiv3Work();
                showToast('Invoice logo uploaded.', 'success');
            } catch (error) {
                showToast(error.message || 'Invoice logo upload failed.', 'error');
            }
        };
        reader.readAsDataURL(file);
    });

    document.getElementById('div3InvoiceItemId')?.addEventListener('change', (event) => {
        const selected = workflowOptions.find((option) => String(option.id) === event.target.value);
        const clientNameInput = document.getElementById('div3InvoiceClientName');
        if (selected && clientNameInput && !clientNameInput.value.trim()) clientNameInput.value = selected.title;
    });
    document.getElementById('div3AddInvoiceLineBtn')?.addEventListener('click', () => {
        state.div3InvoiceDraftLines.push({ description: '', amount: '' });
        renderDiv3InvoiceLineRows();
        updateDiv3InvoiceDraftSummary();
    });
    document.getElementById('div3InvoiceCurrency')?.addEventListener('change', updateDiv3InvoiceDraftSummary);
    document.getElementById('div3CancelInvoiceEditBtn')?.addEventListener('click', () => {
        resetDiv3InvoiceDraft();
        renderDiv3Work();
    });
    document.getElementById('saveDiv3InvoiceBtn')?.addEventListener('click', async () => {
        const items = state.div3InvoiceDraftLines
            .map((line) => ({ description: String(line.description || '').trim(), amount: Number(line.amount || 0) }))
            .filter((line) => line.description);
        const clientName = document.getElementById('div3InvoiceClientName')?.value.trim();
        if (!clientName || !items.length) return showToast('Client name and at least one invoice line are required.', 'warning');
        const payload = {
            division_id: 3,
            item_id: document.getElementById('div3InvoiceItemId')?.value || null,
            client_name: clientName,
            client_address: document.getElementById('div3InvoiceClientAddress')?.value || '',
            client_tax_id: document.getElementById('div3InvoiceClientTaxId')?.value || '',
            client_code: document.getElementById('div3InvoiceClientCode')?.value || '',
            invoice_number: document.getElementById('div3InvoiceNumber')?.value || '',
            invoice_date: document.getElementById('div3InvoiceDate')?.value || '',
            due_date: document.getElementById('div3InvoiceDueDate')?.value || '',
            currency: document.getElementById('div3InvoiceCurrency')?.value || 'EUR',
            deposit_required: document.getElementById('div3InvoiceDeposit')?.value || '',
            payment_reference: document.getElementById('div3InvoicePaymentReference')?.value || '',
            terms: document.getElementById('div3InvoiceTerms')?.value || '',
            status: document.getElementById('div3InvoiceStatus')?.value || 'draft',
            items
        };
        if (state.div3EditingInvoiceId) {
            await api.updateInvoice(state.div3EditingInvoiceId, payload);
            showToast('Invoice updated.', 'success');
        } else {
            await api.addInvoice(payload);
            showToast('Invoice created.', 'success');
        }
        resetDiv3InvoiceDraft();
        await refreshDiv3WorkData();
        renderDiv3Work();
    });

    container.querySelectorAll('.div3-print-invoice-btn').forEach((btn) => {
        btn.addEventListener('click', () => window.open(`/invoices/${btn.dataset.id}/print`, '_blank', 'noopener'));
    });
    container.querySelectorAll('.div3-edit-invoice-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
            const invoice = invoices.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!invoice) return;
            loadDiv3InvoiceDraft(invoice);
            state.activeDiv3WorkTab = 'invoices';
            renderDiv3Work();
        });
    });
    container.querySelectorAll('.div3-delete-invoice-btn').forEach((btn) => {
        btn.addEventListener('click', () => customConfirm('Delete this invoice?', async () => {
            await api.deleteInvoice(btn.dataset.id);
            resetDiv3InvoiceDraft();
            await refreshDiv3WorkData();
            renderDiv3Work();
        }));
    });

    renderDiv3InvoiceLineRows();
    updateDiv3InvoiceDraftSummary();
    renderBattlePlan(3, {
        containerId: 'div3BattlePlanGrid',
        aiButtonsSelector: '#dashboardWorkView .div3-ai-bp-gen-btn'
    });
}
