function formatAgentRunTime(value) {
    if (!value) return 'Manual';
    return value;
}

function formatAgentRunStamp(value) {
    if (!value) return 'Never';
    try {
        return new Date(value).toLocaleString('en-GB');
    } catch (_error) {
        return value;
    }
}

function getAgentLogEntryHtml(run) {
    const actions = (() => {
        try {
            return JSON.parse(run.actions_json || '[]');
        } catch (_error) {
            return [];
        }
    })();
    return `
        <div class="bg-white/5 border border-white/5 rounded-xl p-4">
            <div class="flex flex-wrap items-center gap-2 mb-2">
                <span class="text-white font-semibold">${escapeHtml(run.agent_name)}</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(run.trigger_mode)}</span>
                <span class="px-2 py-1 rounded-full bg-black/30 border border-white/10 text-[10px] uppercase tracking-[0.18em] ${run.status === 'success' ? 'text-emerald-300' : 'text-red-300'}">${escapeHtml(run.status)}</span>
                <span class="text-[11px] text-gray-500 ml-auto">${escapeHtml(formatAgentRunStamp(run.created_at))}</span>
            </div>
            <p class="text-sm text-gray-200">${escapeHtml(run.summary || 'No summary recorded.')}</p>
            ${actions.length ? `<div class="mt-3 flex flex-col gap-2">${actions.slice(0, 6).map((action) => `<div class="text-xs text-gray-400">• ${escapeHtml((action.type || 'action').replace(/_/g, ' '))}${action.text ? `: ${escapeHtml(action.text)}` : action.title ? `: ${escapeHtml(action.title)}` : action.metric_key ? `: ${escapeHtml(action.metric_key)} = ${escapeHtml(String(action.value))}` : ''}</div>`).join('')}</div>` : ''}
        </div>
    `;
}

async function refreshAgentsData() {
    if (!state.activeDashboardDivId) return;
    const [agentsData, runsData] = await Promise.all([
        api.getAgents(state.activeDashboardDivId),
        api.getAgentRuns(state.activeDashboardDivId)
    ]);
    state.agentsData = agentsData.agents || [];
    state.agentRuns = runsData.runs || [];
}

function renderAgentCard(agent) {
    const isBuiltIn = Boolean(agent.system_key);
    const canDelete = !isBuiltIn;
    const pauseLabel = agent.status === 'active' ? 'Pause' : 'Resume';
    const pauseNext = agent.status === 'active' ? 'paused' : 'active';
    return `
        <div class="rounded-2xl border border-white/10 bg-black/20 p-4">
            <div class="flex items-start justify-between gap-3 mb-3">
                <div class="flex items-start gap-3">
                    <div class="w-11 h-11 rounded-2xl flex items-center justify-center shrink-0 border border-white/10" style="background:${escapeAttr(agent.accent_color || '#8b5cf6')}22;color:${escapeAttr(agent.accent_color || '#8b5cf6')}">
                        <i class="fas ${escapeAttr(agent.icon || 'fa-robot')}"></i>
                    </div>
                    <div>
                        <div class="flex flex-wrap items-center gap-2">
                            <p class="text-white font-semibold">${escapeHtml(agent.name)}</p>
                            ${isBuiltIn ? '<span class="px-2 py-1 rounded-full bg-amber-500/15 border border-amber-400/20 text-[10px] uppercase tracking-[0.18em] text-amber-200">built-in</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(agent.run_mode === 'scheduled' ? `scheduled ${formatAgentRunTime(agent.run_time)}` : 'manual')}</span>
                        </div>
                        <p class="text-xs text-gray-400 mt-1">${escapeHtml(agent.description || '')}</p>
                    </div>
                </div>
                <div class="text-[11px] text-gray-500 text-right">
                    <div>Runs: ${escapeHtml(String(agent.run_count || 0))}</div>
                    <div>Last: ${escapeHtml(agent.last_run_at ? formatAgentRunStamp(agent.last_run_at) : 'Never')}</div>
                </div>
            </div>
            <p class="text-sm text-gray-300 leading-relaxed">${escapeHtml(agent.instructions || '')}</p>
            <div class="mt-4 flex flex-wrap gap-2">
                <button class="agent-run-btn px-3 py-2 rounded-xl bg-[var(--dash-accent)]/15 hover:bg-[var(--dash-accent)]/25 border border-[var(--dash-accent)]/20 text-xs font-semibold text-white" data-agent-run="${agent.id}">Run</button>
                <button class="agent-status-btn px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-semibold text-gray-200" data-agent-status="${agent.id}" data-next-status="${pauseNext}">${pauseLabel}</button>
                ${canDelete ? `<button class="agent-delete-btn px-3 py-2 rounded-xl bg-red-500/10 hover:bg-red-500/20 border border-red-400/20 text-xs font-semibold text-red-100" data-agent-delete="${agent.id}">Delete</button>` : ''}
            </div>
        </div>
    `;
}

function renderAgentsView() {
    const generalContainer = document.getElementById('generalAgentsContainer');
    const divisionContainer = document.getElementById('divisionAgentsContainer');
    const runsContainer = document.getElementById('agentLogContainer');
    const agents = state.agentsData || [];
    const generalAgents = agents.filter((agent) => agent.scope_type === 'general');
    const divisionAgents = agents.filter((agent) => agent.scope_type === 'division');
    const isEd = Number(state.activeDashboardDivId) === 8;

    document.getElementById('generalAgentsCount').textContent = String(generalAgents.length);
    document.getElementById('divisionAgentsCount').textContent = String(divisionAgents.length);

    generalContainer.innerHTML = generalAgents.length
        ? generalAgents.map(renderAgentCard).join('')
        : `<div class="text-sm text-gray-500">No general agents available yet.</div>`;

    divisionContainer.innerHTML = divisionAgents.length
        ? divisionAgents.map(renderAgentCard).join('')
        : `<div class="text-sm text-gray-500">No division-specific agents yet. Create one from the brief box above.</div>`;

    runsContainer.innerHTML = state.agentRuns.length
        ? state.agentRuns.map(getAgentLogEntryHtml).join('')
        : `<div class="text-gray-500 text-xs italic">No agent runs recorded yet for this division.</div>`;

    const scopeSelect = document.getElementById('agentScopeSelect');
    const scopeHint = document.getElementById('agentScopeHint');
    if (scopeSelect) {
        scopeSelect.value = isEd ? scopeSelect.value : 'division';
        const generalOption = [...scopeSelect.options].find((option) => option.value === 'general');
        if (generalOption) generalOption.hidden = !isEd;
        if (!isEd) scopeSelect.value = 'division';
    }
    if (scopeHint) {
        scopeHint.textContent = isEd
            ? 'ED can create both general and division agents. Other hats can only create division agents.'
            : 'This hat can create division agents only. General agents are reserved for ED.';
    }

    document.querySelectorAll('[data-agent-run]').forEach((button) => {
        button.addEventListener('click', async () => {
            button.disabled = true;
            button.textContent = 'Running...';
            try {
                const result = await api.runAgent(button.dataset.agentRun, state.activeDashboardDivId);
                showToast(result.summary || 'Agent run completed.', 'success');
                await refreshAgentsAfterMutation();
            } catch (error) {
                showToast(error.message || 'Agent run failed.', 'error');
            } finally {
                button.disabled = false;
                button.textContent = 'Run';
            }
        });
    });

    document.querySelectorAll('[data-agent-status]').forEach((button) => {
        button.addEventListener('click', async () => {
            try {
                await api.updateAgent(button.dataset.agentStatus, {
                    requested_by_division_id: state.activeDashboardDivId,
                    status: button.dataset.nextStatus
                });
                await refreshAgentsData();
                renderAgentsView();
            } catch (error) {
                showToast(error.message || 'Agent update failed.', 'error');
            }
        });
    });

    document.querySelectorAll('[data-agent-delete]').forEach((button) => {
        button.addEventListener('click', () => {
            customConfirm('Delete this agent?', async () => {
                try {
                    await api.deleteAgent(button.dataset.agentDelete, state.activeDashboardDivId);
                    await refreshAgentsAfterMutation();
                    showToast('Agent deleted.', 'success');
                } catch (error) {
                    showToast(error.message || 'Agent delete failed.', 'error');
                }
            });
        });
    });
}

async function refreshAgentsAfterMutation() {
    await refreshActiveAppState({ maintainFocus: true, includeAgents: true });
    if (state.activeDashboardDivId) {
        const preferredConversationId = state.activeConversationId;
        await loadAIConversations(state.activeDashboardDivId, preferredConversationId);
    }
    renderAgentsView();
}

function initAgentsView() {
    const runModeSelect = document.getElementById('agentRunModeSelect');
    const runTimeInput = document.getElementById('agentRunTimeInput');
    const createBtn = document.getElementById('createAgentBtn');
    const runAllBtn = document.getElementById('awakenAgentsBtn');

    runModeSelect?.addEventListener('change', () => {
        const scheduled = runModeSelect.value === 'scheduled';
        runTimeInput.disabled = !scheduled;
        runTimeInput.classList.toggle('opacity-60', !scheduled);
        if (!scheduled) runTimeInput.value = '';
    });

    createBtn?.addEventListener('click', async () => {
        const brief = document.getElementById('agentBriefInput').value.trim();
        const scopeType = document.getElementById('agentScopeSelect').value;
        const runMode = document.getElementById('agentRunModeSelect').value;
        const runTime = document.getElementById('agentRunTimeInput').value;
        if (!brief) {
            showToast('Describe what the agent should do first.', 'error');
            return;
        }
        createBtn.disabled = true;
        createBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Creating Agent';
        try {
            const data = await api.generateAgent({
                requestedByDivisionId: state.activeDashboardDivId,
                requested_by_division_id: state.activeDashboardDivId,
                divisionId: state.activeDashboardDivId,
                division_id: state.activeDashboardDivId,
                scopeType,
                scope_type: scopeType,
                brief,
                runMode,
                run_mode: runMode,
                runTime,
                run_time: runTime
            });
            document.getElementById('agentBriefInput').value = '';
            await refreshAgentsAfterMutation();
            showToast(`${data.agent?.name || 'Agent'} created.`, 'success');
        } catch (error) {
            showToast(error.message || 'Agent creation failed.', 'error');
        } finally {
            createBtn.disabled = false;
            createBtn.innerHTML = '<i class="fas fa-magic"></i> Create Agent';
        }
    });

    runAllBtn?.addEventListener('click', async () => {
        runAllBtn.disabled = true;
        runAllBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Running Visible Agents';
        try {
            const data = await api.runAgents(state.activeDashboardDivId);
            await refreshAgentsAfterMutation();
            showToast(`Visible agent run complete: ${(data.results || []).length} agent(s).`, 'success');
        } catch (error) {
            showToast(error.message || 'Agent run failed.', 'error');
        } finally {
            runAllBtn.disabled = false;
            runAllBtn.innerHTML = '<i class="fas fa-power-off"></i> Run Visible Agents';
        }
    });
}
