function getDiv6LoopMeta(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' },
        done: { label: 'Done', badge: 'border-emerald-400/20 bg-emerald-500/10 text-emerald-100' },
        paused: { label: 'Paused', badge: 'border-amber-400/20 bg-amber-500/10 text-amber-100' }
    };
    return map[status] || map.pending;
}

function getDiv6ReadyFromQa() {
    const gateGroups = new Map();
    const checkGroups = new Map();
    const stagingGroups = new Map();
    const assetCounts = new Map();
    (state.div6WorkData?.gates || []).forEach((gate) => {
        const key = Number(gate.item_id);
        if (!key) return;
        if (!gateGroups.has(key)) gateGroups.set(key, []);
        gateGroups.get(key).push(gate);
    });
    (state.div6WorkData?.checks || []).forEach((check) => {
        const key = Number(check.item_id);
        if (!key) return;
        if (!checkGroups.has(key)) checkGroups.set(key, []);
        checkGroups.get(key).push(check);
    });
    (state.div6WorkData?.stagingRuns || []).forEach((run) => {
        const key = Number(run.item_id);
        if (!key) return;
        const current = stagingGroups.get(key);
        if (!current || String(run.updated_at || run.last_checked_at || '').localeCompare(String(current.updated_at || current.last_checked_at || '')) > 0) {
            stagingGroups.set(key, run);
        }
    });
    (state.div6WorkData?.assets || []).forEach((asset) => {
        const key = Number(asset.item_id);
        if (!key) return;
        if (!['received', 'approved'].includes(asset.status)) return;
        assetCounts.set(key, (assetCounts.get(key) || 0) + 1);
    });

    return getDivisionItems(5)
        .filter((item) => item.title !== '⚡ Executive Orders')
        .map((item) => {
            const gates = gateGroups.get(Number(item.id)) || [];
            const checks = checkGroups.get(Number(item.id)) || [];
            const stagingRun = stagingGroups.get(Number(item.id)) || null;
            const readyAssets = assetCounts.get(Number(item.id)) || 0;
            const pendingTodos = (item.current_todos || []).filter((todo) => !todo.done);
            const passed = gates.length > 0
                && checks.length > 0
                && gates.every((gate) => gate.status === 'passed')
                && checks.every((check) => check.status === 'passed')
                && readyAssets > 0
                && !!stagingRun
                && ['ready_for_qa', 'released'].includes(stagingRun.status)
                && pendingTodos.length === 0;
            return { item, gates, checks, stagingRun, readyAssets, passed };
        })
        .filter((entry) => entry.passed);
}

function renderDiv6LoopCards(loops, emptyMessage) {
    return loops.length ? loops.map((loop) => {
        const meta = getDiv6LoopMeta(loop.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(loop.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(String(loop.loop_type).replaceAll('_', ' '))}</span>
                        </div>
                        <p class="text-sm text-gray-400 mt-3">${loop.item_title ? `Workflow: ${escapeHtml(loop.item_title)}.` : 'No workflow linked.'} ${loop.notes ? escapeHtml(loop.notes) : ''}</p>
                        <p class="text-xs text-gray-500 mt-3">${loop.next_action_date ? `Next action ${escapeHtml(loop.next_action_date)}` : 'No next action date set.'}</p>
                    </div>
                    <div class="flex flex-wrap gap-2 shrink-0">
                        ${loop.status !== 'in_progress' ? `<button class="div6-loop-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="${loop.id}" data-status="in_progress">Start</button>` : ''}
                        ${loop.status !== 'done' ? `<button class="div6-loop-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="${loop.id}" data-status="done">Done</button>` : ''}
                        ${loop.status !== 'paused' ? `<button class="div6-loop-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="${loop.id}" data-status="paused">Pause</button>` : ''}
                        <button class="div6-loop-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="${loop.id}">Delete</button>
                    </div>
                </div>
            </div>
        `;
    }).join('') : `<p class="text-sm text-gray-500">${escapeHtml(emptyMessage)}</p>`;
}

function renderDiv6Work() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 6 || !state.div6WorkData) return;

    const loops = state.div6WorkData.loops || [];
    const orders = getTargetDivisionOrders(6, { includeDone: true });
    const readyFromQa = getDiv6ReadyFromQa();
    const workflowOptions = getDivisionItems(6).filter((item) => item.title !== '⚡ Executive Orders');
    const reviewLoops = loops.filter((loop) => loop.loop_type === 'review_request');
    const supportLoops = loops.filter((loop) => loop.loop_type === 'support_checkin');
    const referralLoops = loops.filter((loop) => loop.loop_type === 'referral_upsell');
    const activeFollowups = loops.filter((loop) => loop.status !== 'done');
    const workTabs = [
        ['success', 'Client Success', 'fa-heart'],
        ['reviews', 'Reviews', 'fa-star'],
        ['support', 'Support', 'fa-headset'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['followups', 'Follow-Ups', 'fa-reply'],
        ['referrals', 'Referrals', 'fa-share-nodes'],
        ['continuity', 'Continuity', 'fa-infinity']
    ];

    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 6 Work Console</p>
                        <h3 class="text-3xl font-bold text-white mt-2">Client Success, Reviews, and Continuity</h3>
                        <p class="text-sm text-gray-400 mt-3 max-w-3xl">Division 6 protects the public side of the org. It turns completed delivery into satisfaction, review growth, support continuity, referrals, and repeat revenue.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 min-w-0 xl:min-w-[420px]">
                        ${[
                            ['Reviews Due', reviewLoops.filter((loop) => loop.status !== 'done').length, 'Review requests still open.'],
                            ['Support Open', supportLoops.filter((loop) => loop.status !== 'done').length, 'Support continuity loops still active.'],
                            ['Referral Pulses', referralLoops.filter((loop) => loop.status !== 'done').length, 'Upsell or referral follow-up in play.'],
                            ['Ready From QA', readyFromQa.length, 'Workflows cleared by Division 5 and ready for public success.']
                        ].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="div6-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeDiv6WorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-div6-work-tab="${id}">
                            <i class="fas ${icon} mr-2"></i>${label}
                        </button>
                    `).join('')}
                </div>
            </section>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'success' ? '' : 'hidden'}" data-div6-work-panel="success">
                <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 Public.</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">Ready From QA</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${readyFromQa.length ? readyFromQa.map((entry) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-5">
                                    <div class="flex items-start justify-between gap-4">
                                        <div>
                                            <h4 class="text-lg font-bold text-white">${escapeHtml(entry.item.title)}</h4>
                                            <p class="text-sm text-gray-400 mt-3">Division 5 has cleared all release gates. This client can move into review requests, support continuity, and public success follow-through.</p>
                                        </div>
                                        <button class="div6-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>
                            `).join('') : '<p class="text-sm text-gray-500">No workflows are fully cleared from QA yet.</p>'}
                        </div>
                    </div>
                </div>
                <div class="grid grid-cols-1 gap-4 mt-6">
                    ${workflowOptions.length ? workflowOptions.map((item) => {
                        const itemLoops = loops.filter((loop) => Number(loop.item_id) === Number(item.id));
                        const doneCount = itemLoops.filter((loop) => loop.status === 'done').length;
                        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>
                                        <h4 class="text-xl font-bold text-white">${escapeHtml(item.title)}</h4>
                                        <p class="text-sm text-gray-400 mt-3">${doneCount}/${itemLoops.length || 0} public-success loops complete for this workflow.</p>
                                    </div>
                                    <div class="flex flex-wrap gap-2 shrink-0">
                                        ${itemLoops.map((loop) => `<span class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-gray-300">${escapeHtml(loop.title)}</span>`).join('')}
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('') : '<p class="text-sm text-gray-500">No workflows currently inside Division 6.</p>'}
                </div>
            </div>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'reviews' ? '' : 'hidden'}" data-div6-work-panel="reviews">
                <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">Review Request Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div6ReviewItemId" 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="div6ReviewTitle" 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="Review request title">
                            <input id="div6ReviewDate" 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)]">
                            <textarea id="div6ReviewNotes" 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="Review message notes or follow-up detail"></textarea>
                            <button id="createDiv6ReviewBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Review Loop</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">Review Queue</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${renderDiv6LoopCards(reviewLoops, 'No review loops yet.')}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'support' ? '' : 'hidden'}" data-div6-work-panel="support">
                <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">Support Loop Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div6SupportItemId" 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="div6SupportTitle" 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="Support loop title">
                            <input id="div6SupportDate" 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)]">
                            <textarea id="div6SupportNotes" 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="Support notes or promised follow-up"></textarea>
                            <button id="createDiv6SupportBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Support Loop</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">Support Queue</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${renderDiv6LoopCards(supportLoops, 'No support loops yet.')}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'battleplans' ? '' : 'hidden'}" data-div6-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 6 Strat-Gen</div>
                        <p class="text-sm text-gray-400 mt-1">Use battle plans here to drive review growth, support continuity, and repeat demand from satisfied clients.</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <button class="div6-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="div6-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="div6-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="div6-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="div6BattlePlanGrid"></div>
            </div>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'followups' ? '' : 'hidden'}" data-div6-work-panel="followups">
                <div class="grid grid-cols-1 gap-4">
                    ${renderDiv6LoopCards(activeFollowups, 'No active follow-up loops right now.')}
                </div>
            </div>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'referrals' ? '' : 'hidden'}" data-div6-work-panel="referrals">
                <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">Referral / Upsell Loop Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <select id="div6ReferralItemId" 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="div6ReferralTitle" 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="Referral or upsell loop title">
                            <input id="div6ReferralDate" 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)]">
                            <textarea id="div6ReferralNotes" 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="Upsell angle, support package note, or referral ask"></textarea>
                            <button id="createDiv6ReferralBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Referral Loop</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">Referral / Upsell Queue</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${renderDiv6LoopCards(referralLoops, 'No referral or upsell loops yet.')}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div6-work-panel ${state.activeDiv6WorkTab === 'continuity' ? '' : 'hidden'}" data-div6-work-panel="continuity">
                <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">Continuity Reading</p>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-4">
                            ${[
                                ['Reviews', getLatestMetricValue(6, 'reviews') ?? 0, 'Real review growth logged in Div 6 metrics.'],
                                ['Support Tickets', getLatestMetricValue(6, 'support_tickets') ?? 0, 'Live support load.'],
                                ['Open Success Loops', activeFollowups.length, 'Customer-success actions still alive.'],
                                ['Ready From QA', readyFromQa.length, 'New workflows available for public handoff.']
                            ].map(([label, value, body]) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <p class="text-[10px] uppercase tracking-[0.18em] text-gray-500">${label}</p>
                                    <p class="text-2xl font-bold text-white mt-2">${value}</p>
                                    <p class="text-sm text-gray-400 mt-2">${body}</p>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                    <div class="glass-panel rounded-3xl border border-white/10 bg-black/40 p-6">
                        <p class="text-[11px] uppercase tracking-[0.24em] text-gray-500 mb-2">Public Hat Reading</p>
                        <p class="text-sm text-gray-400 mt-4">Division 6 exists to prevent delivery from ending in silence. If the work is good but no review is asked for, no support loop is active, and no referral or upsell step exists, the org is leaking future demand.</p>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.querySelectorAll('.div6-work-tab-btn').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeDiv6WorkTab = btn.dataset.div6WorkTab;
            renderDiv6Work();
        });
    });

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

    const createLoop = async ({ itemIdEl, titleEl, dateEl, notesEl, loopType }) => {
        const title = document.getElementById(titleEl).value.trim();
        if (!title) return showToast('Loop title is required.', 'error');
        await api.addSuccessLoop({
            division_id: 6,
            item_id: document.getElementById(itemIdEl).value || null,
            loop_type: loopType,
            title,
            next_action_date: document.getElementById(dateEl).value || '',
            notes: document.getElementById(notesEl).value.trim(),
            status: 'pending'
        });
        await refreshDiv6WorkData();
        renderDiv6Work();
    };

    document.getElementById('createDiv6ReviewBtn')?.addEventListener('click', () => createLoop({
        itemIdEl: 'div6ReviewItemId',
        titleEl: 'div6ReviewTitle',
        dateEl: 'div6ReviewDate',
        notesEl: 'div6ReviewNotes',
        loopType: 'review_request'
    }));

    document.getElementById('createDiv6SupportBtn')?.addEventListener('click', () => createLoop({
        itemIdEl: 'div6SupportItemId',
        titleEl: 'div6SupportTitle',
        dateEl: 'div6SupportDate',
        notesEl: 'div6SupportNotes',
        loopType: 'support_checkin'
    }));

    document.getElementById('createDiv6ReferralBtn')?.addEventListener('click', () => createLoop({
        itemIdEl: 'div6ReferralItemId',
        titleEl: 'div6ReferralTitle',
        dateEl: 'div6ReferralDate',
        notesEl: 'div6ReferralNotes',
        loopType: 'referral_upsell'
    }));

    document.querySelectorAll('.div6-loop-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            const loop = loops.find((entry) => Number(entry.id) === Number(btn.dataset.id));
            if (!loop) return;
            await api.updateSuccessLoop(loop.id, { ...loop, status: btn.dataset.status });
            await refreshDiv6WorkData();
            renderDiv6Work();
        });
    });

    document.querySelectorAll('.div6-loop-delete-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.deleteSuccessLoop(btn.dataset.id);
            await refreshDiv6WorkData();
            renderDiv6Work();
        });
    });

    if (state.activeDiv6WorkTab === 'battleplans') {
        state.battlePlansData = state.div6WorkData.battlePlans?.[6] || { plans: [] };
        renderBattlePlan(6, {
            containerId: 'div6BattlePlanGrid',
            aiButtonsSelector: '#dashboardWorkView .div6-ai-bp-gen-btn'
        });
    }
}
