function getDashboardDefaultWorkDate() {
    if (state.dashboardHistoryPreset === 'today') return state.dashboardHistoryFrom;
    if (state.dashboardHistoryPreset === 'custom') return state.dashboardHistoryTo || state.dashboardHistoryFrom || getTodayDateValue();
    return getTodayDateValue();
}

async function syncBoardHistoryState() {
    if (isLiveHistoryMode()) {
        state.boardHistoryDivisions = null;
        return;
    }
    const { from, to } = getDashboardHistoryRange();
    const data = await api.getBoardHistory(from, to);
    state.boardHistoryDivisions = data.divisions || [];
}

function getDashboardHistorySummary() {
    if (isLiveHistoryMode()) return 'Live board';
    const { from, to } = getDashboardHistoryRange();
    return from === to ? `History for ${from}` : `History from ${from} to ${to}`;
}

function renderDashboardDateToolbar(targetId) {
    const toolbar = document.getElementById(targetId);
    if (!toolbar) return;
    const isCustom = state.dashboardHistoryPreset === 'custom';
    toolbar.innerHTML = `
        <div class="glass-panel rounded-2xl border border-white/10 bg-black/40 px-4 py-4 flex flex-col xl:flex-row xl:items-center gap-4">
            <div class="flex flex-col gap-1 min-w-[180px]">
                <p class="text-[10px] uppercase tracking-[0.24em] text-gray-500">Timeline View</p>
                <p class="text-sm text-white font-semibold">${escapeHtml(getDashboardHistorySummary())}</p>
            </div>
            <div class="flex flex-wrap gap-2">
                ${[
                    ['live', 'Live'],
                    ['today', 'Today'],
                    ['week', 'This Week'],
                    ['custom', 'Custom']
                ].map(([preset, label]) => `
                    <button class="dashboard-history-preset px-3 py-2 rounded-xl border text-xs font-semibold transition ${state.dashboardHistoryPreset === preset ? 'bg-white/10 border-white/20 text-white' : 'bg-white/[0.03] border-white/10 text-gray-400 hover:text-white'}" data-history-preset="${preset}">
                        ${label}
                    </button>
                `).join('')}
            </div>
            <div class="flex flex-col sm:flex-row gap-3 xl:ml-auto">
                <input id="${targetId}From" type="date" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--dash-accent)] ${isCustom ? '' : 'opacity-60'}" value="${escapeAttr(state.dashboardHistoryFrom)}" ${isCustom ? '' : 'disabled'}>
                <input id="${targetId}To" type="date" class="bg-black/30 text-white border border-white/10 rounded-xl px-4 py-2.5 text-sm focus:outline-none focus:border-[var(--dash-accent)] ${isCustom ? '' : 'opacity-60'}" value="${escapeAttr(state.dashboardHistoryTo)}" ${isCustom ? '' : 'disabled'}>
            </div>
        </div>
    `;

    toolbar.querySelectorAll('.dashboard-history-preset').forEach((button) => {
        button.addEventListener('click', async () => {
            const today = getTodayDateValue();
            state.dashboardHistoryPreset = button.dataset.historyPreset;
            if (state.dashboardHistoryPreset === 'today') {
                state.dashboardHistoryFrom = today;
                state.dashboardHistoryTo = today;
            } else if (state.dashboardHistoryPreset === 'week') {
                state.dashboardHistoryFrom = getStartOfWeek(today);
                state.dashboardHistoryTo = today;
            } else if (state.dashboardHistoryPreset === 'custom') {
                state.dashboardHistoryFrom = state.dashboardHistoryFrom || today;
                state.dashboardHistoryTo = state.dashboardHistoryTo || state.dashboardHistoryFrom;
            }
            await initBoard(true);
        });
    });

    const fromInput = toolbar.querySelector(`#${targetId}From`);
    const toInput = toolbar.querySelector(`#${targetId}To`);
    const onDateChange = async () => {
        state.dashboardHistoryPreset = 'custom';
        state.dashboardHistoryFrom = fromInput.value || state.dashboardHistoryFrom || getTodayDateValue();
        state.dashboardHistoryTo = toInput.value || state.dashboardHistoryTo || state.dashboardHistoryFrom;
        if (state.dashboardHistoryTo < state.dashboardHistoryFrom) state.dashboardHistoryTo = state.dashboardHistoryFrom;
        await initBoard(true);
    };
    fromInput?.addEventListener('change', onDateChange);
    toInput?.addEventListener('change', onDateChange);
}

function renderBoard() {
    const boardEl = document.getElementById('board');
    boardEl.innerHTML = '';

    const mainDivisions = getVisibleDivisions().filter(d => d.id !== 8);
    queueTranslationRefresh(mainDivisions.map((d) => d.vfp));

    mainDivisions.forEach(div => {
        const divisionCopy = getDivisionCopy(div);
        const totalTasks = div.items.reduce((sum, item) => sum + (item.current_todos?.length || 0), 0);
        const completedTasks = div.items.reduce((sum, item) => sum + ((item.current_todos || []).filter(todo => todo.done).length), 0);
        const completionPct = totalTasks === 0 ? 0 : Math.round((completedTasks / totalTasks) * 100);

        const divEl = document.createElement('div');
        divEl.className = 'glass-panel division-col p-6 m-2 shrink-0 border-t-[var(--border-var)] relative overflow-hidden group';
        divEl.style.setProperty('--border-var', div.border_var);
        divEl.style.setProperty('background', div.color_var);
        
        divEl.innerHTML = `
            <div class="division-head relative z-10">
                <div class="division-heading">
                    <p class="division-kicker">${escapeHtml(t('board.divisionKicker', { id: div.id }))}</p>
                    <h3 class="font-extrabold text-xl tracking-tight mb-1" style="color: var(--text-div-${div.id})">${escapeHtml(divisionCopy.name)}</h3>
                    <p class="text-xs text-gray-400 font-medium uppercase tracking-wider">${escapeHtml(divisionCopy.subtitle)}</p>
                </div>
                <div class="flex gap-2 opacity-80 group-hover:opacity-100 transition-opacity">
                    <button class="open-dashboard-btn division-tool text-gray-400 hover:text-white hover:bg-white/10 transition-all" data-id="${div.id}" title="${escapeAttr(t('board.openDashboardTitle'))}">
                        <i class="fas fa-expand-arrows-alt"></i>
                    </button>
                    <button class="info-btn division-tool text-gray-400 hover:text-white hover:bg-white/10 transition-all" data-id="${div.id}" title="${escapeAttr(t('board.divisionInfoTitle'))}">
                        <i class="fas fa-circle-info"></i>
                    </button>
                </div>
            </div>

            <div class="division-meta relative z-10">
                <span class="division-stat"><i class="fas fa-layer-group mr-1"></i>${div.items.length} ${escapeHtml(t('board.workflows'))}</span>
                <span class="division-stat"><i class="fas fa-check-double mr-1"></i>${completionPct}% ${escapeHtml(t('board.completed'))}</span>
            </div>

            <div class="relative z-10 mb-4">
                <label class="division-kicker mb-2 block">${escapeHtml(t('board.assignName'))}</label>
                <input type="text" value="${escapeAttr(t('board.comingSoon'))}" disabled class="w-full bg-black/20 border border-white/10 rounded-xl px-4 py-2.5 text-sm text-gray-500 cursor-not-allowed">
            </div>
            
            <div class="kanban-list flex-1 min-h-[50px] relative z-10" data-id="${div.id}" id="list-${div.id}"></div>

            <div class="mt-4 pt-4 border-t border-white/5 relative z-10 flex flex-col gap-3">
                <button class="add-item-btn w-full py-3 bg-black/40 hover:bg-black/60 rounded-xl border border-white/5 transition-all text-sm text-gray-200 flex items-center justify-center gap-2 shadow-inner">
                    <i class="fas fa-plus text-xs"></i> ${escapeHtml(t('board.createWorkflow'))}
                </button>
                <div class="vfp-container">
                    <input type="text" class="vfp-input" placeholder="${escapeAttr(t('board.vfpPlaceholder'))}" value="${escapeAttr(getDisplayVfp(div))}" data-id="${div.id}" data-input-id="vfp-${div.id}">
                </div>
            </div>
        `;

        const listEl = divEl.querySelector('.kanban-list');
        if (div.items.length === 0) {
            listEl.innerHTML = `<div class="empty-column-state">${t('board.emptyLane')}</div>`;
        } else {
            div.items.forEach(item => {
                listEl.appendChild(createItemElement(item, div));
            });
        }

        divEl.querySelector('.info-btn').addEventListener('click', () => openInfoModal(div.id));
        divEl.querySelector('.open-dashboard-btn').addEventListener('click', () => openDashboard(div.id));
        divEl.querySelector('.add-item-btn').addEventListener('click', () => addNewItem(div.id));
        
        const vfpInput = divEl.querySelector('.vfp-input');
        vfpInput.addEventListener('change', async (e) => {
            await api.updateVfp(div.id, e.target.value);
        });

        boardEl.appendChild(divEl);

        new Sortable(listEl, {
            group: 'kanban',
            animation: 250,
            ghostClass: 'sortable-ghost',
            dragClass: 'sortable-drag',
            easing: "cubic-bezier(1, 0, 0, 1)",
            onEnd: async (evt) => {
                const itemId = evt.item.dataset.id;
                const newDivId = evt.to.dataset.id;
                if (evt.from.dataset.id !== newDivId) {
                    await api.moveItem(itemId, newDivId, getDashboardDefaultWorkDate());
                    await refreshActiveAppState({ maintainFocus: true });
                }
            }
        });
    });

    initTooltips();
}

function renderDashboardKanban(divId) {
    const container = document.getElementById('dashboardKanbanContainer');
    container.innerHTML = '';
    
    const div = getDivisionById(divId);
    if (!div) return;
    const divisionCopy = getDivisionCopy(div);
    const incomingOrders = getTargetDivisionOrders(divId);

    const divEl = document.createElement('div');
    divEl.className = 'w-full flex flex-col bg-black/40 rounded-2xl border border-white/10 p-6 shadow-[0_10px_40px_-10px_rgba(0,0,0,0.5)] backdrop-blur-2xl transition-all duration-500 relative overflow-hidden';
    divEl.style.setProperty('--border-var', div.border_var);
    
    divEl.innerHTML = `
        <div class="absolute inset-0 bg-[radial-gradient(circle_at_top_right,_var(--border-var),_transparent_40%)] opacity-10 pointer-events-none"></div>
        <div class="mb-5 relative z-10" id="dashboardBoardToolbar"></div>
        <div class="flex items-center justify-between mb-6 relative z-10 border-b border-white/5 pb-4">
            <h3 class="text-xl font-bold text-white tracking-tight flex items-center gap-3">
                ${escapeHtml(t('dashboard.activePipeline'))}
                <button class="info-tooltip text-gray-500 hover:text-white transition" data-tooltip="${escapeAttr(t('tooltip.pipeline'))}"><i class="fas fa-info-circle text-[15px]"></i></button>
            </h3>
            <span class="px-3 py-1 bg-white/5 rounded-lg text-xs font-semibold text-gray-400 border border-white/10">${escapeHtml(t('dashboard.tasksCount', { count: div.items.length }))}</span>
        </div>
        ${incomingOrders.length ? `
            <div class="mb-6 relative z-10 rounded-2xl border border-amber-500/20 bg-amber-500/10 p-5">
                <div class="flex items-center justify-between gap-4 mb-4">
                    <div>
                        <p class="text-[11px] uppercase tracking-[0.22em] text-amber-300 mb-2">Incoming Executive Orders</p>
                        <p class="text-sm text-gray-300">ED directives currently assigned to this division.</p>
                    </div>
                    <span class="px-3 py-1 rounded-full bg-black/30 border border-white/10 text-xs text-white">${incomingOrders.length} active</span>
                </div>
                <div class="flex flex-col gap-3">
                    ${incomingOrders.slice(0, 4).map((order) => `
                        <div class="rounded-2xl border border-white/10 bg-black/20 p-4">
                            <div class="flex flex-col md:flex-row md:items-start justify-between gap-3">
                                <div>
                                    <p class="text-sm font-bold text-white">${escapeHtml(order.title)}</p>
                                    <p class="text-sm text-gray-400 mt-2">${escapeHtml(order.body || '')}</p>
                                    <div class="mt-3 flex flex-wrap gap-2 text-[10px] uppercase tracking-[0.18em]">
                                        <span class="px-2 py-1 rounded-full bg-white/[0.05] border border-white/10 text-gray-300">${escapeHtml(order.priority)}</span>
                                        <span class="px-2 py-1 rounded-full bg-white/[0.05] border border-white/10 text-gray-300">${escapeHtml(order.status.replace('_', ' '))}</span>
                                        ${order.due_date ? `<span class="px-2 py-1 rounded-full bg-white/[0.05] border border-white/10 text-gray-300">Due ${escapeHtml(order.due_date)}</span>` : ''}
                                    </div>
                                </div>
                                <div class="flex gap-2 shrink-0">
                                    ${order.status !== 'in_progress' ? `<button class="px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs text-white order-status-btn" data-order-id="${order.id}" data-status="in_progress">Start</button>` : ''}
                                    ${order.status !== 'done' ? `<button class="px-3 py-2 rounded-xl bg-emerald-500/15 hover:bg-emerald-500/25 border border-emerald-400/20 text-xs text-emerald-100 order-status-btn" data-order-id="${order.id}" data-status="done">Complete</button>` : ''}
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        ` : ''}
        <div class="mb-6 relative z-10 rounded-2xl border border-white/10 bg-white/[0.03] p-5 shadow-inner">
            <p class="text-[11px] uppercase tracking-[0.22em] text-gray-500 mb-2">Division VFP</p>
            <p class="text-sm md:text-[15px] leading-relaxed text-white font-medium">${escapeHtml(getLiveVfp(div) || 'No VFP set yet for this division.')}</p>
        </div>
        <div class="kanban-list flex-1 min-h-[300px] relative z-10" data-id="${div.id}" id="dash-list-${div.id}"></div>
        <div class="mt-4 pt-6 relative z-10">
            <button class="dash-add-item-btn w-full py-4 bg-white/5 hover:bg-white/10 rounded-xl border border-white/10 transition-all text-sm font-semibold text-gray-200 flex items-center justify-center gap-3" style="color: var(--dash-accent)">
                <i class="fas fa-plus"></i> ${escapeHtml(t('dashboard.initializeWorkflow'))}
            </button>
        </div>
    `;

    const listEl = divEl.querySelector('.kanban-list');
    div.items.forEach(item => {
        listEl.appendChild(createItemElement(item, div, true));
    });

    divEl.querySelector('.dash-add-item-btn').addEventListener('click', () => addNewItem(div.id));
    divEl.querySelectorAll('.order-status-btn').forEach((btn) => {
        btn.addEventListener('click', async () => {
            await api.updateExecutiveOrder(btn.dataset.orderId, { status: btn.dataset.status });
            const ordersData = await api.getExecutiveOrders();
            state.executiveOrders = ordersData.orders || [];
            renderDashboardKanban(divId);
            if (isWorkDivision(state.activeDashboardDivId)) {
                if (state.activeDashboardDivId === 1) await refreshDiv1WorkData();
                if (state.activeDashboardDivId === 2) await refreshDiv2WorkData();
                if (state.activeDashboardDivId === 3) await refreshDiv3WorkData();
                if (state.activeDashboardDivId === 4) await refreshDiv4WorkData();
                if (state.activeDashboardDivId === 5) await refreshDiv5WorkData();
                if (state.activeDashboardDivId === 6) await refreshDiv6WorkData();
                if (state.activeDashboardDivId === 8) await refreshEdWorkData();
                if (state.activeDashboardDivId === 7) await refreshDiv7WorkData();
                renderDivisionWork();
            }
        });
    });
    container.appendChild(divEl);
    renderDashboardDateToolbar('dashboardBoardToolbar');
    initTooltips();

    new Sortable(listEl, {
        group: 'dashboard-kanban',
        animation: 250,
        ghostClass: 'sortable-ghost',
        dragClass: 'sortable-drag'
    });
}

function createItemElement(item, div, isDashboard = false) {
    const el = document.createElement('div');
    el.className = 'kanban-card group';
    el.style.setProperty('--card-accent', div.border_var);
    el.dataset.id = item.id;

    // Use current_todos for active tracking
    const completedTodos = item.current_todos.filter(t => t.done).length;
    const totalTodos = item.current_todos.length;
    const progressText = totalTodos > 0 ? `${completedTodos}/${totalTodos}` : '0/0';
    const isExpanded = state.expandedItemIds.has(item.id);
    const sortedTodos = [...item.current_todos].sort((a, b) => Number(a.done) - Number(b.done) || a.id - b.id);

    // Group history tasks by division for display
    let historyHtml = '';
    if (item.history_todos && item.history_todos.length > 0) {
        historyHtml = `
            <div class="mt-4 pt-3 border-t border-white/5">
                <button class="text-xs text-gray-500 hover:text-white transition flex items-center gap-1 w-full justify-between" onclick="this.nextElementSibling.classList.toggle('hidden')">
                    <span class="flex items-center gap-2"><i class="fas fa-history text-[10px]"></i> Client History Log</span>
                    <i class="fas fa-chevron-down text-[10px]"></i>
                </button>
                <div class="hidden mt-2 flex flex-col gap-1 max-h-32 overflow-y-auto custom-scrollbar pr-2">
                    ${item.history_todos.map(ht => `
                    <div class="text-[10px] text-gray-500 bg-black/30 rounded p-1.5 flex items-center gap-2 ${ht.done ? 'line-through opacity-70' : ''}">
                            <i class="fas ${ht.done ? 'fa-check text-green-500/50' : 'fa-times text-red-500/50'}"></i> ${escapeHtml(ht.text)}
                        </div>
                    `).join('')}
                </div>
            </div>
        `;
    }

    el.innerHTML = `
        <div class="card-topline">
            <div class="card-tag"><i class="fas fa-sparkles"></i> ${escapeHtml(t('card.workflowCard'))}</div>
            <div class="card-progress">${progressText}</div>
        </div>
        <div class="flex justify-between items-start mb-2">
            <h4 class="font-semibold text-white text-[15px] pr-8 leading-tight">${escapeHtml(item.title)}</h4>
            <button class="edit-item-btn absolute top-3 right-3 text-gray-400 hover:text-white" data-id="${item.id}">
                <i class="fas fa-ellipsis-h text-sm"></i>
            </button>
        </div>
        <div class="text-[10px] uppercase tracking-[0.18em] text-gray-500 mb-2">Work Date · ${escapeHtml(item.work_date || 'Not set')}</div>
        
        <div class="text-xs text-gray-500 mt-1">${escapeHtml(t('card.activeTasks', { count: totalTodos }))}</div>
        
        <div class="card-actions" data-id="${item.id}">
            <button class="card-action-primary toggle-todos" type="button">
                <i class="fas fa-list-check"></i>
                <span>${escapeHtml(isExpanded ? t('card.hideTasks') : t('card.openTasks'))}</span>
                <i class="fas fa-chevron-down transition-transform duration-300 ml-1" style="transform: ${isExpanded ? 'rotate(180deg)' : 'rotate(0deg)'}"></i>
            </button>
            <button class="card-action-secondary ai-plan-btn" type="button" data-id="${item.id}" title="${escapeAttr(t('guided.generate'))}">
                <i class="fas fa-wand-magic-sparkles"></i>
                <span>${escapeHtml(t('card.aiTasks'))}</span>
            </button>
        </div>

        <div class="todo-list-container flex flex-col gap-2 ${isExpanded ? 'expanded mt-3' : ''}" id="${isDashboard ? 'dash-' : ''}todos-${item.id}"></div>
        
        ${historyHtml}
    `;

    const todosContainer = el.querySelector('.todo-list-container');
    sortedTodos.forEach(todo => {
        const todoEl = document.createElement('div');
        todoEl.className = `todo-item bg-white/5 rounded-lg p-2 px-3 border border-white/5 hover:border-white/10 ${todo.done ? 'done' : ''}`;
        todoEl.innerHTML = `
            <input type="checkbox" class="todo-checkbox shrink-0" ${todo.done ? 'checked' : ''} data-id="${todo.id}">
            <div class="flex-1 min-w-0 ml-2">
                <span class="block break-words">${escapeHtml(todo.text)}</span>
                <input type="date" class="todo-date-input mt-2 w-full bg-black/40 border border-white/10 rounded-lg px-2 py-1 text-[11px] text-gray-300 focus:outline-none focus:border-[var(--dash-accent)]" value="${escapeAttr(todo.work_date || '')}" data-id="${todo.id}">
            </div>
            <button class="text-red-400/30 hover:text-red-400 text-xs ml-2 delete-todo-btn p-1 transition-colors self-start" data-id="${todo.id}"><i class="fas fa-times"></i></button>
        `;
        todoEl.querySelector('.todo-checkbox').addEventListener('change', async (e) => {
            await api.toggleTodo(todo.id, e.target.checked);
            await refreshActiveAppState({ maintainFocus: true });
        });
        todoEl.querySelector('.todo-date-input').addEventListener('change', async (e) => {
            await api.updateTodoMeta(todo.id, { work_date: e.target.value });
            await refreshActiveAppState({ maintainFocus: true });
        });
        todoEl.querySelector('.delete-todo-btn').addEventListener('click', async (e) => {
            e.stopPropagation();
            await api.deleteTodo(todo.id);
            await refreshActiveAppState({ maintainFocus: true });
        });
        todosContainer.appendChild(todoEl);
    });

    const addTodoEl = document.createElement('div');
    addTodoEl.className = 'mt-1 flex items-center relative';
    const inputId = `add-todo-${isDashboard ? 'dash-' : ''}${item.id}`;
    addTodoEl.innerHTML = `
        <div class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500 text-xs"><i class="fas fa-plus"></i></div>
        <input type="text" class="w-full bg-black/40 border border-white/10 rounded-lg py-2 pl-8 pr-3 text-xs text-white focus:outline-none focus:border-white/30 transition-colors add-todo-input" placeholder="${escapeAttr(t('card.newTaskPlaceholder'))}" data-item-id="${item.id}" data-input-id="${inputId}">
    `;
    addTodoEl.querySelector('input').addEventListener('keypress', async (e) => {
        if (e.key === 'Enter' && e.target.value.trim()) {
            state.expandedItemIds.add(item.id);
            await api.addTodo(item.id, e.target.value.trim(), getDashboardDefaultWorkDate());
            await refreshActiveAppState({ maintainFocus: true });
        }
    });

    todosContainer.appendChild(addTodoEl);

    // AI Auto-Plan click handler — opens Guided Brief modal
    const aiBtn = el.querySelector('.ai-plan-btn');
    if (aiBtn) {
        aiBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            state.expandedItemIds.add(item.id);
            openGuidedTaskModal(item.id, div.id, item.title);
        });
    }

    el.querySelector('.toggle-todos').addEventListener('click', (e) => {
        e.stopPropagation();
        const icon = el.querySelector('.fa-chevron-down');
        const container = el.querySelector('.todo-list-container');
        if (container.classList.contains('expanded')) {
            container.classList.remove('expanded', 'mt-3');
            icon.style.transform = 'rotate(0deg)';
            state.expandedItemIds.delete(item.id);
        } else {
            container.classList.add('expanded', 'mt-3');
            icon.style.transform = 'rotate(180deg)';
            state.expandedItemIds.add(item.id);
        }
    });

    el.querySelector('.edit-item-btn').addEventListener('click', (e) => {
        e.stopPropagation();
        openEditItemModal(item);
    });

    return el;
}

function addNewItem(divId) {
    state.activeAddDivisionId = divId;
    const input = document.getElementById('addItemTitleInput');
    const dateInput = document.getElementById('addItemDateInput');
    input.value = '';
    if (dateInput) dateInput.value = getDashboardDefaultWorkDate();
    
    const div = state.divisions.find(d => d.id === divId);
    const btn = document.getElementById('confirmAddItemBtn');
    if (state.activeDashboardDivId === divId && div) {
        btn.style.background = div.color_var;
        btn.style.borderColor = div.border_var;
    } else {
        btn.style.background = '';
        btn.style.borderColor = '';
    }

    const modal = document.getElementById('addItemModal');
    modal.classList.remove('hidden');
    setTimeout(() => { 
        modal.classList.remove('opacity-0'); 
        modal.querySelector('.glass-panel').classList.remove('scale-95'); 
        input.focus(); 
    }, 10);
}

function closeAddItemModal() {
    const modal = document.getElementById('addItemModal');
    modal.classList.add('opacity-0');
    modal.querySelector('.glass-panel').classList.add('scale-95');
    setTimeout(() => { modal.classList.add('hidden'); state.activeAddDivisionId = null; }, 300);
}

// Dashboards (Mac App Sidebar Navigation)
function initDashboard() {
    const dirBtn = document.getElementById('openDirDashboard');
    if (dirBtn) dirBtn.addEventListener('click', () => openDashboard(8));
    
    const dirInfo = document.getElementById('openDirInfo');
    if (dirInfo) dirInfo.addEventListener('click', () => openInfoModal(8));

    document.getElementById('closeDashboard').addEventListener('click', closeDashboard);

    const navBtns = document.querySelectorAll('.dash-nav-btn');
    const views = document.querySelectorAll('.dash-view');

    navBtns.forEach(btn => {
        btn.addEventListener('click', async () => {
            if(btn.id === 'closeDashboard') return;
            
            navBtns.forEach(b => {
                b.classList.remove('active', 'bg-white/10', 'text-white');
                b.classList.add('text-gray-400');
                b.style.boxShadow = 'none';
                b.style.background = 'transparent';
            });
            
            btn.classList.add('active', 'text-white');
            btn.classList.remove('text-gray-400');
            
            const div = state.divisions.find(d => d.id === state.activeDashboardDivId);
            if(div) {
                btn.style.boxShadow = `inset 3px 0 0 0 ${div.border_var}`;
                btn.style.background = `linear-gradient(90deg, ${div.color_var} 0%, transparent 100%)`;
            }

            const targetViewId = btn.dataset.view;
            state.activeDashboardView = targetViewId;
            views.forEach(v => {
                if (v.id === targetViewId) v.classList.remove('hidden');
                else v.classList.add('hidden');
            });

            // Re-render specific view content based on tab
            if(targetViewId === 'dashboardMetricsView') renderMetrics(state.activeDashboardDivId);
            if(targetViewId === 'dashboardTrainingView') renderTraining(state.activeDashboardDivId);
            if(targetViewId === 'dashboardBattlePlanView') renderBattlePlan(state.activeDashboardDivId);
            if(targetViewId === 'dashboardWorkView') renderDivisionWork();
            if(targetViewId === 'dashboardBoardView') renderDashboardKanban(state.activeDashboardDivId);
            if(targetViewId === 'dashboardSkillsView') renderSkills(state.activeDashboardDivId);
            if(targetViewId === 'dashboardAIView') await loadAIConversations(state.activeDashboardDivId, state.activeConversationId);
            if(targetViewId === 'dashboardAgentsView') {
                await refreshAgentsData();
                renderAgentsView();
                renderMemoryExplorer();
            }
        });
    });

    // Chart period toggles
    document.querySelectorAll('.chart-period-btn').forEach(b => {
        b.addEventListener('click', (e) => {
            document.querySelectorAll('.chart-period-btn').forEach(x => {
                x.classList.remove('active', 'bg-white/10', 'text-white');
                x.classList.add('text-gray-400');
            });
            e.target.classList.add('active', 'bg-white/10', 'text-white');
            e.target.classList.remove('text-gray-400');
            state.activeChartPeriod = e.target.dataset.period;
            renderChart(state.activeChartPeriod);
        });
    });

    const mockToggle = document.getElementById('mockDataToggle');
    if (mockToggle) {
        mockToggle.addEventListener('change', (e) => {
            state.showMockData = e.target.checked;
            saveSettingsPatch({ show_mock_data: state.showMockData ? 1 : 0 }).catch(() => {});
            renderChart(state.activeChartPeriod);
        });
    }

    // Skills buttons
    document.getElementById('addSkillBtn').addEventListener('click', () => {
        const divId = state.activeDashboardDivId;
        customPrompt(t('skills.newCoreSkill'), t('skills.newCoreSkillPrompt'), async (name) => {
            customPrompt(`${t('skills.skillPrefix')}: ${name}`, t('skills.skillContentPrompt'), async (content) => {
                await api.addSkill({
                    division_id: divId,
                    parent_id: null,
                    name: name,
                    content: content,
                    icon: 'fa-lightbulb',
                    color: '#34d399',
                    tags: ''
                });
                showToast(t('skills.addedToast', { name }), 'success');
                renderSkills(divId);
            });
        });
    });

    document.getElementById('backfillSkillsBtn').addEventListener('click', async () => {
        const btn = document.getElementById('backfillSkillsBtn');
        btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${escapeHtml(t('skills.embedding'))}`;
        btn.disabled = true;
        try {
            const res = await api.backfillSkills();
            showToast(res.message || t('skills.embeddedToast', { done: res.done, total: res.total }), 'success');
            renderSkills(state.activeDashboardDivId);
        } catch(e) {
            showToast(t('skills.embeddingFailed'), 'error');
        }
        btn.innerHTML = `<i class="fas fa-sync"></i> ${escapeHtml(t('skills.embedAll'))}`;
        btn.disabled = false;
    });

    // Memory: search button + enter key
    document.getElementById('memorySearchBtn').addEventListener('click', () => searchMemoryUI());
    document.getElementById('memorySearchInput').addEventListener('keypress', (e) => { if(e.key === 'Enter') searchMemoryUI(); });

}

async function openDashboard(divId) {
    const div = state.divisions.find(d => d.id === divId);
    if (!div) return;
    const divisionCopy = getDivisionCopy(div);
    state.activeDashboardDivId = divId;
    state.activeDiv1WorkTab = 'lines';
    state.activeDiv2WorkTab = 'pipeline';
    state.activeDiv3WorkTab = 'cashflow';
    state.activeDiv4WorkTab = 'production';
    state.activeDiv5WorkTab = 'queue';
    state.activeDiv6WorkTab = 'success';
    state.activeEdWorkTab = 'command';
    state.activeDiv7WorkTab = 'policies';
    state.div3EditingInvoiceId = null;
    state.div3InvoiceDraftLines = [{ description: '', amount: '' }];

    document.getElementById('dashboardTitle').textContent = divisionCopy.name;
    document.getElementById('dashIcon').style.color = div.border_var;

    const modal = document.getElementById('dashboardModal');
    modal.style.setProperty('--dash-accent', div.border_var);
    modal.style.setProperty('--dash-accent-faded', div.color_var);

    const workNavBtn = document.getElementById('dashboardWorkNavBtn');
    const battlePlanNavBtn = document.getElementById('dashboardBattlePlanNavBtn');
    if (isWorkDivision(divId)) {
        workNavBtn?.classList.remove('hidden');
        workNavBtn?.classList.add('flex');
        battlePlanNavBtn?.classList.add('hidden');
        battlePlanNavBtn?.classList.remove('flex');
    } else {
        workNavBtn?.classList.add('hidden');
        workNavBtn?.classList.remove('flex');
        battlePlanNavBtn?.classList.remove('hidden');
        battlePlanNavBtn?.classList.add('flex');
    }

    renderDashboardKanban(divId);

    // Pre-fetch all data for fast switching
    state.metricsData = await api.getMetrics(divId);
    state.battlePlansData = await api.getBattlePlans(divId);
    state.trainingsData = await api.getTrainings(divId);
    if (divId === 8) {
        await refreshEdWorkData();
    } else if (divId === 6) {
        await refreshDiv6WorkData();
    } else if (divId === 5) {
        await refreshDiv5WorkData();
    } else if (divId === 4) {
        await refreshDiv4WorkData();
    } else if (divId === 3) {
        await refreshDiv3WorkData();
    } else if (divId === 2) {
        await refreshDiv2WorkData();
    } else if (divId === 1) {
        await refreshDiv1WorkData();
    } else if (divId === 7) {
        await refreshDiv7WorkData();
    } else {
        state.div1WorkData = null;
        state.div2WorkData = null;
        state.div3WorkData = null;
        state.div4WorkData = null;
        state.div5WorkData = null;
        state.div6WorkData = null;
        state.edWorkData = null;
        state.div7WorkData = null;
    }

    if (window.matchMedia('(max-width: 980px)').matches) {
        document.body.classList.add('dock-collapsed');
        document.getElementById('topDockToggle')?.setAttribute('aria-expanded', 'false');
    }

    if (isWorkDivision(divId)) {
        state.activeDashboardView = 'dashboardWorkView';
        workNavBtn?.click();
    } else {
        state.activeDashboardView = 'dashboardBoardView';
        document.querySelector('.dash-nav-btn[data-view="dashboardBoardView"]')?.click();
    }

    modal.classList.remove('hidden');
    setTimeout(() => { modal.classList.remove('opacity-0', 'scale-95'); }, 10);
    await loadAIConversations(divId);
}

function closeDashboard() {
    const modal = document.getElementById('dashboardModal');
    modal.classList.add('opacity-0', 'scale-95');
    setTimeout(() => {
        modal.classList.add('hidden');
        state.activeDashboardDivId = null;
        state.activeConversationId = null;
        state.aiConversations = [];
        state.chatHistory = [];
        state.activeDashboardView = 'dashboardBoardView';
        state.div1WorkData = null;
        state.div2WorkData = null;
        state.div3WorkData = null;
        state.div4WorkData = null;
        state.div5WorkData = null;
        state.div6WorkData = null;
        state.edWorkData = null;
        state.div7WorkData = null;
        state.div3EditingInvoiceId = null;
        state.div3InvoiceDraftLines = [{ description: '', amount: '' }];
    }, 300);
}
