function getTodayDateValue() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

async function refreshActiveAppState({ maintainFocus = true, includeAgents = false } = {}) {
    if (state.liveSyncInFlight) return;
    state.liveSyncInFlight = true;
    try {
        await initBoard(maintainFocus);
        const divId = state.activeDashboardDivId;
        if (!divId) return;

        const [metricsData, battlePlansData, trainingsData] = await Promise.all([
            api.getMetrics(divId),
            api.getBattlePlans(divId),
            api.getTrainings(divId)
        ]);
        state.metricsData = metricsData;
        state.battlePlansData = battlePlansData;
        state.trainingsData = trainingsData;

        const activeView = state.activeDashboardView;
        if (activeView === 'dashboardMetricsView') renderMetrics(divId);
        if (activeView === 'dashboardTrainingView') renderTraining(divId);
        if (activeView === 'dashboardBattlePlanView') renderBattlePlan(divId);
        if (activeView === 'dashboardWorkView') renderDivisionWork();
        if (activeView === 'dashboardBoardView') renderDashboardKanban(divId);
        if (activeView === 'dashboardSkillsView') renderSkills(divId);
        if (activeView === 'dashboardAIView') await loadAIConversations(divId, state.activeConversationId);
        if (includeAgents || activeView === 'dashboardAgentsView') {
            await refreshAgentsData();
            renderAgentsView();
            renderMemoryExplorer();
        }
    } finally {
        state.liveSyncInFlight = false;
    }
}

function startLiveSyncLoop() {
    if (state.liveSyncTimer) return;
    state.liveSyncTimer = setInterval(async () => {
        if (document.hidden) return;
        if (!state.settings?.onboarding_complete) return;
        try {
            await refreshActiveAppState({ maintainFocus: true, includeAgents: false });
        } catch (_) {}
    }, 12000);
}

function stopLiveSyncLoop() {
    if (!state.liveSyncTimer) return;
    clearInterval(state.liveSyncTimer);
    state.liveSyncTimer = null;
}

function getStartOfWeek(dateStr) {
    const base = new Date(`${dateStr}T12:00:00`);
    const day = (base.getDay() + 6) % 7;
    base.setDate(base.getDate() - day);
    return base.toISOString().slice(0, 10);
}

function getDashboardHistoryRange() {
    const today = getTodayDateValue();
    if (state.dashboardHistoryPreset === 'today') {
        return { from: today, to: today };
    }
    if (state.dashboardHistoryPreset === 'week') {
        return { from: getStartOfWeek(today), to: today };
    }
    return {
        from: state.dashboardHistoryFrom || today,
        to: state.dashboardHistoryTo || state.dashboardHistoryFrom || today
    };
}

function isLiveHistoryMode() {
    return state.dashboardHistoryPreset === 'live';
}

function getVisibleDivisions() {
    return state.boardHistoryDivisions || state.divisions;
}

function getDivisionById(divId) {
    return getVisibleDivisions().find((div) => div.id === divId) || state.divisions.find((div) => div.id === divId);
}

function recordTouchesDashboardRange(record, keys = []) {
    if (isLiveHistoryMode()) return true;
    const { from, to } = getDashboardHistoryRange();
    const values = [
        record?.work_date,
        record?.invoice_date,
        record?.meeting_date,
        record?.due_date,
        record?.next_action_date,
        record?.last_checked_at,
        record?.created_at,
        record?.updated_at,
        record?.completed_at,
        ...keys.map((key) => record?.[key])
    ]
        .filter(Boolean)
        .map((value) => String(value).slice(0, 10));

    return values.some((value) => value >= from && value <= to);
}

function filterRecordsByDashboardRange(records, keys = []) {
    return isLiveHistoryMode() ? records : records.filter((record) => recordTouchesDashboardRange(record, keys));
}

function isWorkDivision(divId) {
    return divId === 8 || divId === 7 || divId === 6 || divId === 5 || divId === 4 || divId === 3 || divId === 2 || divId === 1;
}

function renderDivisionWork() {
    if (typeof renderDashboardDateToolbar === 'function') renderDashboardDateToolbar('dashboardWorkToolbar');
    if (state.activeDashboardDivId === 1) return renderDiv1Work();
    if (state.activeDashboardDivId === 2) return renderDiv2Work();
    if (state.activeDashboardDivId === 3) return renderDiv3Work();
    if (state.activeDashboardDivId === 4) return renderDiv4Work();
    if (state.activeDashboardDivId === 5) return renderDiv5Work();
    if (state.activeDashboardDivId === 6) return renderDiv6Work();
    if (state.activeDashboardDivId === 8) return renderEdWork();
    if (state.activeDashboardDivId === 7) return renderDiv7Work();
}

function getWorkMetricsBundle(divId) {
    return state.edWorkData?.metrics?.[divId]
        || state.div7WorkData?.metrics?.[divId]
        || state.div6WorkData?.metrics?.[divId]
        || state.div5WorkData?.metrics?.[divId]
        || state.div4WorkData?.metrics?.[divId]
        || state.div3WorkData?.metrics?.[divId]
        || state.div2WorkData?.metrics?.[divId]
        || state.div1WorkData?.metrics?.[divId]
        || null;
}

function getEdMetricsBundle(divId) {
    return getWorkMetricsBundle(divId);
}

function getLatestMetricValue(divId, metricKey) {
    const bundle = getEdMetricsBundle(divId);
    if (!bundle?.data) return null;
    const rows = bundle.data
        .filter((row) => row.metric_key === metricKey && row.is_mock === 0)
        .sort((a, b) => String(b.date).localeCompare(String(a.date)));
    if (!rows.length) return null;
    return Number(rows[0].value) || 0;
}

function getOverdueDailyPlanCount(divId) {
    const plans = state.edWorkData?.battlePlans?.[divId]?.plans
        || state.div7WorkData?.battlePlans?.[divId]?.plans
        || state.div6WorkData?.battlePlans?.[divId]?.plans
        || state.div5WorkData?.battlePlans?.[divId]?.plans
        || state.div4WorkData?.battlePlans?.[divId]?.plans
        || state.div3WorkData?.battlePlans?.[divId]?.plans
        || state.div2WorkData?.battlePlans?.[divId]?.plans
        || state.div1WorkData?.battlePlans?.[divId]?.plans
        || [];
    const today = new Date().toISOString().split('T')[0];
    return plans.filter((plan) => plan.period === 'daily' && !plan.done && String(plan.created_at || '').slice(0, 10) < today).length;
}

function getPendingTaskCount(divId) {
    const div = getDivisionById(divId);
    if (!div) return 0;
    return div.items.reduce((sum, item) => sum + (item.current_todos || []).filter((todo) => !todo.done).length, 0);
}

function getWorkloadSummary(divId) {
    const div = getDivisionById(divId);
    if (!div) return { workflows: 0, pendingTasks: 0 };
    return {
        workflows: div.items.length,
        pendingTasks: getPendingTaskCount(divId)
    };
}

function getDivisionItems(divId) {
    return getDivisionById(divId)?.items || [];
}

function getDivisionWorkflowTitles(divId, limit = 3) {
    return getDivisionItems(divId).slice(0, limit).map((item) => item.title);
}

function getDivisionMetricStatus(divId) {
    const bundle = getEdMetricsBundle(divId);
    const today = new Date().toISOString().split('T')[0];
    const hasToday = bundle?.data?.some((row) => row.is_mock === 0 && row.date === today);
    return hasToday ? 'Current' : 'Missing';
}

function getHatLoadLabel(lane) {
    const pressure = lane.pendingTasks + (lane.overduePlans * 2);
    if (pressure >= 12) return 'Critical load';
    if (pressure >= 6) return 'Heavy load';
    if (pressure >= 3) return 'Controlled';
    return 'Light';
}

function buildExecutiveOrders(laneSummaries, divisionsMissingMetrics) {
    const orders = [];
    const ranked = [...laneSummaries].sort((a, b) => (b.pendingTasks + b.overduePlans * 2) - (a.pendingTasks + a.overduePlans * 2));
    const topLane = ranked[0];

    if (topLane && (topLane.pendingTasks > 0 || topLane.overduePlans > 0)) {
        orders.push({
            title: `Stabilize ${topLane.name}`,
            body: `Redirect ED attention to ${topLane.name}. It currently carries ${topLane.pendingTasks} pending tasks and ${topLane.overduePlans} overdue daily plans.`,
            divisionId: topLane.id
        });
    }

    if (divisionsMissingMetrics.length) {
        orders.push({
            title: 'Restore stats discipline',
            body: `Get same-day metric logging restored in ${divisionsMissingMetrics.length} division(s) before close of business.`,
            divisionId: 8
        });
    }

    const treasury = laneSummaries.find((lane) => lane.id === 3);
    const marketing = laneSummaries.find((lane) => lane.id === 2);
    if (treasury && marketing && treasury.pendingTasks > 0 && marketing.workflows > 0) {
        orders.push({
            title: 'Align sales-to-cash handoff',
            body: 'Review whether newly closed work is moving cleanly from dissemination into treasury deposit/invoice control.',
            divisionId: 3
        });
    }

    const delivery = laneSummaries.find((lane) => lane.id === 4);
    const qa = laneSummaries.find((lane) => lane.id === 5);
    if (delivery && qa && (delivery.pendingTasks > 0 || qa.pendingTasks > 0)) {
        orders.push({
            title: 'Protect delivery quality',
            body: 'Confirm QA is not lagging behind technical delivery and that launch readiness is being held before release.',
            divisionId: 5
        });
    }

    const publicDiv = laneSummaries.find((lane) => lane.id === 6);
    if (publicDiv && publicDiv.workflows > 0) {
        orders.push({
            title: 'Keep public satisfaction visible',
            body: 'Check that review requests, follow-ups, and support continuity are active for completed and near-complete client work.',
            divisionId: 6
        });
    }

    return orders.slice(0, 5);
}

function getTargetDivisionOrders(divId, { includeDone = false } = {}) {
    return (state.executiveOrders || [])
        .filter((order) => Number(order.target_division_id) === Number(divId))
        .filter((order) => includeDone || order.status !== 'done')
        .sort((a, b) => {
            const statusRank = { open: 0, in_progress: 1, done: 2 };
            const priorityRank = { high: 0, medium: 1, low: 2 };
            return (statusRank[a.status] ?? 9) - (statusRank[b.status] ?? 9)
                || (priorityRank[a.priority] ?? 9) - (priorityRank[b.priority] ?? 9)
                || String(b.created_at || '').localeCompare(String(a.created_at || ''));
        });
}

function getAllActiveWorkflowRecords() {
    return getVisibleDivisions().flatMap((division) =>
        (division.items || []).map((item) => ({
            divisionId: division.id,
            divisionName: getDivisionCopy(division).name,
            item,
            pendingTodos: (item.current_todos || []).filter((todo) => !todo.done),
            doneTodos: (item.current_todos || []).filter((todo) => todo.done)
        }))
    );
}

async function refreshEdWorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.edWorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        orders: state.executiveOrders
    };
}

async function refreshDiv7WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, policiesData, meetingsData, risksData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getPolicies(7),
        api.getMeetings(7),
        api.getRisks(7),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div7WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        policies: filterRecordsByDashboardRange(policiesData.policies || [], ['created_at', 'updated_at']),
        meetings: filterRecordsByDashboardRange(meetingsData.meetings || [], ['meeting_date', 'created_at', 'updated_at']),
        risks: filterRecordsByDashboardRange(risksData.risks || [], ['created_at', 'updated_at']),
        orders: state.executiveOrders
    };
}

async function refreshDiv1WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, templatesData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getCommunicationTemplates(1),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div1WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        templates: filterRecordsByDashboardRange(templatesData.templates || [], ['created_at', 'updated_at']),
        orders: state.executiveOrders
    };
}

async function refreshDiv2WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, briefsData, treasuryData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getCampaignBriefs(2),
        api.getTreasuryCases(3),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div2WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        briefs: filterRecordsByDashboardRange(briefsData.briefs || [], ['created_at', 'updated_at']),
        treasuryCases: filterRecordsByDashboardRange(treasuryData.cases || [], ['created_at', 'updated_at', 'due_date']),
        orders: state.executiveOrders
    };
}

async function refreshDiv3WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, casesData, invoicesData, profileData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getTreasuryCases(3),
        api.getInvoices(3),
        api.getInvoiceProfile(),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div3WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        cases: filterRecordsByDashboardRange(casesData.cases || [], ['created_at', 'updated_at', 'due_date']),
        invoices: filterRecordsByDashboardRange(invoicesData.invoices || [], ['invoice_date', 'created_at', 'updated_at']),
        invoiceProfile: profileData.profile || {},
        orders: state.executiveOrders
    };
}

async function refreshDiv4WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, assetsData, stagingData, scopeData, treasuryData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getProductionAssets(4),
        api.getStagingRuns(4),
        api.getScopeControls(4),
        api.getTreasuryCases(3),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div4WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        assets: filterRecordsByDashboardRange(assetsData.assets || [], ['created_at', 'updated_at']),
        stagingRuns: filterRecordsByDashboardRange(stagingData.runs || [], ['created_at', 'updated_at', 'last_checked_at']),
        scopeControls: filterRecordsByDashboardRange(scopeData.controls || [], ['created_at', 'updated_at']),
        treasuryCases: filterRecordsByDashboardRange(treasuryData.cases || [], ['created_at', 'updated_at', 'due_date']),
        orders: state.executiveOrders
    };
}

async function refreshDiv5WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, checksData, gatesData, stagingData, assetsData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getQaChecks(5),
        api.getReleaseGates(5),
        api.getStagingRuns(4),
        api.getProductionAssets(4),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div5WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        checks: filterRecordsByDashboardRange(checksData.checks || [], ['created_at', 'updated_at']),
        gates: filterRecordsByDashboardRange(gatesData.gates || [], ['created_at', 'updated_at']),
        stagingRuns: filterRecordsByDashboardRange(stagingData.runs || [], ['created_at', 'updated_at', 'last_checked_at']),
        assets: filterRecordsByDashboardRange(assetsData.assets || [], ['created_at', 'updated_at']),
        orders: state.executiveOrders
    };
}

async function refreshDiv6WorkData() {
    const allDivisions = state.divisions.map((entry) => entry.id);
    const [metricsBundles, battlePlanBundles, loopsData, gatesData, checksData, stagingData, assetsData, ordersData] = await Promise.all([
        Promise.all(allDivisions.map(async (id) => [id, await api.getMetrics(id)])),
        Promise.all(allDivisions.map(async (id) => [id, await api.getBattlePlans(id)])),
        api.getSuccessLoops(6),
        api.getReleaseGates(5),
        api.getQaChecks(5),
        api.getStagingRuns(4),
        api.getProductionAssets(4),
        api.getExecutiveOrders()
    ]);
    state.executiveOrders = ordersData.orders || [];
    state.div6WorkData = {
        metrics: Object.fromEntries(metricsBundles),
        battlePlans: Object.fromEntries(battlePlanBundles),
        loops: filterRecordsByDashboardRange(loopsData.loops || [], ['created_at', 'updated_at', 'next_action_date']),
        gates: filterRecordsByDashboardRange(gatesData.gates || [], ['created_at', 'updated_at']),
        checks: filterRecordsByDashboardRange(checksData.checks || [], ['created_at', 'updated_at']),
        stagingRuns: filterRecordsByDashboardRange(stagingData.runs || [], ['created_at', 'updated_at', 'last_checked_at']),
        assets: filterRecordsByDashboardRange(assetsData.assets || [], ['created_at', 'updated_at']),
        orders: state.executiveOrders
    };
}
