function getRoutingRecommendation(record) {
    if (record.divisionId === 2) return 'Maintain outbound contact and proposal follow-up until the lead is closed or disqualified.';
    if (record.divisionId === 3) return 'Send clear payment / invoice communication and confirm treasury handoff in writing.';
    if (record.divisionId === 4) return 'Request missing assets, confirm production milestones, and keep updates concise.';
    if (record.divisionId === 5) return 'Prepare QA-ready update messaging and make release conditions explicit.';
    if (record.divisionId === 6) return 'Client-success line should request feedback, reviews, and confirm the next support step.';
    if (record.divisionId === 7) return 'Escalate structural, legal, or policy-sensitive communication through Division 7.';
    return 'Keep the communication line current and route the next owner clearly.';
}

function getFollowupSuggestion(record) {
    const pendingCount = record.pendingTodos.length;
    if (record.divisionId === 2) return `Follow up on outreach or discovery status. ${pendingCount} open task(s) still depend on communication.`;
    if (record.divisionId === 3) return `Confirm payment / invoice status before work proceeds. ${pendingCount} treasury task(s) remain open.`;
    if (record.divisionId === 4) return `Send a production update or request the missing client input blocking delivery.`;
    if (record.divisionId === 5) return `Tell the client what QA is waiting for and what release gate is still open.`;
    if (record.divisionId === 6) return `Use the public/client-success line to ask for feedback, reviews, or support confirmation.`;
    return `Keep the current line active and make the next owner explicit.`;
}

function renderDiv1Work() {
    const container = document.getElementById('edWorkContainer');
    if (!container || state.activeDashboardDivId !== 1 || !state.div1WorkData) return;

    const templates = state.div1WorkData.templates || [];
    const activeTemplates = templates.filter((template) => template.status === 'active');
    const allRecords = getAllActiveWorkflowRecords().filter((record) => record.item?.title !== '⚡ Executive Orders');
    const activeOrders = state.executiveOrders || [];
    const inboundOrders = getTargetDivisionOrders(1, { includeDone: true });
    const crossDivisionPressure = allRecords
        .filter((record) => record.divisionId !== 1 && record.pendingTodos.length)
        .sort((a, b) => b.pendingTodos.length - a.pendingTodos.length || a.divisionId - b.divisionId)
        .slice(0, 8);
    const followUpQueue = allRecords
        .filter((record) => record.divisionId !== 8 && record.item?.title)
        .sort((a, b) => b.pendingTodos.length - a.pendingTodos.length || a.divisionId - b.divisionId)
        .slice(0, 8);
    const linesCards = [
        ['Emails Sent', getLatestMetricValue(1, 'emails_sent') ?? 0, 'Daily outbound and internal line volume.'],
        ['Response Rate', `${getLatestMetricValue(1, 'response_rate') ?? 0}%`, 'Communication effectiveness tracked in Div 1.'],
        ['Active Templates', activeTemplates.length, 'Reusable lines currently approved for use.'],
        ['Incoming ED Orders', inboundOrders.filter((order) => order.status !== 'done').length, 'Division 1 directives waiting on execution.']
    ];
    const workTabs = [
        ['lines', 'Lines', 'fa-comments'],
        ['routing', 'Routing', 'fa-share-nodes'],
        ['templates', 'Templates', 'fa-envelope-open-text'],
        ['battleplans', 'Battle Plans', 'fa-chess-knight'],
        ['dispatches', 'Dispatches', 'fa-bullhorn'],
        ['followups', 'Follow-Ups', 'fa-reply'],
        ['standards', 'Standards', 'fa-book-open']
    ];
    const trainings = state.trainingsData?.modules || [];

    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 1 Work Console</p>
                        <h3 class="text-3xl font-bold text-white mt-2">Lines, Routing, and Message Control</h3>
                        <p class="text-sm text-gray-400 mt-3 max-w-3xl">Division 1 keeps communication lines clean across the org. It owns message clarity, routing discipline, internal dispatch support, and the reusable templates that keep client and internal communication sharp.</p>
                    </div>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3 min-w-0 xl:min-w-[420px]">
                        ${linesCards.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="div1-work-tab-btn px-4 py-2.5 rounded-xl border text-sm font-semibold transition ${state.activeDiv1WorkTab === id ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-div1-work-tab="${id}">
                            <i class="fas ${icon} mr-2"></i>${label}
                        </button>
                    `).join('')}
                </div>
            </section>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'lines' ? '' : 'hidden'}" data-div1-work-panel="lines">
                <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">Communication Pressure</p>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-4">
                            ${[
                                ['Lead demand', getLatestMetricValue(2, 'leads') ?? 0, 'Demand that will require outbound and follow-up lines.'],
                                ['Calls made', getLatestMetricValue(2, 'calls') ?? 0, 'Active discovery / sales line intensity.'],
                                ['Support tickets', getLatestMetricValue(6, 'support_tickets') ?? 0, 'Public/client line pressure that may need comms support.'],
                                ['Reviews obtained', getLatestMetricValue(6, 'reviews') ?? 0, 'Proof line generated by successful follow-up.']
                            ].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">Line Reading</p>
                        <p class="text-sm text-gray-400 mt-4">Division 1 is not just “send emails”. It controls whether the right person gets the right message at the right time. This view should tell you if communication is helping the org flow or letting items stall between hats.</p>
                        <div class="mt-5 flex flex-col gap-3">
                            ${crossDivisionPressure.slice(0, 4).map((record) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <div class="flex items-center justify-between gap-3">
                                        <h4 class="text-sm font-bold text-white">${escapeHtml(record.item.title)}</h4>
                                        <span class="text-xs text-indigo-200">${escapeHtml(record.divisionName)}</span>
                                    </div>
                                    <p class="text-sm text-gray-400 mt-2">${getFollowupSuggestion(record)}</p>
                                </div>
                            `).join('') || '<p class="text-sm text-gray-500">No communication pressure detected.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'routing' ? '' : 'hidden'}" data-div1-work-panel="routing">
                <div class="grid grid-cols-1 gap-4">
                    ${crossDivisionPressure.length ? crossDivisionPressure.map((record) => `
                        <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>
                                    <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">${escapeHtml(record.divisionName)}</p>
                                    <h4 class="text-xl font-bold text-white mt-2">${escapeHtml(record.item.title)}</h4>
                                    <p class="text-sm text-gray-400 mt-3">${getRoutingRecommendation(record)}</p>
                                    <div class="mt-3 flex flex-wrap gap-2">
                                        ${record.pendingTodos.slice(0, 3).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 todos in this lane.</span>'}
                                    </div>
                                </div>
                                <button class="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white div1-open-division-btn" data-division="${record.divisionId}">Open ${escapeHtml(record.divisionName)}</button>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No live routing pressure right now.</p>'}
                </div>
            </div>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'templates' ? '' : 'hidden'}" data-div1-work-panel="templates">
                <div class="grid grid-cols-1 xl:grid-cols-[0.9fr_1.25fr] 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">Template Creation</p>
                        <div class="mt-5 flex flex-col gap-3">
                            <input id="div1TemplateTitle" 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="Template title">
                            <select id="div1TemplateType" 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="client_follow_up">Client follow-up</option>
                                <option value="internal_update">Internal update</option>
                                <option value="asset_request">Asset request</option>
                                <option value="review_request">Review request</option>
                                <option value="general">General</option>
                            </select>
                            <select id="div1TemplateStatus" 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="active" selected>Active</option>
                                <option value="draft">Draft</option>
                                <option value="archived">Archived</option>
                            </select>
                            <textarea id="div1TemplateContent" rows="6" 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="Reusable communication line"></textarea>
                            <button id="createDiv1TemplateBtn" class="mt-2 px-5 py-3 rounded-xl bg-[var(--dash-accent)] text-white font-bold hover:brightness-110 transition">Create Template</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">Template Library</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${templates.length ? templates.map((template) => `
                                <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(template.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(template.template_type.replaceAll('_', ' '))}</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(template.status)}</span>
                                            </div>
                                            <p class="text-sm text-gray-400 mt-3 whitespace-pre-line">${escapeHtml(template.content || '')}</p>
                                        </div>
                                        <div class="flex flex-wrap gap-2 shrink-0">
                                            ${template.status !== 'active' ? `<button class="div1-template-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="${template.id}" data-status="active">Activate</button>` : ''}
                                            ${template.status !== 'draft' ? `<button class="div1-template-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="${template.id}" data-status="draft">Draft</button>` : ''}
                                            ${template.status !== 'archived' ? `<button class="div1-template-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="${template.id}" data-status="archived">Archive</button>` : ''}
                                            <button class="div1-template-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="${template.id}">Delete</button>
                                        </div>
                                    </div>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No templates yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'battleplans' ? '' : 'hidden'}" data-div1-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 1 Strat-Gen</div>
                        <p class="text-sm text-gray-400 mt-1">Use battle plans here to set communication cadence, follow-up targets, and routing priorities for the org.</p>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <button class="div1-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="div1-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="div1-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="div1-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="div1BattlePlanGrid"></div>
            </div>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'dispatches' ? '' : 'hidden'}" data-div1-work-panel="dispatches">
                <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">Incoming Dispatches</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${inboundOrders.length ? inboundOrders.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 incoming Division 1 orders.</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">Cross-Division Message Needs</p>
                        <div class="flex flex-col gap-4 mt-4">
                            ${crossDivisionPressure.length ? crossDivisionPressure.slice(0, 6).map((record) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <div class="flex items-center justify-between gap-3">
                                        <h4 class="text-sm font-bold text-white">${escapeHtml(record.item.title)}</h4>
                                        <span class="text-xs text-indigo-200">${escapeHtml(record.divisionName)}</span>
                                    </div>
                                    <p class="text-sm text-gray-400 mt-2">${getRoutingRecommendation(record)}</p>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No cross-division dispatch pressure right now.</p>'}
                        </div>
                    </div>
                </div>
            </div>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'followups' ? '' : 'hidden'}" data-div1-work-panel="followups">
                <div class="grid grid-cols-1 gap-4">
                    ${followUpQueue.length ? followUpQueue.map((record) => `
                        <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>
                                    <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">${escapeHtml(record.divisionName)}</p>
                                    <h4 class="text-xl font-bold text-white mt-2">${escapeHtml(record.item.title)}</h4>
                                    <p class="text-sm text-gray-400 mt-3">${getFollowupSuggestion(record)}</p>
                                    <div class="mt-3 flex flex-wrap gap-2">
                                        ${record.pendingTodos.slice(0, 4).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 pending todos on this workflow.</span>'}
                                    </div>
                                </div>
                                <button class="px-4 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-sm text-white div1-open-division-btn" data-division="${record.divisionId}">Open ${escapeHtml(record.divisionName)}</button>
                            </div>
                        </div>
                    `).join('') : '<p class="text-sm text-gray-500">No follow-up queue right now.</p>'}
                </div>
            </div>

            <div class="div1-work-panel ${state.activeDiv1WorkTab === 'standards' ? '' : 'hidden'}" data-div1-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">Training Standards</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${trainings.length ? trainings.map((module) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <div class="flex items-center justify-between gap-3">
                                        <div>
                                            <h4 class="text-base font-bold text-white">${escapeHtml(module.title)}</h4>
                                            <p class="text-sm text-gray-400 mt-1">${escapeHtml(module.read_time || '')}</p>
                                        </div>
                                        <button class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white div1-open-training-btn">Open Training</button>
                                    </div>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No training modules loaded 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">Approved Lines</p>
                        <div class="flex flex-col gap-3 mt-4">
                            ${activeTemplates.length ? activeTemplates.map((template) => `
                                <div class="rounded-2xl border border-white/10 bg-white/[0.03] p-4">
                                    <h4 class="text-sm font-bold text-white">${escapeHtml(template.title)}</h4>
                                    <p class="text-sm text-gray-400 mt-2">${escapeHtml(template.content || '')}</p>
                                </div>
                            `).join('') : '<p class="text-sm text-gray-500">No active templates yet.</p>'}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    `;

    container.querySelectorAll('[data-div1-work-tab]').forEach((btn) => {
        btn.addEventListener('click', () => {
            state.activeDiv1WorkTab = btn.dataset.div1WorkTab;
            renderDiv1Work();
        });
    });
    container.querySelectorAll('.div1-open-division-btn').forEach((btn) => {
        btn.addEventListener('click', () => openDashboard(Number(btn.dataset.division)));
    });
    container.querySelectorAll('.div1-open-training-btn').forEach((btn) => {
        btn.addEventListener('click', () => document.querySelector('.dash-nav-btn[data-view="dashboardTrainingView"]')?.click());
    });
    container.querySelectorAll('.div1-template-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.updateCommunicationTemplate(btn.dataset.id, { status: btn.dataset.status });
            await refreshDiv1WorkData();
            renderDiv1Work();
        });
    });
    container.querySelectorAll('.div1-template-delete-btn').forEach((btn) => {
        btn.addEventListener('click', () => customConfirm('Delete this communication template?', async () => {
            await api.deleteCommunicationTemplate(btn.dataset.id);
            await refreshDiv1WorkData();
            renderDiv1Work();
        }));
    });

    document.getElementById('createDiv1TemplateBtn')?.addEventListener('click', async () => {
        const title = document.getElementById('div1TemplateTitle')?.value.trim();
        const templateType = document.getElementById('div1TemplateType')?.value || 'general';
        const status = document.getElementById('div1TemplateStatus')?.value || 'active';
        const content = document.getElementById('div1TemplateContent')?.value.trim();
        if (!title) return showToast('Template title is required.', 'warning');
        await api.addCommunicationTemplate({
            division_id: 1,
            title,
            template_type: templateType,
            status,
            content
        });
        await refreshDiv1WorkData();
        renderDiv1Work();
        showToast('Communication template created.', 'success');
    });

    renderBattlePlan(1, {
        containerId: 'div1BattlePlanGrid',
        aiButtonsSelector: '#dashboardWorkView .div1-ai-bp-gen-btn'
    });
}
