function renderEdWork() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 8) return;

    const owner = state.settings?.owner_name || 'Executive';
    const today = new Date().toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long' });
    const workTabs = [
        ['command', 'Command', 'fa-satellite-dish'],
        ['stats', 'Stats', 'fa-chart-line'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['bottlenecks', 'Bottlenecks', 'fa-triangle-exclamation'],
        ['finance', 'Finance', 'fa-wallet'],
        ['delivery', 'Delivery', 'fa-truck-fast'],
        ['people', 'People', 'fa-users'],
        ['orders', 'Orders', 'fa-scroll'],
        ['scene', 'Scene', 'fa-globe']
    ];

    const laneIds = [7, 1, 2, 3, 4, 5, 6];
    const laneSummaries = laneIds.map((divId) => {
        const div = getDivisionById(divId);
        const workload = getWorkloadSummary(divId);
        return {
            id: divId,
            name: getDivisionCopy(div).name,
            subtitle: getDivisionCopy(div).subtitle,
            workflows: workload.workflows,
            pendingTasks: workload.pendingTasks,
            overduePlans: getOverdueDailyPlanCount(divId)
        };
    });

    const commandLeader = [...laneSummaries].sort((a, b) => (b.pendingTasks + b.overduePlans * 2) - (a.pendingTasks + a.overduePlans * 2))[0];
    const totalPending = laneSummaries.reduce((sum, lane) => sum + lane.pendingTasks, 0);
    const totalWorkflows = laneSummaries.reduce((sum, lane) => sum + lane.workflows, 0);
    const totalOverduePlans = laneSummaries.reduce((sum, lane) => sum + lane.overduePlans, 0);
    const divisionsMissingMetrics = [2, 3, 4, 6, 8].filter((divId) => {
        const bundle = getEdMetricsBundle(divId);
        return !bundle?.data?.some((row) => row.is_mock === 0 && row.date === new Date().toISOString().split('T')[0]);
    }).length;
    const missingMetricDivisions = [2, 3, 4, 6, 8]
        .filter((divId) => getDivisionMetricStatus(divId) === 'Missing')
        .map((divId) => ({ id: divId, name: getDivisionCopy(getDivisionById(divId)).name }));
    const executiveOrders = buildExecutiveOrders(laneSummaries, missingMetricDivisions);
    const activeScene = laneSummaries
        .filter((lane) => lane.workflows > 0)
        .map((lane) => ({
            ...lane,
            titles: getDivisionWorkflowTitles(lane.id, 3)
        }));

    const financeCards = [
        ['Collected', `${getLatestMetricValue(3, 'collected') ?? 0}`, 'Div 3 collected cash'],
        ['Invoiced', `${getLatestMetricValue(3, 'invoiced') ?? 0}`, 'Div 3 invoice output'],
        ['MRR', `${getLatestMetricValue(8, 'mrr') ?? 0}`, 'ED finance pulse'],
        ['Deals Closed', `${getLatestMetricValue(2, 'deals') ?? 0}`, 'Div 2 close rate']
    ];

    const deliveryCards = [
        ['Production', getWorkloadSummary(4).workflows, `${getWorkloadSummary(4).pendingTasks} pending tasks in Div 4`],
        ['QA', getWorkloadSummary(5).workflows, `${getWorkloadSummary(5).pendingTasks} pending tasks in Div 5`],
        ['Public', getWorkloadSummary(6).workflows, `${getWorkloadSummary(6).pendingTasks} pending tasks in Div 6`]
    ];

    container.innerHTML = `
        <div class="flex flex-col gap-6">
            <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                <div class="flex flex-col xl:flex-row xl:items-end justify-between gap-5">
                    <div>
                        <p class="text-[11px] uppercase tracking-[0.28em] text-indigo-300 mb-2">Executive Work Console</p>
                        <h3 class="text-3xl font-bold text-white">ED Hat Control for ${escapeHtml(owner)}</h3>
                        <p class="text-sm text-gray-400 mt-2 max-w-3xl">Switch into executive command mode. This view consolidates the org-wide stats, bottlenecks, finance, delivery pressure, and planning instruments that the Executive Director needs in order to direct the board.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3">
                            <p class="text-[10px] uppercase tracking-[0.22em] text-gray-500">Today</p>
                            <p class="text-sm text-white font-semibold mt-1">${escapeHtml(today)}</p>
                        </div>
                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3">
                            <p class="text-[10px] uppercase tracking-[0.22em] text-gray-500">Pending Tasks</p>
                            <p class="text-sm text-white font-semibold mt-1">${totalPending}</p>
                        </div>
                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3">
                            <p class="text-[10px] uppercase tracking-[0.22em] text-gray-500">Active Workflows</p>
                            <p class="text-sm text-white font-semibold mt-1">${totalWorkflows}</p>
                        </div>
                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3">
                            <p class="text-[10px] uppercase tracking-[0.22em] text-gray-500">Overdue Daily Plans</p>
                            <p class="text-sm text-white font-semibold mt-1">${totalOverduePlans}</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="flex flex-wrap gap-2">
                ${workTabs.map(([id, label, icon]) => `
                    <button class="ed-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeEdWorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-ed-work-tab="${id}">
                        <i class="fas ${icon} mr-2"></i>${label}
                    </button>
                `).join('')}
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'command' ? '' : 'hidden'}" data-ed-work-panel="command">
                <div class="grid grid-cols-1 xl:grid-cols-[1.3fr_0.9fr] gap-6">
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <div class="flex items-start justify-between gap-4 mb-5">
                            <div>
                                <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Primary Command Target</p>
                                <h4 class="text-2xl font-bold text-white">${escapeHtml(commandLeader?.name || 'No active division')}</h4>
                                <p class="text-sm text-gray-400 mt-2">The current highest-pressure lane by pending work and overdue daily plans. This is where the ED should focus first.</p>
                            </div>
                            <div class="rounded-2xl border border-amber-500/20 bg-amber-500/10 px-4 py-3 text-right">
                                <p class="text-[10px] uppercase tracking-[0.2em] text-amber-300">Executive Reading</p>
                                <p class="text-lg font-bold text-white mt-1">${commandLeader ? `${commandLeader.pendingTasks} pending / ${commandLeader.overduePlans} overdue` : 'Clear'}</p>
                            </div>
                        </div>
                        <div class="grid md:grid-cols-2 gap-4">
                            ${laneSummaries.map((lane) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <div class="flex items-start justify-between gap-3">
                                        <div>
                                            <p class="text-sm font-bold text-white">${escapeHtml(lane.name)}</p>
                                            <p class="text-xs text-gray-500 mt-1">${escapeHtml(lane.subtitle)}</p>
                                        </div>
                                        <span class="text-[10px] uppercase tracking-[0.2em] text-gray-500">${lane.workflows} workflows</span>
                                    </div>
                                    <div class="mt-4 grid grid-cols-3 gap-2 text-center">
                                        <div class="rounded-xl bg-black/30 border border-white/5 px-2 py-3">
                                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Pending</p>
                                            <p class="text-sm font-bold text-white mt-1">${lane.pendingTasks}</p>
                                        </div>
                                        <div class="rounded-xl bg-black/30 border border-white/5 px-2 py-3">
                                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Daily Plans</p>
                                            <p class="text-sm font-bold text-white mt-1">${lane.overduePlans}</p>
                                        </div>
                                        <div class="rounded-xl bg-black/30 border border-white/5 px-2 py-3">
                                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Scope</p>
                                            <p class="text-sm font-bold text-white mt-1">Div ${lane.id}</p>
                                        </div>
                                    </div>
                                </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">Command Exceptions</p>
                        <div class="flex flex-col gap-3">
                            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                <p class="text-sm font-semibold text-white">Divisions missing today&apos;s metrics</p>
                                <p class="text-2xl font-bold text-white mt-2">${divisionsMissingMetrics}</p>
                                <div class="mt-3 flex flex-wrap gap-2">
                                    ${missingMetricDivisions.length
                                        ? missingMetricDivisions.map((entry) => `<button class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-gray-300 ed-open-division-btn" data-division="${entry.id}">${escapeHtml(entry.name)}</button>`).join('')
                                        : '<span class="text-xs text-emerald-300">All executive stats are current.</span>'}
                                </div>
                            </div>
                            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                <p class="text-sm font-semibold text-white">Total overdue daily plans</p>
                                <p class="text-2xl font-bold text-white mt-2">${totalOverduePlans}</p>
                            </div>
                            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                <p class="text-sm font-semibold text-white">Executive directive</p>
                                <p class="text-sm text-gray-400 mt-2">Stabilize the highest-pressure division first, then restore stats reporting discipline, then push cross-division handoffs back into flow.</p>
                                ${commandLeader ? `<button class="mt-3 px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white ed-open-division-btn" data-division="${commandLeader.id}">Open ${escapeHtml(commandLeader.name)}</button>` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'stats' ? '' : 'hidden'}" data-ed-work-panel="stats">
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
                    ${[
                        ['MRR', getLatestMetricValue(8, 'mrr') ?? 0, 'ED'],
                        ['Net Profit', getLatestMetricValue(8, 'net_profit') ?? 0, 'ED'],
                        ['Leads', getLatestMetricValue(2, 'leads') ?? 0, 'Div 2'],
                        ['Deals', getLatestMetricValue(2, 'deals') ?? 0, 'Div 2'],
                        ['Collected', getLatestMetricValue(3, 'collected') ?? 0, 'Div 3'],
                        ['Tasks Done', getLatestMetricValue(4, 'tasks_done') ?? 0, 'Div 4'],
                        ['Bugs Fixed', getLatestMetricValue(5, 'bugs_fixed') ?? 0, 'Div 5'],
                        ['Reviews', getLatestMetricValue(6, 'reviews') ?? 0, 'Div 6']
                    ].map(([label, value, ownerTag]) => `
                        <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">${ownerTag}</p>
                            <p class="text-sm text-gray-400 mt-2">${label}</p>
                            <p class="text-3xl font-bold text-white mt-2">${value}</p>
                        </div>
                    `).join('')}
                </div>
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6 mt-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">Metric Discipline</p>
                        <div class="grid sm:grid-cols-2 gap-3 mt-4">
                            ${[2, 3, 4, 6, 8].map((divId) => {
                                const div = getDivisionById(divId);
                                const status = getDivisionMetricStatus(divId);
                                return `
                                    <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                        <p class="text-sm font-semibold text-white">${escapeHtml(getDivisionCopy(div).name)}</p>
                                        <p class="text-xs ${status === 'Current' ? 'text-emerald-300' : 'text-amber-300'} mt-2">${status}</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">Executive Reading</p>
                        <p class="text-sm text-gray-400 mt-4">This tab is the ED stat rollup. It should answer one question fast: are dissemination, treasury, production, public, and executive stats moving in the right direction today?</p>
                    </div>
                </div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'battleplans' ? '' : 'hidden'}" data-ed-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 class="flex items-center gap-2 text-purple-400 font-bold"><i class="fas fa-magic"></i> ED Strat-Gen</div>
                    <div class="flex flex-wrap gap-2">
                        <button class="ed-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="ed-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="ed-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="ed-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="edBattlePlanGrid"></div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'bottlenecks' ? '' : 'hidden'}" data-ed-work-panel="bottlenecks">
                <div class="grid gap-4">
                    ${[...laneSummaries]
                        .sort((a, b) => (b.pendingTasks + b.overduePlans * 2) - (a.pendingTasks + a.overduePlans * 2))
                        .map((lane, index) => `
                            <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-center justify-between gap-4">
                                    <div>
                                        <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">Priority ${index + 1}</p>
                                        <h4 class="text-xl font-bold text-white mt-2">${escapeHtml(lane.name)}</h4>
                                        <p class="text-sm text-gray-400 mt-2">${lane.pendingTasks} pending tasks, ${lane.overduePlans} overdue daily plans, ${lane.workflows} active workflows.</p>
                                        <div class="mt-3 flex flex-wrap gap-2">
                                            ${getDivisionWorkflowTitles(lane.id, 3).map((title) => `<span class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-gray-300">${escapeHtml(title)}</span>`).join('')}
                                        </div>
                                    </div>
                                    <div class="grid grid-cols-3 gap-2 text-center min-w-[220px]">
                                        <div class="rounded-xl bg-white/[0.03] border border-white/10 px-3 py-3"><p class="text-[10px] text-gray-500 uppercase tracking-[0.18em]">Pending</p><p class="text-lg font-bold text-white mt-1">${lane.pendingTasks}</p></div>
                                        <div class="rounded-xl bg-white/[0.03] border border-white/10 px-3 py-3"><p class="text-[10px] text-gray-500 uppercase tracking-[0.18em]">Overdue</p><p class="text-lg font-bold text-white mt-1">${lane.overduePlans}</p></div>
                                        <div class="rounded-xl bg-white/[0.03] border border-white/10 px-3 py-3"><p class="text-[10px] text-gray-500 uppercase tracking-[0.18em]">Flow</p><p class="text-lg font-bold text-white mt-1">${lane.workflows}</p></div>
                                    </div>
                                </div>
                                <div class="mt-4 flex justify-end">
                                    <button class="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white ed-open-division-btn" data-division="${lane.id}">Open ${escapeHtml(lane.name)}</button>
                                </div>
                            </div>
                        `).join('')}
                </div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'finance' ? '' : 'hidden'}" data-ed-work-panel="finance">
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
                    ${financeCards.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">${value}</p>
                            <p class="text-sm text-gray-400 mt-2">${body}</p>
                        </div>
                    `).join('')}
                </div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'delivery' ? '' : 'hidden'}" data-ed-work-panel="delivery">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    ${deliveryCards.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">${value}</p>
                            <p class="text-sm text-gray-400 mt-2">${body}</p>
                        </div>
                    `).join('')}
                </div>
                <div class="grid grid-cols-1 xl:grid-cols-3 gap-4 mt-6">
                    ${[4, 5, 6].map((divId) => {
                        const div = getDivisionById(divId);
                        const titles = getDivisionWorkflowTitles(divId, 4);
                        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-1.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white ed-open-division-btn" data-division="${divId}">Open</button>
                                </div>
                                <div class="mt-4 flex flex-col gap-2">
                                    ${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="ed-work-panel ${state.activeEdWorkTab === 'people' ? '' : 'hidden'}" data-ed-work-panel="people">
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    ${laneSummaries.map((lane) => `
                        <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 p-5">
                            <p class="text-lg font-bold text-white">${escapeHtml(lane.name)}</p>
                            <p class="text-sm text-gray-400 mt-2">Current hat-load visibility for future assignment and role balancing.</p>
                            <div class="mt-3 inline-flex px-3 py-1 rounded-full bg-white/[0.03] border border-white/10 text-xs text-white">${getHatLoadLabel(lane)}</div>
                            <div class="mt-4 flex gap-2 text-xs flex-wrap">
                                <span class="px-3 py-1 rounded-full bg-white/[0.05] border border-white/10 text-gray-300">${lane.workflows} workflows</span>
                                <span class="px-3 py-1 rounded-full bg-white/[0.05] border border-white/10 text-gray-300">${lane.pendingTasks} pending</span>
                                <span class="px-3 py-1 rounded-full bg-white/[0.05] border border-white/10 text-gray-300">${lane.overduePlans} overdue plans</span>
                            </div>
                            <button class="mt-4 px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white ed-open-division-btn" data-division="${lane.id}">Open ${escapeHtml(lane.name)}</button>
                        </div>
                    `).join('')}
                </div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'orders' ? '' : 'hidden'}" data-ed-work-panel="orders">
                <div class="grid grid-cols-1 xl:grid-cols-[0.95fr_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">Issue Executive Order</p>
                        <h4 class="text-2xl font-bold text-white">Create a tracked directive</h4>
                        <p class="text-sm text-gray-400 mt-3">Direct a division, set urgency, set a due date, and let the order appear downstream inside that division dashboard.</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="edOrderDivision" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-3 focus:outline-none focus:border-[var(--dash-accent)]">
                                ${laneSummaries.map((lane) => `<option value="${lane.id}">${escapeHtml(lane.name)}</option>`).join('')}
                            </select>
                            <input id="edOrderTitle" 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="Order title">
                            <textarea id="edOrderBody" rows="5" 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="What exactly must this division do, and why?"></textarea>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <select id="edOrderPriority" 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="high">High priority</option>
                                    <option value="medium" selected>Medium priority</option>
                                    <option value="low">Low priority</option>
                                </select>
                                <input id="edOrderDueDate" 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>
                            <button id="createEdOrderBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Executive Order</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">Tracked Orders</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${(state.executiveOrders || []).length ? (state.executiveOrders || []).map((order, index) => `
                                <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>
                                            <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">Order ${index + 1} · ${escapeHtml(order.target_division_name || `Division ${order.target_division_id}`)}</p>
                                            <h4 class="text-xl font-bold text-white mt-2">${escapeHtml(order.title)}</h4>
                                            <p class="text-sm text-gray-400 mt-2">${escapeHtml(order.body || '')}</p>
                                            <div class="mt-3 flex flex-wrap gap-2 text-[10px] uppercase tracking-[0.18em]">
                                                <span class="px-2 py-1 rounded-full bg-black/30 border border-white/10 text-gray-300">${escapeHtml(order.priority)}</span>
                                                <span class="px-2 py-1 rounded-full bg-black/30 border border-white/10 text-gray-300">${escapeHtml(String(order.status).replace('_', ' '))}</span>
                                                ${order.due_date ? `<span class="px-2 py-1 rounded-full bg-black/30 border border-white/10 text-gray-300">Due ${escapeHtml(order.due_date)}</span>` : ''}
                                            </div>
                                        </div>
                                        <div class="flex flex-wrap gap-2 shrink-0">
                                            <button class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white ed-open-division-btn" data-division="${order.target_division_id}">Open Division</button>
                                            ${order.status !== 'open' ? `<button class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white ed-order-status-btn" data-order-id="${order.id}" data-status="open">Reopen</button>` : ''}
                                            ${order.status !== 'in_progress' ? `<button class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white ed-order-status-btn" data-order-id="${order.id}" data-status="in_progress">Start</button>` : ''}
                                            ${order.status !== 'done' ? `<button class="px-3 py-2 rounded-xl bg-emerald-500/15 hover:bg-emerald-500/25 border border-emerald-400/20 text-xs text-emerald-100 ed-order-status-btn" data-order-id="${order.id}" data-status="done">Complete</button>` : ''}
                                            <button class="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 ed-order-delete-btn" data-order-id="${order.id}">Delete</button>
                                        </div>
                                    </div>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No executive orders yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="ed-work-panel ${state.activeEdWorkTab === 'scene' ? '' : 'hidden'}" data-ed-work-panel="scene">
                <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
                    ${[
                        ['Leads Generated', getLatestMetricValue(2, 'leads') ?? 0, 'Scene inflow from Div 2'],
                        ['Deals Closed', getLatestMetricValue(2, 'deals') ?? 0, 'Scene conversion from Div 2'],
                        ['Reviews', getLatestMetricValue(6, 'reviews') ?? 0, 'Public proof from Div 6'],
                        ['Support Tickets', getLatestMetricValue(6, 'support_tickets') ?? 0, 'Public pressure from Div 6']
                    ].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">${value}</p>
                            <p class="text-sm text-gray-400 mt-2">${body}</p>
                        </div>
                    `).join('')}
                </div>
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-6 mt-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 Snapshot</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${activeScene.length ? activeScene.map((lane) => `
                                <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(lane.name)}</h4>
                                        <button class="px-3 py-1.5 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white ed-open-division-btn" data-division="${lane.id}">Open</button>
                                    </div>
                                    <div class="mt-3 flex flex-wrap gap-2">
                                        ${lane.titles.map((title) => `<span class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-gray-300">${escapeHtml(title)}</span>`).join('')}
                                    </div>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No active scene 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 is the ED public/commercial scene check: new demand from Dissemination, client pressure from Public, and whether active delivery is generating future reputation and repeat demand.</p>
                    </div>
                </div>
            </div>
        </div>
    `;

    container.querySelectorAll('[data-ed-work-tab]').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeEdWorkTab = btn.dataset.edWorkTab;
            renderEdWork();
        });
    });
    container.querySelectorAll('.ed-open-division-btn').forEach((btn) => {
        btn.addEventListener('click', () => openDashboard(Number(btn.dataset.division)));
    });
    container.querySelectorAll('.ed-order-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.updateExecutiveOrder(btn.dataset.orderId, { status: btn.dataset.status });
            await refreshEdWorkData();
            renderEdWork();
        });
    });
    container.querySelectorAll('.ed-order-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            customConfirm('Delete this executive order?', async () => {
                await api.deleteExecutiveOrder(btn.dataset.orderId);
                await refreshEdWorkData();
                renderEdWork();
            });
        });
    });
    const createBtn = document.getElementById('createEdOrderBtn');
    if (createBtn) {
        createBtn.addEventListener('click', async () => {
            const targetDivisionId = Number(document.getElementById('edOrderDivision')?.value);
            const title = document.getElementById('edOrderTitle')?.value.trim();
            const body = document.getElementById('edOrderBody')?.value.trim();
            const priority = document.getElementById('edOrderPriority')?.value || 'medium';
            const dueDate = document.getElementById('edOrderDueDate')?.value || null;
            if (!targetDivisionId || !title) {
                showToast('Target division and order title are required.', 'warning');
                return;
            }
            await api.addExecutiveOrder({
                target_division_id: targetDivisionId,
                title,
                body,
                priority,
                due_date: dueDate
            });
            await refreshEdWorkData();
            renderEdWork();
            showToast('Executive order created.', 'success');
        });
    }

    renderBattlePlan(8, {
        containerId: 'edBattlePlanGrid',
        aiButtonsSelector: '#dashboardWorkView .ed-ai-bp-gen-btn'
    });
}

async function loadMetricsInsight(divId) {
    const el = document.getElementById('aiMetricsInsight');
    el.innerHTML = `<i class="fas fa-spinner fa-spin text-purple-400"></i> ${escapeHtml(t('metrics.aiReading'))}`;
    try {
        const data = await api.interpretMetrics(divId);
        el.innerHTML = `<span class="text-purple-200"><i class="fas fa-robot text-purple-400 mr-1"></i>${data.insight}</span>`;
    } catch(e) {
        el.innerHTML = `<span class="text-red-400 text-xs">${escapeHtml(t('metrics.interpretFail'))}</span>`;
}
}

// ====== BATTLE PLAN ENGINE ======
