function getDiv2OfferAngle(service) {
    if ((service.name || '').toLowerCase().includes('automation')) return 'Lead with wasted time, repetitive manual work, and the ROI of automation.';
    if ((service.name || '').toLowerCase().includes('support')) return 'Lead with retention, uptime, and the safety of ongoing support.';
    return 'Lead with visibility, trust, and conversion improvement.';
}

function getDiv2CampaignSuggestion(record) {
    if (record.divisionId === 2) return 'Push the lead forward to a call, proposal, or clear next step.';
    if (record.divisionId === 3) return 'Make sure the closed sale has converted into deposit and invoice action.';
    if (record.divisionId === 4) return 'Use completed delivery to generate proof, case study material, or referral fuel.';
    if (record.divisionId === 6) return 'Convert satisfaction into reviews, referrals, and repeat demand.';
    return 'Keep dissemination connected to the live org flow.';
}

function renderDiv2Work() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 2 || !state.div2WorkData) return;

    const briefs = state.div2WorkData.briefs || [];
    const activeBriefs = briefs.filter((brief) => brief.status === 'active');
    const treasuryCases = state.div2WorkData.treasuryCases || [];
    const services = state.services || [];
    const allRecords = getAllActiveWorkflowRecords().filter((record) => record.item?.title !== '⚡ Executive Orders');
    const disseminationRecords = allRecords.filter((record) => [2, 3, 4, 6].includes(record.divisionId));
    const followupRecords = disseminationRecords
        .sort((a, b) => b.pendingTodos.length - a.pendingTodos.length || a.divisionId - b.divisionId)
        .slice(0, 8);
    const pipelineCards = [
        ['Leads Generated', getLatestMetricValue(2, 'leads') ?? 0, 'Top-of-funnel volume created by Dissemination.'],
        ['Calls Made', getLatestMetricValue(2, 'calls') ?? 0, 'Discovery / qualification motion currently in play.'],
        ['Deals Closed', getLatestMetricValue(2, 'deals') ?? 0, 'Demand converted into real business.'],
        ['Active Briefs', activeBriefs.length, 'Campaign or offer briefs currently live.']
    ];
    const workTabs = [
        ['pipeline', 'Pipeline', 'fa-filter-circle-dollar'],
        ['offers', 'Offers', 'fa-tags'],
        ['campaigns', 'Campaigns', 'fa-bullhorn'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['followups', 'Follow-Ups', 'fa-reply'],
        ['handoffs', 'Handoffs', 'fa-right-left'],
        ['scene', 'Scene', 'fa-satellite-dish']
    ];

    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 2 Work Console</p>
                        <h3 class="text-3xl font-bold text-white mt-2">Dissemination, Offers, and Demand Flow</h3>
                        <p class="text-sm text-gray-400 mt-3 max-w-3xl">Division 2 exists to create and move demand. It owns offers, campaign angles, follow-up pressure, and the commercial handoff from scene to treasury and delivery reality.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 min-w-0 xl:min-w-[420px]">
                        ${pipelineCards.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">${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="div2-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeDiv2WorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-div2-work-tab="${id}">
                            <i class="fas ${icon} mr-2"></i>${label}
                        </button>
                    `).join('')}
                </div>
            </section>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'pipeline' ? '' : 'hidden'}" data-div2-work-panel="pipeline">
                <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">Demand Reading</p>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-4">
                            ${[
                                ['MRR', getLatestMetricValue(8, 'mrr') ?? 0, 'Executive top-line signal tied to dissemination quality.'],
                                ['Amount Collected', getLatestMetricValue(3, 'collected') ?? 0, 'Whether closed business is converting into cash.'],
                                ['Reviews Obtained', getLatestMetricValue(6, 'reviews') ?? 0, 'Scene proof generated from completed work.'],
                                ['Active Workflows', getDivisionItems(2).length, 'Live dissemination cards in motion.']
                            ].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">${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">Scene Pulse</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${followupRecords.slice(0, 4).map((record) => `
                                <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(record.item.title)}</h4>
                                        <span class="text-xs text-indigo-200">${escapeHtml(record.divisionName)}</span>
                                    </div>
                                    <p class="text-sm text-gray-400 mt-2">${getDiv2CampaignSuggestion(record)}</p>
                                </div>
                            `).join('') || '<p class="text-sm text-gray-500">No live demand pulse yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'offers' ? '' : 'hidden'}" data-div2-work-panel="offers">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
                    ${services.length ? services.map((service) => `
                        <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                            <div class="flex items-start justify-between gap-4">
                                <div>
                                    <h4 class="text-xl font-bold text-white">${escapeHtml(service.name)}</h4>
                                    <p class="text-sm text-gray-400 mt-2">${escapeHtml(service.description || '')}</p>
                                </div>
                                <div class="text-right">
                                    <p class="text-2xl font-bold text-white">${escapeHtml(formatServicePrice(service))}</p>
                                    <p class="text-xs text-gray-500 mt-1">${escapeHtml((service.currency || 'EUR').toUpperCase())}</p>
                                </div>
                            </div>
                            <div class="mt-4 grid grid-cols-1 gap-3">
                                <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">Ideal client</p>
                                    <p class="text-sm text-gray-300 mt-2">${escapeHtml(service.ideal_client || '')}</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">Angle</p>
                                    <p class="text-sm text-gray-300 mt-2">${getDiv2OfferAngle(service)}</p>
                                </div>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No services loaded yet.</p>'}
                </div>
            </div>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'campaigns' ? '' : 'hidden'}" data-div2-work-panel="campaigns">
                <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">Campaign Brief Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <input id="div2BriefTitle" 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="Brief title">
                            <select id="div2BriefType" 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="campaign">Campaign</option>
                                <option value="offer">Offer</option>
                                <option value="channel">Channel</option>
                            </select>
                            <select id="div2BriefStatus" 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="active" selected>Active</option>
                                <option value="draft">Draft</option>
                                <option value="archived">Archived</option>
                            </select>
                            <textarea id="div2BriefAngle" 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="Primary angle / hook"></textarea>
                            <textarea id="div2BriefNotes" 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="Notes, CTA, channel plan, ICP"></textarea>
                            <button id="createDiv2BriefBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Brief</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">Campaign Brief Library</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${briefs.length ? briefs.map((brief) => `
                                <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(brief.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(brief.brief_type)}</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(brief.status)}</span>
                                            </div>
                                            <p class="text-sm text-gray-300 mt-3"><span class="text-gray-500">Angle:</span> ${escapeHtml(brief.angle || '')}</p>
                                            <p class="text-sm text-gray-400 mt-2">${escapeHtml(brief.notes || '')}</p>
                                        </div>
                                        <div class="flex flex-wrap gap-2 shrink-0">
                                            ${brief.status !== 'active' ? `<button class="div2-brief-status-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="${brief.id}" data-status="active">Activate</button>` : ''}
                                            ${brief.status !== 'draft' ? `<button class="div2-brief-status-btn px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white" data-id="${brief.id}" data-status="draft">Draft</button>` : ''}
                                            ${brief.status !== 'archived' ? `<button class="div2-brief-status-btn px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white" data-id="${brief.id}" data-status="archived">Archive</button>` : ''}
                                            <button class="div2-brief-delete-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-200" data-id="${brief.id}">Delete</button>
                                        </div>
                                    </div>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No campaign briefs yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'battleplans' ? '' : 'hidden'}" data-div2-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 2 Strat-Gen</div>
                        <p class="text-sm text-gray-400 mt-1">Use this to drive campaigns, follow-up cadence, and lead-to-cash momentum.</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <button class="div2-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="div2-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="div2-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="div2-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="div2BattlePlanGrid"></div>
            </div>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'followups' ? '' : 'hidden'}" data-div2-work-panel="followups">
                <div class="grid grid-cols-1 gap-4">
                    ${followupRecords.length ? followupRecords.map((record) => `
                        <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 p-5">
                            <div class="flex flex-col md:flex-row md:items-start justify-between gap-4">
                                <div>
                                    <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">${escapeHtml(record.divisionName)}</p>
                                    <h4 class="text-xl font-bold text-white mt-2">${escapeHtml(record.item.title)}</h4>
                                    <p class="text-sm text-gray-400 mt-3">${getDiv2CampaignSuggestion(record)}</p>
                                    <div class="mt-3 flex flex-wrap gap-2">
                                        ${record.pendingTodos.slice(0, 4).map((todo) => `<span class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-gray-300">${escapeHtml(todo.text)}</span>`).join('') || '<span class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-gray-500">No pending tasks on this workflow.</span>'}
                                    </div>
                                </div>
                                <button class="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white div2-open-division-btn" data-division="${record.divisionId}">Open ${escapeHtml(record.divisionName)}</button>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No follow-up queue right now.</p>'}
                </div>
            </div>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'handoffs' ? '' : 'hidden'}" data-div2-work-panel="handoffs">
                <div class="grid grid-cols-1 xl:grid-cols-3 gap-4">
                    ${[3, 4, 6].map((divId) => {
                        const div = getDivisionById(divId);
                        const titles = getDivisionWorkflowTitles(divId, 4);
                        const treasuryPreview = divId === 3
                            ? treasuryCases.slice(0, 4).map((entry) => `
                                <div class="rounded-xl bg-white/[0.03] border border-white/10 px-3 py-2 text-sm text-gray-200">
                                    <div class="flex items-center justify-between gap-3">
                                        <span>${escapeHtml(entry.client_name)}</span>
                                        <span class="text-[10px] uppercase tracking-[0.18em] text-gray-400">${escapeHtml(String(entry.stage || '').replaceAll('_', ' '))}</span>
                                    </div>
                                </div>
                            `).join('')
                            : '';
                        return `
                            <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 p-5">
                                <div class="flex items-center justify-between gap-3">
                                    <h4 class="text-lg font-bold text-white">${escapeHtml(getDivisionCopy(div).name)}</h4>
                                    <button class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white div2-open-division-btn" data-division="${divId}">Open</button>
                                </div>
                                <p class="text-sm text-gray-400 mt-3">${divId === 3 ? 'Sales-to-cash handoff.' : divId === 4 ? 'Promise-to-delivery handoff.' : 'Success-to-proof handoff.'}</p>
                                <div class="mt-4 flex flex-col gap-2">
                                    ${divId === 3
                                        ? (treasuryPreview || '<p class="text-sm text-gray-500">No treasury cases yet.</p>')
                                        : (titles.length ? titles.map((title) => `<div class="rounded-xl bg-white/[0.03] border border-white/10 px-3 py-2 text-sm text-gray-200">${escapeHtml(title)}</div>`).join('') : '<p class="text-sm text-gray-500">No active workflows.</p>')}
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            </div>

            <div class="div2-work-panel ${state.activeDiv2WorkTab === 'scene' ? '' : 'hidden'}" data-div2-work-panel="scene">
                <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">Active Scene Assets</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${activeBriefs.length ? activeBriefs.map((brief) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <h4 class="text-sm font-bold text-white">${escapeHtml(brief.title)}</h4>
                                    <p class="text-sm text-gray-400 mt-2">${escapeHtml(brief.angle || '')}</p>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No active scene briefs yet.</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">Scene Reading</p>
                        <p class="text-sm text-gray-400 mt-4">This tab should tell you whether market attention is being created, whether offers are clear enough to close, and whether completed work is feeding the next wave of demand through proof and referrals.</p>
                        <div class="mt-5 flex flex-col gap-3">
                            ${services.slice(0, 3).map((service) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <h4 class="text-sm font-bold text-white">${escapeHtml(service.name)}</h4>
                                    <p class="text-sm text-gray-400 mt-2">${getDiv2OfferAngle(service)}</p>
                                </div>
                            `).join('') || '<p class="text-sm text-gray-500">No service catalog loaded yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    container.querySelectorAll('[data-div2-work-tab]').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeDiv2WorkTab = btn.dataset.div2WorkTab;
            renderDiv2Work();
        });
    });
    container.querySelectorAll('.div2-open-division-btn').forEach((btn) => {
        btn.addEventListener('click', () => openDashboard(Number(btn.dataset.division)));
    });
    container.querySelectorAll('.div2-brief-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.updateCampaignBrief(btn.dataset.id, { status: btn.dataset.status });
            await refreshDiv2WorkData();
            renderDiv2Work();
        });
    });
    container.querySelectorAll('.div2-brief-delete-btn').forEach((btn) => {
        btn.addEventListener('click', () => customConfirm('Delete this campaign brief?', async () => {
            await api.deleteCampaignBrief(btn.dataset.id);
            await refreshDiv2WorkData();
            renderDiv2Work();
        }));
    });

    document.getElementById('createDiv2BriefBtn')?.addEventListener('click', async () => {
        const title = document.getElementById('div2BriefTitle')?.value.trim();
        const briefType = document.getElementById('div2BriefType')?.value || 'campaign';
        const status = document.getElementById('div2BriefStatus')?.value || 'active';
        const angle = document.getElementById('div2BriefAngle')?.value.trim();
        const notes = document.getElementById('div2BriefNotes')?.value.trim();
        if (!title) return showToast('Campaign brief title is required.', 'warning');
        await api.addCampaignBrief({
            division_id: 2,
            title,
            brief_type: briefType,
            status,
            angle,
            notes
        });
        await refreshDiv2WorkData();
        renderDiv2Work();
        showToast('Campaign brief created.', 'success');
    });

    renderBattlePlan(2, {
        containerId: 'div2BattlePlanGrid',
        aiButtonsSelector: '#dashboardWorkView .div2-ai-bp-gen-btn'
    });
}
