function getDiv5CheckMeta(status) {
    const map = {
        pending: { label: 'Pending', badge: 'border-white/10 bg-white/[0.03] text-gray-200' },
        in_progress: { label: 'In Progress', badge: 'border-blue-400/20 bg-blue-500/10 text-blue-100' },
        passed: { label: 'Passed', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' },
        failed: { label: 'Failed', badge: 'border-red-400/20 bg-red-500/10 text-red-100' }
    };
    return map[status] || map.pending;
}

function getDiv5GateMeta(status) {
    const map = {
        pending: { label: 'Pending', badge: 'border-white/10 bg-white/[0.03] text-gray-200' },
        passed: { label: 'Passed', 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' }
    };
    return map[status] || map.pending;
}

function getDiv5WorkflowRecords() {
    const checks = state.div5WorkData?.checks || [];
    const gates = state.div5WorkData?.gates || [];
    const stagingRuns = state.div5WorkData?.stagingRuns || [];
    const assets = state.div5WorkData?.assets || [];
    const items = getDivisionItems(5).filter((item) => item.title !== '⚡ Executive Orders');

    return items.map((item) => {
        const itemChecks = checks.filter((entry) => Number(entry.item_id) === Number(item.id));
        const itemGates = gates.filter((entry) => Number(entry.item_id) === Number(item.id));
        const stagingRun = 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 readyAssets = assets.filter((entry) => Number(entry.item_id) === Number(item.id) && ['received', 'approved'].includes(entry.status)).length;
        const pendingTodos = (item.current_todos || []).filter((todo) => !todo.done);
        const failedChecks = itemChecks.filter((entry) => entry.status === 'failed');
        const passedChecks = itemChecks.filter((entry) => entry.status === 'passed');
        const blockedGates = itemGates.filter((entry) => entry.status === 'blocked');
        const passedGates = itemGates.filter((entry) => entry.status === 'passed');
        const stagingReady = !!recordStagingReady(itemStaging);
        const readyForPublic = itemChecks.length > 0
            && itemGates.length > 0
            && failedChecks.length === 0
            && blockedGates.length === 0
            && passedChecks.length === itemChecks.length
            && passedGates.length === itemGates.length
            && readyAssets > 0
            && stagingReady
            && pendingTodos.length === 0;
        return {
            item,
            checks: itemChecks,
            gates: itemGates,
            stagingRun,
            readyAssets,
            pendingTodos,
            failedChecks,
            blockedGates,
            readyForPublic
        };
    });
}

function recordStagingReady(stagingRun) {
    return !!stagingRun && ['ready_for_qa', 'released'].includes(stagingRun.status);
}

function getDiv5Blockers(records) {
    return records.flatMap((record) => {
        const blockers = [];
        if (!record.stagingRun || !['ready_for_qa', 'released'].includes(record.stagingRun.status)) {
            blockers.push({ workflow: record.item.title, reason: 'Production has not staged this build cleanly for QA yet.', divisionId: 4 });
        }
        if (record.readyAssets === 0) {
            blockers.push({ workflow: record.item.title, reason: 'No approved assets are visible from Production for this workflow.', divisionId: 4 });
        }
        if (record.failedChecks.length) {
            blockers.push({ workflow: record.item.title, reason: `${record.failedChecks.length} QA check(s) failed and must be cleared before release.`, divisionId: 5 });
        }
        if (record.blockedGates.length) {
            blockers.push({ workflow: record.item.title, reason: `${record.blockedGates.length} release gate(s) are blocked.`, divisionId: 5 });
        }
        if (record.pendingTodos.length) {
            blockers.push({ workflow: record.item.title, reason: `${record.pendingTodos.length} QA task(s) are still open on the workflow card.`, divisionId: 5 });
        }
        return blockers;
    });
}

function renderDiv5Work() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 5 || !state.div5WorkData) return;

    const records = getDiv5WorkflowRecords();
    const blockers = getDiv5Blockers(records);
    const checks = state.div5WorkData.checks || [];
    const gates = state.div5WorkData.gates || [];
    const orders = getTargetDivisionOrders(5, { includeDone: true });
    const workflowOptions = records.map((record) => record.item);
    const trainings = state.trainingsData?.trainings || [];
    const readyForPublic = records.filter((record) => record.readyForPublic);
    const workTabs = [
        ['queue', 'QA Queue', 'fa-clipboard-list'],
        ['zerobug', 'Zero-Bug', 'fa-bug-slash'],
        ['gates', 'Release Gates', 'fa-shield-halved'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['blockers', 'Blockers', 'fa-triangle-exclamation'],
        ['handoffs', 'Handoffs', 'fa-right-left'],
        ['standards', 'Standards', 'fa-book-open']
    ];

    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 5 Work Console</p>
                        <h3 class="text-3xl font-bold text-white mt-2">Qualifications, QA, and Release Control</h3>
                        <p class="text-sm text-gray-400 mt-3 max-w-3xl">Division 5 protects standards. It qualifies work from Production, clears the zero-bug checklist, enforces release gates, and only hands clean output into Division 6.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 min-w-0 xl:min-w-[420px]">
                        ${[
                            ['QA Workflows', records.length, 'Active workflows currently in the QA lane.'],
                            ['Checks Passed', checks.filter((entry) => entry.status === 'passed').length, 'Checklist items already cleared.'],
                            ['Blocked Gates', gates.filter((entry) => entry.status === 'blocked').length, 'Release decisions still blocked.'],
                            ['Ready For Public', readyForPublic.length, 'Workflows cleared to move into Division 6.']
                        ].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="div5-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeDiv5WorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-div5-work-tab="${id}">
                            <i class="fas ${icon} mr-2"></i>${label}
                        </button>
                    `).join('')}
                </div>
            </section>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'queue' ? '' : 'hidden'}" data-div5-work-panel="queue">
                <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 QA.</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">QA Pressure Reading</p>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-4">
                            ${[
                                ['Bugs Found', getLatestMetricValue(5, 'bugs_found') ?? 0, 'Daily bug intake in QA.'],
                                ['Bugs Fixed', getLatestMetricValue(5, 'bugs_fixed') ?? 0, 'Bugs cleared back out of QA.'],
                                ['Production Live', getDivisionItems(4).length, 'Current upstream build load.'],
                                ['Reviews Ready', readyForPublic.length, 'Items clean enough for Public.']
                            ].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 gap-4 mt-6">
                    ${records.length ? records.map((record) => `
                        <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 bg-black/30 border border-white/10 text-[10px] uppercase tracking-[0.18em] text-gray-300">${record.checks.filter((entry) => entry.status === 'passed').length}/${record.checks.length} checks passed</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.gates.filter((entry) => entry.status === 'passed').length}/${record.gates.length} gates cleared</span>
                                        ${record.readyForPublic ? '<span class="px-2 py-1 rounded-full border border-emerald-400/20 bg-emerald-500/10 text-[10px] uppercase tracking-[0.18em] text-emerald-100">Ready For Public</span>' : ''}
                                    </div>
                                    <p class="text-sm text-gray-400 mt-3">${record.failedChecks.length ? `${record.failedChecks.length} failed check(s) need rework.` : 'No failed checks on record.'} ${record.stagingRun ? `Staging: ${escapeHtml(record.stagingRun.status.replaceAll('_', ' '))}.` : 'No staging record visible.'}</p>
                                </div>
                                <div class="flex gap-2 shrink-0">
                                    <button class="div5-open-division-btn px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white" data-division="4">Open Production</button>
                                    ${record.readyForPublic ? '<button class="div5-open-division-btn px-4 py-2 rounded-xl bg-emerald-500/15 hover:bg-emerald-500/25 border border-emerald-400/20 text-sm text-emerald-100" data-division="6">Open Public</button>' : ''}
                                </div>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No workflows currently inside Division 5.</p>'}
                </div>
            </div>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'zerobug' ? '' : 'hidden'}" data-div5-work-panel="zerobug">
                <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">QA Check Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div5CheckItemId" 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="div5CheckName" 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="QA check name">
                            <div class="grid grid-cols-2 gap-3">
                                <select id="div5CheckStatus" 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="in_progress">In Progress</option>
                                    <option value="passed">Passed</option>
                                    <option value="failed">Failed</option>
                                </select>
                                <select id="div5CheckSeverity" 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="standard">Standard</option>
                                    <option value="critical">Critical</option>
                                </select>
                            </div>
                            <textarea id="div5CheckNotes" 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 failed or what is being verified?"></textarea>
                            <button id="createDiv5CheckBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create QA Check</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">Zero-Bug Checklist</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${checks.length ? checks.map((check) => {
                                const meta = getDiv5CheckMeta(check.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(check.check_name)}</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(check.severity)}</span>
                                                </div>
                                                <p class="text-sm text-gray-400 mt-3">${check.item_title ? `Workflow: ${escapeHtml(check.item_title)}.` : 'No workflow linked.'} ${check.notes ? escapeHtml(check.notes) : ''}</p>
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                ${check.status !== 'in_progress' ? `<button class="div5-check-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="${check.id}" data-status="in_progress">Start</button>` : ''}
                                                ${check.status !== 'passed' ? `<button class="div5-check-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="${check.id}" data-status="passed">Pass</button>` : ''}
                                                ${check.status !== 'failed' ? `<button class="div5-check-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="${check.id}" data-status="failed">Fail</button>` : ''}
                                                <button class="div5-check-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="${check.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No QA checks yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'gates' ? '' : 'hidden'}" data-div5-work-panel="gates">
                <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">Release Gate Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div5GateItemId" 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="div5GateName" 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="Release gate name">
                            <select id="div5GateStatus" 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="passed">Passed</option>
                                <option value="blocked">Blocked</option>
                            </select>
                            <textarea id="div5GateNotes" 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 still blocking release?"></textarea>
                            <button id="createDiv5GateBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Release Gate</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">Release Gate Register</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${gates.length ? gates.map((gate) => {
                                const meta = getDiv5GateMeta(gate.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(gate.gate_name)}</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">${gate.item_title ? `Workflow: ${escapeHtml(gate.item_title)}.` : 'No workflow linked.'} ${gate.notes ? escapeHtml(gate.notes) : ''}</p>
                                            </div>
                                            <div class="flex flex-wrap gap-2 shrink-0">
                                                ${gate.status !== 'passed' ? `<button class="div5-gate-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="${gate.id}" data-status="passed">Pass</button>` : ''}
                                                ${gate.status !== 'blocked' ? `<button class="div5-gate-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="${gate.id}" data-status="blocked">Block</button>` : ''}
                                                ${gate.status !== 'pending' ? `<button class="div5-gate-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="${gate.id}" data-status="pending">Reset</button>` : ''}
                                                <button class="div5-gate-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="${gate.id}">Delete</button>
                                            </div>
                                        </div>
                                    </div>
                                `;
                            }).join('') : '<p class="text-sm text-gray-500">No release gates yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'battleplans' ? '' : 'hidden'}" data-div5-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 5 Strat-Gen</div>
                        <p class="text-sm text-gray-400 mt-1">Use battle plans here to protect QA rhythm, release discipline, and downstream delivery confidence.</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <button class="div5-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="div5-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="div5-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="div5-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="div5BattlePlanGrid"></div>
            </div>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'blockers' ? '' : 'hidden'}" data-div5-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>
                                    <h4 class="text-lg font-bold text-white">${escapeHtml(blocker.workflow)}</h4>
                                    <p class="text-sm text-gray-400 mt-3">${escapeHtml(blocker.reason)}</p>
                                </div>
                                <button class="div5-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 QA blockers detected right now.</p>'}
                </div>
            </div>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'handoffs' ? '' : 'hidden'}" data-div5-work-panel="handoffs">
                <div class="grid grid-cols-1 xl:grid-cols-2 gap-4">
                    ${readyForPublic.length ? readyForPublic.map((record) => `
                        <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-3">All checks and release gates are passed. This workflow can now move into Division 6 for review requests, support continuity, and public success actions.</p>
                                </div>
                                <button class="div5-open-division-btn px-4 py-2 rounded-xl bg-emerald-500/15 hover:bg-emerald-500/25 border border-emerald-400/20 text-sm text-emerald-100 shrink-0" data-division="6">Open Public</button>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No workflows are fully cleared for Division 6 yet.</p>'}
                </div>
            </div>

            <div class="div5-work-panel ${state.activeDiv5WorkTab === 'standards' ? '' : 'hidden'}" data-div5-work-panel="standards">
                <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">QA Standards</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${trainings.length ? trainings.map((module) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <h4 class="text-lg font-bold text-white">${escapeHtml(module.title)}</h4>
                                    <p class="text-sm text-gray-400 mt-2">${escapeHtml((module.read_time || '10 min'))}</p>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No QA training modules 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">Qualification View</p>
                        <p class="text-sm text-gray-400 mt-4">Division 5 should never become a passive parking lot. The role is to qualify work against a standard, clear failures fast, and release only what is truly ready for the public/client-success line.</p>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.querySelectorAll('.div5-work-tab-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeDiv5WorkTab = btn.dataset.div5WorkTab;
            renderDiv5Work();
        });
    });

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

    document.getElementById('createDiv5CheckBtn')?.addEventListener('click', async () => {
        const checkName = document.getElementById('div5CheckName').value.trim();
        if (!checkName) return showToast('QA check name is required.', 'error');
        await api.addQaCheck({
            division_id: 5,
            item_id: document.getElementById('div5CheckItemId').value || null,
            check_name: checkName,
            status: document.getElementById('div5CheckStatus').value,
            severity: document.getElementById('div5CheckSeverity').value,
            notes: document.getElementById('div5CheckNotes').value.trim()
        });
        await refreshDiv5WorkData();
        renderDiv5Work();
    });

    document.querySelectorAll('.div5-check-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            const check = checks.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!check) return;
            await api.updateQaCheck(check.id, { ...check, status: btn.dataset.status });
            await refreshDiv5WorkData();
            renderDiv5Work();
        });
    });

    document.querySelectorAll('.div5-check-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.deleteQaCheck(btn.dataset.id);
            await refreshDiv5WorkData();
            renderDiv5Work();
        });
    });

    document.getElementById('createDiv5GateBtn')?.addEventListener('click', async () => {
        const gateName = document.getElementById('div5GateName').value.trim();
        if (!gateName) return showToast('Release gate name is required.', 'error');
        await api.addReleaseGate({
            division_id: 5,
            item_id: document.getElementById('div5GateItemId').value || null,
            gate_name: gateName,
            status: document.getElementById('div5GateStatus').value,
            notes: document.getElementById('div5GateNotes').value.trim()
        });
        await refreshDiv5WorkData();
        renderDiv5Work();
    });

    document.querySelectorAll('.div5-gate-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            const gate = gates.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!gate) return;
            await api.updateReleaseGate(gate.id, { ...gate, status: btn.dataset.status });
            await refreshDiv5WorkData();
            renderDiv5Work();
        });
    });

    document.querySelectorAll('.div5-gate-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.deleteReleaseGate(btn.dataset.id);
            await refreshDiv5WorkData();
            renderDiv5Work();
        });
    });

    if (state.activeDiv5WorkTab === 'battleplans') {
        state.battlePlansData = state.div5WorkData.battlePlans?.[5] || { plans: [] };
        renderBattlePlan(5, {
            containerId: 'div5BattlePlanGrid',
            aiButtonsSelector: '#dashboardWorkView .div5-ai-bp-gen-btn'
        });
    }
}
