function getOrgHealthSnapshot() {
    const divisions = (state.divisions || []).filter((division) => division.id !== 8);
    let totalTasks = 0;
    let completedTasks = 0;
    let totalWorkflows = 0;

    const divisionPressure = divisions.map((division) => {
        const tasks = division.items.reduce((count, item) => {
            const currentTodos = item.current_todos || [];
            const historyTodos = item.history_todos || [];
            totalTasks += currentTodos.length + historyTodos.length;
            completedTasks += currentTodos.filter((todo) => todo.done).length;
            completedTasks += historyTodos.filter((todo) => todo.done).length;
            return count + currentTodos.filter((todo) => !todo.done).length;
        }, 0);

        totalWorkflows += division.items.length;
        return {
            id: division.id,
            name: getDivisionCopy(division).name,
            workflows: division.items.length,
            openTasks: tasks
        };
    });

    const completionPct = totalTasks === 0 ? 100 : Math.round((completedTasks / totalTasks) * 100);
    const grade = completionPct > 80 ? 'A+' : completionPct > 50 ? 'B' : 'C';
    const openTasks = Math.max(0, totalTasks - completedTasks);
    const openExecutiveOrders = (state.executiveOrders || []).filter((order) => order.status !== 'done').length;
    const idleDivisions = divisionPressure.filter((division) => division.workflows === 0);
    const pressureDivisions = divisionPressure
        .filter((division) => division.openTasks > 0)
        .sort((a, b) => b.openTasks - a.openTasks)
        .slice(0, 3);

    const narrative = grade === 'A+'
        ? 'The org is closing work faster than it is accumulating visible drag.'
        : grade === 'B'
            ? 'The org is moving, but backlog and idle hats are starting to create friction.'
            : 'The org needs intervention. Too much visible work is still open compared with what is being completed.';

    const reasons = [];
    if (totalTasks === 0) {
        reasons.push('No tracked tasks exist yet, so the score reflects an empty board more than proven execution.');
    } else {
        reasons.push(`${completedTasks} of ${totalTasks} tracked tasks are currently marked done, which is a ${completionPct}% visible completion rate.`);
    }
    if (idleDivisions.length > 0) {
        reasons.push(`${idleDivisions.map((division) => division.name).join(', ')} currently have no active workflow, so parts of the org loop are idle.`);
    }
    if (pressureDivisions.length > 0) {
        reasons.push(`${pressureDivisions.map((division) => `${division.name} (${division.openTasks} open)`).join(', ')} are carrying the heaviest visible task load right now.`);
    }
    if (openExecutiveOrders > 0) {
        reasons.push(`${openExecutiveOrders} executive order${openExecutiveOrders === 1 ? ' is' : 's are'} still open, which means command decisions are waiting on downstream execution.`);
    }
    if (idleDivisions.length === 0 && pressureDivisions.length === 0 && openExecutiveOrders === 0) {
        reasons.push('No major idle hats or visible control gaps are standing out from the current board snapshot.');
    }

    return {
        grade,
        completionPct,
        totalTasks,
        completedTasks,
        openTasks,
        totalWorkflows,
        openExecutiveOrders,
        idleDivisions,
        pressureDivisions,
        narrative,
        reasons
    };
}

function updateGlobalHealth() {
    const snapshot = getOrgHealthSnapshot();
    const badge = document.getElementById('globalHealthScore');
    const icon = document.getElementById('healthIcon');
    if (!badge || !icon) return snapshot;

    if (snapshot.grade === 'A+') {
        badge.textContent = 'A+';
        badge.className = 'font-bold text-green-400';
        icon.className = 'fas fa-heart text-green-400 group-hover:animate-pulse';
    } else if (snapshot.grade === 'B') {
        badge.textContent = 'B';
        badge.className = 'font-bold text-yellow-400';
        icon.className = 'fas fa-heart text-yellow-400 group-hover:animate-pulse';
    } else {
        badge.textContent = 'C';
        badge.className = 'font-bold text-red-400';
        icon.className = 'fas fa-heart text-red-400 group-hover:animate-pulse';
    }

    return snapshot;
}

function renderHealthModal() {
    const container = document.getElementById('healthModalContent');
    if (!container) return;
    const snapshot = getOrgHealthSnapshot();
    const gradeTone = snapshot.grade === 'A+' ? 'text-green-400' : snapshot.grade === 'B' ? 'text-yellow-400' : 'text-red-400';

    container.innerHTML = `
        <div class="grid md:grid-cols-[220px_1fr] gap-4 mb-6">
            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-5">
                <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500 mb-2">Current Grade</p>
                <div class="flex items-end gap-3">
                    <span class="text-5xl font-black ${gradeTone}">${escapeHtml(snapshot.grade)}</span>
                    <span class="text-sm text-gray-400 mb-1">${escapeHtml(`${snapshot.completionPct}% completion`)}</span>
                </div>
            </div>
            <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-5">
                <p class="text-[10px] uppercase tracking-[0.24em] text-cyan-300 mb-2">Why It Looks Like This</p>
                <p class="text-sm text-gray-200 leading-relaxed">${escapeHtml(snapshot.narrative)}</p>
            </div>
        </div>
        <div class="grid sm:grid-cols-2 xl:grid-cols-4 gap-3 mb-6">
            ${[
                ['Active workflows', snapshot.totalWorkflows],
                ['Open tasks', snapshot.openTasks],
                ['Completed tasks', snapshot.completedTasks],
                ['Open ED orders', snapshot.openExecutiveOrders]
            ].map(([label, value]) => `
                <div class="rounded-2xl border border-white/10 bg-black/30 px-4 py-4">
                    <p class="text-[10px] uppercase tracking-[0.22em] text-gray-500 mb-1">${escapeHtml(label)}</p>
                    <p class="text-2xl font-extrabold text-white">${escapeHtml(String(value))}</p>
                </div>
            `).join('')}
        </div>
        <div class="grid xl:grid-cols-[1.2fr_0.8fr] gap-4">
            <div class="rounded-2xl border border-white/10 bg-black/30 p-5">
                <p class="text-[10px] uppercase tracking-[0.24em] text-indigo-300 mb-3">Reason Breakdown</p>
                <div class="flex flex-col gap-3">
                    ${snapshot.reasons.map((reason) => `
                        <div class="rounded-xl border border-white/8 bg-white/[0.03] px-4 py-3 text-sm text-gray-300 leading-relaxed">
                            ${escapeHtml(reason)}
                        </div>
                    `).join('')}
                </div>
            </div>
            <div class="rounded-2xl border border-white/10 bg-black/30 p-5">
                <p class="text-[10px] uppercase tracking-[0.24em] text-emerald-300 mb-3">Pressure Points</p>
                <div class="flex flex-col gap-3">
                    ${(snapshot.pressureDivisions.length ? snapshot.pressureDivisions : [{ name: 'No visible pressure spike', openTasks: 0, workflows: snapshot.totalWorkflows }]).map((division) => `
                        <div class="rounded-xl border border-white/8 bg-white/[0.03] px-4 py-3">
                            <div class="flex items-center justify-between gap-3">
                                <p class="text-sm font-semibold text-white">${escapeHtml(division.name)}</p>
                                <span class="text-xs text-gray-400">${escapeHtml(`${division.openTasks} open tasks`)}</span>
                            </div>
                            <p class="text-xs text-gray-500 mt-1">${escapeHtml(`${division.workflows} active workflow${division.workflows === 1 ? '' : 's'} in this hat`)}</p>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
    `;
}

function openHealthModal() {
    const modal = document.getElementById('healthModal');
    if (!modal) return;
    renderHealthModal();
    modal.classList.remove('hidden');
    requestAnimationFrame(() => {
        modal.classList.remove('opacity-0');
        modal.querySelector('.glass-panel')?.classList.remove('scale-95');
    });
}

function closeHealthModal() {
    const modal = document.getElementById('healthModal');
    if (!modal) return;
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel')?.classList.add('scale-95');
    setTimeout(() => modal.classList.add('hidden'), 250);
}

function initHealthUi() {
    const openBtn = document.getElementById('openHealthBtn');
    const closeBtn = document.getElementById('closeHealthModal');
    const modal = document.getElementById('healthModal');
    if (!openBtn || !closeBtn || !modal || openBtn.dataset.bound === '1') return;

    openBtn.dataset.bound = '1';
    openBtn.addEventListener('click', openHealthModal);
    closeBtn.addEventListener('click', closeHealthModal);
    modal.addEventListener('click', (event) => {
        if (event.target === modal) closeHealthModal();
    });
}
