function getDiv4AssetMeta(status) {
    const map = {
        missing: { label: 'Missing', badge: 'border-red-400/20 bg-red-500/10 text-red-100' },
        requested: { label: 'Requested', badge: 'border-amber-400/20 bg-amber-500/10 text-amber-100' },
        received: { label: 'Received', badge: 'border-blue-400/20 bg-blue-500/10 text-blue-100' },
        approved: { label: 'Approved', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' }
    };
    return map[status] || map.missing;
}

function getDiv4StagingMeta(status) {
    const map = {
        pending: { label: 'Pending', badge: 'border-white/10 bg-white/[0.03] text-gray-200' },
        live: { label: 'Live', badge: 'border-blue-400/20 bg-blue-500/10 text-blue-100' },
        review: { label: 'In Review', badge: 'border-violet-400/20 bg-violet-500/10 text-violet-100' },
        ready_for_qa: { label: 'Ready For QA', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' },
        released: { label: 'Released', badge: 'border-cyan-400/20 bg-cyan-500/10 text-cyan-100' }
    };
    return map[status] || map.pending;
}

function getDiv4ScopeMeta(status) {
    const map = {
        requested: { label: 'Requested', badge: 'border-amber-400/20 bg-amber-500/10 text-amber-100' },
        approved: { label: 'Approved', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' },
        blocked: { label: 'Blocked', badge: 'border-red-400/20 bg-red-500/10 text-red-100' },
        implemented: { label: 'Implemented', badge: 'border-blue-400/20 bg-blue-500/10 text-blue-100' }
    };
    return map[status] || map.requested;
}

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

function getDiv4WorkflowRecords() {
    const items = getDivisionItems(4).filter((item) => item.title !== '⚡ Executive Orders');
    const assets = state.div4WorkData?.assets || [];
    const stagingRuns = state.div4WorkData?.stagingRuns || [];
    const scopeControls = state.div4WorkData?.scopeControls || [];
    const treasuryCases = state.div4WorkData?.treasuryCases || [];

    return items.map((item) => {
        const itemAssets = assets.filter((entry) => Number(entry.item_id) === Number(item.id));
        const itemStaging = stagingRuns
            .filter((entry) => Number(entry.item_id) === Number(item.id))
            .sort((a, b) => String(b.updated_at || b.last_checked_at || '').localeCompare(String(a.updated_at || a.last_checked_at || '')))[0] || null;
        const itemScopes = scopeControls.filter((entry) => Number(entry.item_id) === Number(item.id));
        const treasuryCase = treasuryCases.find((entry) => Number(entry.item_id) === Number(item.id)) || null;
        const pendingTodos = (item.current_todos || []).filter((todo) => !todo.done);
        const readyAssetCount = itemAssets.filter((entry) => ['received', 'approved'].includes(entry.status)).length;
        const pendingScopeCount = itemScopes.filter((entry) => ['requested', 'blocked'].includes(entry.status)).length;
        const paid = treasuryCase?.stage === 'paid';
        const stagingReady = itemStaging && ['ready_for_qa', 'released'].includes(itemStaging.status);
        const readyForQa = paid && readyAssetCount > 0 && stagingReady && pendingScopeCount === 0 && pendingTodos.length === 0;

        return {
            item,
            pendingTodos,
            treasuryCase,
            assets: itemAssets,
            stagingRun: itemStaging,
            scopeControls: itemScopes,
            readyAssetCount,
            pendingScopeCount,
            readyForQa
        };
    });
}

function getDiv4Blockers(records) {
    return records.flatMap((record) => {
        const blockers = [];
        if (!record.treasuryCase || record.treasuryCase.stage !== 'paid') {
            blockers.push({ workflow: record.item.title, reason: 'Production started without a cleared treasury gate.', owner: 'Treasury', divisionId: 3, severity: 'high' });
        }
        if (!record.readyAssetCount) {
            blockers.push({ workflow: record.item.title, reason: 'Client assets or approvals are still missing.', owner: 'Client Assets', divisionId: 4, severity: 'medium' });
        }
        if (!record.stagingRun || !['ready_for_qa', 'released'].includes(record.stagingRun.status)) {
            blockers.push({ workflow: record.item.title, reason: 'Staging is not ready to hand off into QA.', owner: 'Staging', divisionId: 4, severity: 'medium' });
        }
        if (record.pendingScopeCount) {
            blockers.push({ workflow: record.item.title, reason: 'Open scope decisions are still unresolved.', owner: 'Scope Control', divisionId: 7, severity: 'high' });
        }
        if (record.pendingTodos.length) {
            blockers.push({ workflow: record.item.title, reason: `${record.pendingTodos.length} active production task(s) still open.`, owner: 'Production', divisionId: 4, severity: 'medium' });
        }
        return blockers;
    });
}

function renderDiv4Work() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 4 || !state.div4WorkData) return;

    const records = getDiv4WorkflowRecords();
    const blockers = getDiv4Blockers(records);
    const assets = state.div4WorkData.assets || [];
    const stagingRuns = state.div4WorkData.stagingRuns || [];
    const scopeControls = state.div4WorkData.scopeControls || [];
    const orders = getTargetDivisionOrders(4, { includeDone: true });
    const workflowOptions = records.map((record) => record.item);
    const readyForQa = records.filter((record) => record.readyForQa);
    const clearedTreasury = records.filter((record) => record.treasuryCase?.stage === 'paid');
    const liveQaCount = getDivisionItems(5).length;
    const workTabs = [
        ['production', 'Production', 'fa-laptop-code'],
        ['queue', 'Build Queue', 'fa-list-check'],
        ['assets', 'Client Assets', 'fa-folder-open'],
        ['staging', 'Staging', 'fa-server'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['blockers', 'Blockers', 'fa-triangle-exclamation'],
        ['readiness', 'Delivery Readiness', 'fa-clipboard-check'],
        ['scope', 'Scope Control', 'fa-ruler-combined']
    ];

    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 4 Work Console</p>
                        <h3 class="text-3xl font-bold text-white mt-2">Production, Staging, and Delivery Control</h3>
                        <p class="text-sm text-gray-400 mt-3 max-w-3xl">Division 4 turns sold work into a controlled build. It should not just code. It must keep treasury gates visible, capture the assets required to ship, control staging, and hand clean work into QA.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 min-w-0 xl:min-w-[420px]">
                        ${[
                            ['Live Builds', records.length, 'Active client workflows currently inside production.'],
                            ['Treasury Cleared', clearedTreasury.length, 'Builds with payment cleared by Treasury.'],
                            ['Ready For QA', readyForQa.length, 'Builds that can move downstream into Division 5.'],
                            ['Active Blockers', blockers.length, 'Production or readiness gaps still unresolved.']
                        ].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="div4-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeDiv4WorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-div4-work-tab="${id}">
                            <i class="fas ${icon} mr-2"></i>${label}
                        </button>
                    `).join('')}
                </div>
            </section>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'production' ? '' : 'hidden'}" data-div4-work-panel="production">
                <div class="grid grid-cols-1 xl:grid-cols-[0.92fr_1.08fr] 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">
                            ${orders.length ? orders.slice(0, 4).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(order.priority)}</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(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 Production.</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">Production Snapshot</p>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-4">
                            ${[
                                ['Deals Closed', getLatestMetricValue(2, 'deals') ?? 0, 'Demand already converted that could hit production soon.'],
                                ['Collected', formatServicePrice({ price: getLatestMetricValue(3, 'collected') ?? 0, currency: 'EUR' }), 'Cash already protected by Treasury.'],
                                ['QA Live', liveQaCount, 'Workflows currently downstream in Division 5.'],
                                ['Overdue Daily Plans', getOverdueDailyPlanCount(4), 'Production planning discipline still unresolved.']
                            ].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>
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-4 mt-6">
                    ${records.length ? records.slice(0, 6).map((record) => {
                        const treasuryMeta = getDiv4TreasuryMeta(record.treasuryCase?.stage);
                        const stagingMeta = record.stagingRun ? getDiv4StagingMeta(record.stagingRun.status) : { label: 'No Staging', badge: 'border-white/10 bg-white/[0.03] text-gray-300' };
                        return `
                            <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>
                                        <h4 class="text-xl font-bold text-white">${escapeHtml(record.item.title)}</h4>
                                        <div class="mt-3 flex flex-wrap gap-2">
                                            <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${treasuryMeta.badge}">${treasuryMeta.label}</span>
                                            <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${stagingMeta.badge}">${stagingMeta.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">${record.readyAssetCount} asset(s) ready</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">${record.pendingTodos.length} open task(s)</span>
                                        </div>
                                        <p class="text-sm text-gray-400 mt-3">${record.readyForQa ? 'This workflow is cleared to hand off into QA.' : 'This workflow still needs production control steps before QA.'}</p>
                                    </div>
                                    <button class="div4-open-division-btn px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white shrink-0" data-division="${record.readyForQa ? 5 : 4}">${record.readyForQa ? 'Open QA' : 'Open Pipeline'}</button>
                                </div>
                            </div>
                        `;
                    }).join('') : '<p class="text-sm text-gray-500">No active production workflows in Division 4.</p>'}
                </div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'queue' ? '' : 'hidden'}" data-div4-work-panel="queue">
                <div class="grid grid-cols-1 gap-4">
                    ${records.length ? records.map((record) => {
                        const treasuryMeta = getDiv4TreasuryMeta(record.treasuryCase?.stage);
                        return `
                            <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 p-5">
                                <div class="flex flex-col xl:flex-row xl:items-start justify-between gap-4">
                                    <div>
                                        <div class="flex flex-wrap items-center gap-2">
                                            <h4 class="text-xl font-bold text-white">${escapeHtml(record.item.title)}</h4>
                                            <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${treasuryMeta.badge}">${treasuryMeta.label}</span>
                                            ${record.readyForQa ? '<span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] border border-emerald-400/20 bg-emerald-500/10 text-emerald-100">Ready For QA</span>' : ''}
                                        </div>
                                        <div class="mt-3 flex flex-wrap gap-2">
                                            ${record.pendingTodos.slice(0, 6).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 open production todos.</span>'}
                                        </div>
                                    </div>
                                    <div class="grid grid-cols-2 gap-3 shrink-0 min-w-[220px]">
                                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
                                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Assets</p>
                                            <p class="text-lg font-bold text-white mt-2">${record.readyAssetCount}/${record.assets.length || 0}</p>
                                        </div>
                                        <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-3">
                                            <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">Scope Gaps</p>
                                            <p class="text-lg font-bold text-white mt-2">${record.pendingScopeCount}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('') : '<p class="text-sm text-gray-500">No build queue yet.</p>'}
                </div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'assets' ? '' : 'hidden'}" data-div4-work-panel="assets">
                <div class="grid grid-cols-1 xl:grid-cols-[0.92fr_1.08fr] 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">Asset Intake</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div4AssetItemId" 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</option>
                                ${workflowOptions.map((item) => `<option value="${item.id}">${escapeHtml(item.title)}</option>`).join('')}
                            </select>
                            <div class="grid grid-cols-2 gap-3">
                                <select id="div4AssetType" 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="brief">Brief</option>
                                    <option value="copy">Copy</option>
                                    <option value="credentials">Credentials</option>
                                    <option value="media">Media</option>
                                    <option value="approval">Approval</option>
                                    <option value="other">Other</option>
                                </select>
                                <select id="div4AssetStatus" 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="missing">Missing</option>
                                    <option value="requested">Requested</option>
                                    <option value="received">Received</option>
                                    <option value="approved">Approved</option>
                                </select>
                            </div>
                            <input id="div4AssetLabel" 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="Asset label">
                            <input id="div4AssetUrl" type="url" 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="Source URL or folder link">
                            <textarea id="div4AssetNotes" 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="What is missing, approved, or still waiting?"></textarea>
                            <button id="createDiv4AssetBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Asset Record</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">Asset Register</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${assets.length ? assets.map((asset) => {
                                const meta = getDiv4AssetMeta(asset.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(asset.label)}</h4>
                                                    <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${meta.badge}">${meta.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(String(asset.asset_type).replace('_', ' '))}</span>
                                                </div>
                                                <p class="text-sm text-gray-400 mt-3">${asset.item_title ? `Workflow: ${escapeHtml(asset.item_title)}.` : 'No workflow linked.'} ${asset.notes ? escapeHtml(asset.notes) : ''}</p>
                                                ${asset.source_url ? `<a href="${escapeAttr(asset.source_url)}" target="_blank" rel="noreferrer" class="inline-flex mt-3 text-sm text-indigo-300 hover:text-indigo-200">Open source <i class="fas fa-arrow-up-right-from-square ml-2 mt-0.5 text-xs"></i></a>` : ''}
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                ${asset.status !== 'requested' ? `<button class="div4-asset-status-btn px-3 py-2 rounded-xl bg-amber-500/10 hover:bg-amber-500/20 border border-amber-400/20 text-xs text-amber-100" data-id="${asset.id}" data-status="requested">Request</button>` : ''}
                                                ${asset.status !== 'received' ? `<button class="div4-asset-status-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="${asset.id}" data-status="received">Received</button>` : ''}
                                                ${asset.status !== 'approved' ? `<button class="div4-asset-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="${asset.id}" data-status="approved">Approve</button>` : ''}
                                                <button class="div4-asset-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="${asset.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No client assets tracked yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'staging' ? '' : 'hidden'}" data-div4-work-panel="staging">
                <div class="grid grid-cols-1 xl:grid-cols-[0.92fr_1.08fr] 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">Staging Control</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div4StagingItemId" 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</option>
                                ${workflowOptions.map((item) => `<option value="${item.id}">${escapeHtml(item.title)}</option>`).join('')}
                            </select>
                            <div class="grid grid-cols-2 gap-3">
                                <input id="div4StagingEnvironment" 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="Environment label">
                                <select id="div4StagingStatus" 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="pending">Pending</option>
                                    <option value="live">Live</option>
                                    <option value="review">In Review</option>
                                    <option value="ready_for_qa">Ready For QA</option>
                                    <option value="released">Released</option>
                                </select>
                            </div>
                            <input id="div4StagingUrl" type="url" 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="Staging URL">
                            <textarea id="div4StagingNotes" 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="Deployment notes, release notes, pending review items"></textarea>
                            <button id="createDiv4StagingBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Staging Record</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">Staging Register</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${stagingRuns.length ? stagingRuns.map((run) => {
                                const meta = getDiv4StagingMeta(run.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(run.environment_label || 'Staging')}</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-400 mt-3">${run.item_title ? `Workflow: ${escapeHtml(run.item_title)}.` : 'No workflow linked.'} ${run.notes ? escapeHtml(run.notes) : ''}</p>
                                                <div class="mt-3 flex flex-wrap gap-3 text-xs text-gray-500">
                                                    <span>Checked ${escapeHtml(String(run.last_checked_at || '').slice(0, 10) || 'today')}</span>
                                                    ${run.staging_url ? `<a href="${escapeAttr(run.staging_url)}" target="_blank" rel="noreferrer" class="text-indigo-300 hover:text-indigo-200">Open URL</a>` : ''}
                                                </div>
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                ${run.status !== 'review' ? `<button class="div4-staging-status-btn px-3 py-2 rounded-xl bg-violet-500/10 hover:bg-violet-500/20 border border-violet-400/20 text-xs text-violet-100" data-id="${run.id}" data-status="review">Review</button>` : ''}
                                                ${run.status !== 'ready_for_qa' ? `<button class="div4-staging-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="${run.id}" data-status="ready_for_qa">Ready For QA</button>` : ''}
                                                ${run.status !== 'released' ? `<button class="div4-staging-status-btn px-3 py-2 rounded-xl bg-cyan-500/10 hover:bg-cyan-500/20 border border-cyan-400/20 text-xs text-cyan-100" data-id="${run.id}" data-status="released">Released</button>` : ''}
                                                <button class="div4-staging-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="${run.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No staging records yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'battleplans' ? '' : 'hidden'}" data-div4-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 4 Strat-Gen</div>
                        <p class="text-sm text-gray-400 mt-1">Use battle plans here to control production capacity, protect release quality, and keep staging moving into QA.</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <button class="div4-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="div4-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="div4-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="div4-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="div4BattlePlanGrid"></div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'blockers' ? '' : 'hidden'}" data-div4-work-panel="blockers">
                <div class="grid grid-cols-1 gap-4">
                    ${blockers.length ? blockers.map((blocker) => `
                        <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>
                                    <div class="flex flex-wrap items-center gap-2">
                                        <h4 class="text-lg font-bold text-white">${escapeHtml(blocker.workflow)}</h4>
                                        <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${blocker.severity === 'high' ? 'border-red-400/20 bg-red-500/10 text-red-100' : 'border-amber-400/20 bg-amber-500/10 text-amber-100'}">${escapeHtml(blocker.severity)}</span>
                                    </div>
                                    <p class="text-sm text-gray-400 mt-3">${escapeHtml(blocker.reason)}</p>
                                    <p class="text-xs text-gray-500 mt-3">Owner: ${escapeHtml(blocker.owner)}</p>
                                </div>
                                <button class="div4-open-division-btn px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white shrink-0" data-division="${blocker.divisionId}">Open Division</button>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No blockers detected right now.</p>'}
                </div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'readiness' ? '' : 'hidden'}" data-div4-work-panel="readiness">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
                    ${records.length ? records.map((record) => {
                        const treasuryMeta = getDiv4TreasuryMeta(record.treasuryCase?.stage);
                        const stagingMeta = record.stagingRun ? getDiv4StagingMeta(record.stagingRun.status) : { label: 'No Staging', badge: 'border-white/10 bg-white/[0.03] text-gray-300' };
                        return `
                            <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 p-5">
                                <div class="flex items-start justify-between gap-4">
                                    <div>
                                        <h4 class="text-xl font-bold text-white">${escapeHtml(record.item.title)}</h4>
                                        <p class="text-sm text-gray-400 mt-2">${record.readyForQa ? 'Release gate passed. Push this into QA.' : 'Not ready for QA yet. Resolve the gaps below.'}</p>
                                    </div>
                                    <button class="div4-open-division-btn px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white shrink-0" data-division="5">Open QA</button>
                                </div>
                                <div class="grid grid-cols-2 gap-3 mt-4">
                                    <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">Treasury</p>
                                        <span class="inline-flex mt-2 px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${treasuryMeta.badge}">${treasuryMeta.label}</span>
                                    </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">Staging</p>
                                        <span class="inline-flex mt-2 px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${stagingMeta.badge}">${stagingMeta.label}</span>
                                    </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">Assets Ready</p>
                                        <p class="text-lg font-bold text-white mt-2">${record.readyAssetCount}</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">Scope Gaps</p>
                                        <p class="text-lg font-bold text-white mt-2">${record.pendingScopeCount}</p>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('') : '<p class="text-sm text-gray-500">No delivery readiness data yet.</p>'}
                </div>
            </div>

            <div class="div4-work-panel ${state.activeDiv4WorkTab === 'scope' ? '' : 'hidden'}" data-div4-work-panel="scope">
                <div class="grid grid-cols-1 xl:grid-cols-[0.92fr_1.08fr] 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">Scope Control</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div4ScopeItemId" 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</option>
                                ${workflowOptions.map((item) => `<option value="${item.id}">${escapeHtml(item.title)}</option>`).join('')}
                            </select>
                            <input id="div4ScopeTitle" 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="Scope request title">
                            <div class="grid grid-cols-2 gap-3">
                                <select id="div4ScopeStatus" 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="requested">Requested</option>
                                    <option value="approved">Approved</option>
                                    <option value="blocked">Blocked</option>
                                    <option value="implemented">Implemented</option>
                                </select>
                                <select id="div4ScopeImpact" 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="low">Low Impact</option>
                                    <option value="medium">Medium Impact</option>
                                    <option value="high">High Impact</option>
                                </select>
                            </div>
                            <textarea id="div4ScopeNotes" 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="Decision notes, cost/time impact, approval summary"></textarea>
                            <button id="createDiv4ScopeBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Scope Record</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">Scope Register</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${scopeControls.length ? scopeControls.map((control) => {
                                const meta = getDiv4ScopeMeta(control.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(control.title)}</h4>
                                                    <span class="px-2 py-1 rounded-full text-[10px] uppercase tracking-[0.18em] ${meta.badge}">${meta.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(control.impact_level)}</span>
                                                </div>
                                                <p class="text-sm text-gray-400 mt-3">${control.item_title ? `Workflow: ${escapeHtml(control.item_title)}.` : 'No workflow linked.'} ${control.notes ? escapeHtml(control.notes) : ''}</p>
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                ${control.status !== 'approved' ? `<button class="div4-scope-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="${control.id}" data-status="approved">Approve</button>` : ''}
                                                ${control.status !== 'blocked' ? `<button class="div4-scope-status-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="${control.id}" data-status="blocked">Block</button>` : ''}
                                                ${control.status !== 'implemented' ? `<button class="div4-scope-status-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="${control.id}" data-status="implemented">Implemented</button>` : ''}
                                                <button class="div4-scope-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="${control.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No scope-control records yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.querySelectorAll('.div4-work-tab-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeDiv4WorkTab = btn.dataset.div4WorkTab;
            renderDiv4Work();
        });
    });

    document.querySelectorAll('.div4-open-division-btn').forEach((btn) => {
        btn.addEventListener('click', () => openDashboard(Number(btn.dataset.division)));
    });

    document.getElementById('createDiv4AssetBtn')?.addEventListener('click', async () => {
        const label = document.getElementById('div4AssetLabel').value.trim();
        if (!label) return showToast('Asset label is required.', 'error');
        await api.addProductionAsset({
            division_id: 4,
            item_id: document.getElementById('div4AssetItemId').value || null,
            asset_type: document.getElementById('div4AssetType').value,
            label,
            status: document.getElementById('div4AssetStatus').value,
            source_url: document.getElementById('div4AssetUrl').value.trim(),
            notes: document.getElementById('div4AssetNotes').value.trim()
        });
        await refreshDiv4WorkData();
        renderDiv4Work();
    });

    document.querySelectorAll('.div4-asset-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            const asset = assets.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!asset) return;
            await api.updateProductionAsset(asset.id, { ...asset, status: btn.dataset.status });
            await refreshDiv4WorkData();
            renderDiv4Work();
        });
    });

    document.querySelectorAll('.div4-asset-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.deleteProductionAsset(btn.dataset.id);
            await refreshDiv4WorkData();
            renderDiv4Work();
        });
    });

    document.getElementById('createDiv4StagingBtn')?.addEventListener('click', async () => {
        const environmentLabel = document.getElementById('div4StagingEnvironment').value.trim();
        if (!environmentLabel) return showToast('Environment label is required.', 'error');
        await api.addStagingRun({
            division_id: 4,
            item_id: document.getElementById('div4StagingItemId').value || null,
            environment_label: environmentLabel,
            staging_url: document.getElementById('div4StagingUrl').value.trim(),
            status: document.getElementById('div4StagingStatus').value,
            notes: document.getElementById('div4StagingNotes').value.trim()
        });
        await refreshDiv4WorkData();
        renderDiv4Work();
    });

    document.querySelectorAll('.div4-staging-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            const run = stagingRuns.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!run) return;
            await api.updateStagingRun(run.id, { ...run, status: btn.dataset.status, last_checked_at: new Date().toISOString() });
            await refreshDiv4WorkData();
            renderDiv4Work();
        });
    });

    document.querySelectorAll('.div4-staging-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.deleteStagingRun(btn.dataset.id);
            await refreshDiv4WorkData();
            renderDiv4Work();
        });
    });

    document.getElementById('createDiv4ScopeBtn')?.addEventListener('click', async () => {
        const title = document.getElementById('div4ScopeTitle').value.trim();
        if (!title) return showToast('Scope title is required.', 'error');
        await api.addScopeControl({
            division_id: 4,
            item_id: document.getElementById('div4ScopeItemId').value || null,
            title,
            status: document.getElementById('div4ScopeStatus').value,
            impact_level: document.getElementById('div4ScopeImpact').value,
            notes: document.getElementById('div4ScopeNotes').value.trim()
        });
        await refreshDiv4WorkData();
        renderDiv4Work();
    });

    document.querySelectorAll('.div4-scope-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            const control = scopeControls.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!control) return;
            await api.updateScopeControl(control.id, { ...control, status: btn.dataset.status });
            await refreshDiv4WorkData();
            renderDiv4Work();
        });
    });

    document.querySelectorAll('.div4-scope-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.deleteScopeControl(btn.dataset.id);
            await refreshDiv4WorkData();
            renderDiv4Work();
        });
    });

    if (state.activeDiv4WorkTab === 'battleplans') {
        state.battlePlansData = state.div4WorkData.battlePlans?.[4] || { plans: [] };
        renderBattlePlan(4, {
            containerId: 'div4BattlePlanGrid',
            aiButtonsSelector: '#dashboardWorkView .div4-ai-bp-gen-btn'
        });
    }
}
