import React, { useState, useEffect } from 'react';
import { getAgents, getAgentTelemetry, updateAgentStatus, deployAgent, deleteAgent, getUserConfig, getUserAccessibleNodes, getAgentTriggers } from '../../../services/apiService';
import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer } from 'recharts';
import BuddyAvatar from './BuddyAvatar';
import { useWebMcp } from '../../../shared/components/WebMcpProvider';

// Polling interval in ms
const POLLING_INTERVAL = 5000;

const formatTimeLocal = (utcString) => {
    if (!utcString) return 'Never';
    const dateStr = utcString.endsWith('Z') || utcString.includes('+') ? utcString : utcString + 'Z';
    return new Date(dateStr).toLocaleString(undefined, { 
        month: 'short', day: 'numeric', 
        hour: '2-digit', minute: '2-digit', second: '2-digit' 
    });
};

export default function AgentHarnessPage({ onNavigate }) {
    const { registerTool, unregisterTool } = useWebMcp();
    const [agents, setAgents] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showDeploy, setShowDeploy] = useState(false);

    useEffect(() => {
        registerTool({
            name: 'list_agents',
            description: 'List all autonomous agents currently configured in the system.',
            inputSchema: { type: 'object', properties: {} },
            execute: async () => {
                const result = {
                    agents: agents.map(a => ({
                        id: a.id,
                        name: a.template?.name,
                        status: a.status,
                        node: a.mesh_node_id,
                        last_heartbeat: a.last_heartbeat
                    }))
                };
                return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
            }
        });

        return () => {
            unregisterTool('list_agents');
        };
    }, [agents, registerTool, unregisterTool]);

    const fetchAgents = async () => {
        try {
            const data = await getAgents();
            setAgents(data);
            setError(null);
        } catch (err) {
            setError(err.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchAgents();
        const interval = setInterval(fetchAgents, POLLING_INTERVAL);
        return () => clearInterval(interval);
    }, []);

    return (
        <div className="flex-1 h-full overflow-y-auto bg-gray-100 dark:bg-gray-900 text-gray-900 dark:text-gray-100 p-8">
            <div className="max-w-7xl mx-auto space-y-8">
                {/* Header Section */}
                <div className="flex justify-between items-end mb-8 relative">
                    <div className="absolute top-0 right-0 w-96 h-96 bg-blue-600/20 blur-[130px] rounded-full pointer-events-none -z-10" />
                    <div>
                        <h1 className="text-4xl font-extrabold bg-clip-text text-transparent bg-gradient-to-r from-blue-500 via-indigo-500 to-purple-500 mb-2">
                            Agent Dashboard
                        </h1>
                        <p className="text-gray-500 dark:text-gray-400 text-sm tracking-wide uppercase">Cortex System Orchestrator</p>
                    </div>
                    {/* Deploy New Agent Button */}
                    <button
                        onClick={() => setShowDeploy(true)}
                        className="px-5 py-2.5 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white font-semibold text-sm tracking-wide transition-all shadow-lg shadow-blue-900/30 hover:shadow-blue-600/40 flex items-center gap-2"
                    >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" /></svg>
                        Deploy New Agent
                    </button>
                </div>

                {error && (
                    <div className="bg-red-900/40 border border-red-500/50 text-red-200 px-6 py-4 rounded-xl flex items-center justify-between">
                        <span>{error}</span>
                        <button onClick={() => setError(null)} className="text-red-400 hover:text-red-200 cursor-pointer text-xl font-bold">&times;</button>
                    </div>
                )}

                {loading && agents.length === 0 ? (
                    <div className="flex items-center justify-center p-20 animate-pulse">
                        <div className="flex items-center space-x-3 text-blue-500 font-medium">
                            <div className="w-5 h-5 rounded-full border-t-2 border-l-2 border-blue-500 animate-spin" />
                            <span>Loading Agents...</span>
                        </div>
                    </div>
                ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 relative z-10">
                        {agents.map(agent => (
                            <AgentCard key={agent.id} agent={agent} onNavigate={onNavigate} onStatusChange={fetchAgents} />
                        ))}
                        {agents.length === 0 && (
                            <div className="col-span-full py-20 text-center text-gray-500 border border-dashed border-gray-300 dark:border-gray-700 rounded-2xl bg-white/50 dark:bg-gray-800/30">
                                No active agents found in the system.
                            </div>
                        )}
                    </div>
                )}

                {/* Deploy New Agent Modal */}
                {showDeploy && (
                    <DeployAgentModal
                        onClose={() => setShowDeploy(false)}
                        onDeployed={() => {
                            setShowDeploy(false);
                            fetchAgents();
                        }}
                    />
                )}
            </div>
        </div>
    );
}

// ─────────────────────────────────────────────────────────────
// Deploy Agent Modal
// ─────────────────────────────────────────────────────────────
const DeployAgentModal = ({ onClose, onDeployed }) => {
    const [form, setForm] = useState({
        name: '',
        description: '',
        system_prompt: '',
        mesh_node_id: '',
        max_loop_iterations: 20,
        initial_prompt: '',
        provider_name: '', // Dynamic LLM selection
        trigger_type: 'manual',
        cron_expression: '',
        interval_seconds: 0,
        default_prompt: '',
        co_worker_quality_gate: false,
        rework_threshold: 80,
        max_rework_attempts: 3
    });
    const [deploying, setDeploying] = useState(false);
    const [result, setResult] = useState(null);
    const [deployError, setDeployError] = useState(null);
    const [userConfig, setUserConfig] = useState(null);
    const [nodes, setNodes] = useState([]);

    useEffect(() => {
        const loadConfig = async () => {
            try {
                const conf = await getUserConfig();
                setUserConfig(conf);
                
                const providers = Object.keys(conf?.effective?.llm?.providers || {});
                const defaultProvider = conf?.effective?.llm?.active_provider || (providers.length > 0 ? providers[0] : '');
                
                setForm(f => ({ ...f, provider_name: defaultProvider }));
            } catch (e) {
                console.warn("Failed to load user config for provider setup", e);
            }
            try {
                const fetchedNodes = await getUserAccessibleNodes();
                setNodes(fetchedNodes);
                if (fetchedNodes.length > 0) {
                    setForm(f => ({ ...f, mesh_node_id: fetchedNodes[0].node_id }));
                }
            } catch (e) {
                console.warn("Failed to load nodes", e);
            }
        };
        loadConfig();
    }, []);

    const handleDeploy = async (e) => {
        e.preventDefault();
        if (!form.name.trim()) return;
        setDeploying(true);
        setDeployError(null);
        try {
            const res = await deployAgent({
                ...form,
                mesh_node_id: form.mesh_node_id || null,
                system_prompt: form.system_prompt || null,
                initial_prompt: form.initial_prompt || null,
                description: form.description || null,
                provider_name: form.provider_name || null
            });
            setResult(res);
            setTimeout(() => onDeployed(), 1500);
        } catch (err) {
            setDeployError(err.message);
        } finally {
            setDeploying(false);
        }
    };

    const update = (key, val) => setForm(prev => ({ ...prev, [key]: val }));

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-gray-900/40 backdrop-blur-sm p-4">
            <div className="bg-white dark:bg-gray-800 shadow-2xl rounded-2xl w-full max-w-lg overflow-hidden border border-gray-100 dark:border-gray-700 transform transition-all p-8 relative">
                <div className="absolute top-0 right-0 w-64 h-64 bg-indigo-500/5 blur-[80px] rounded-full pointer-events-none -z-10" />
                <div className="flex justify-between items-start mb-6">
                    <div>
                        <h2 className="text-2xl font-bold text-gray-900 dark:text-white mb-1">Deploy Agent</h2>
                        <p className="text-gray-500 dark:text-gray-400 text-sm">Configure a new autonomous instance to connect to the mesh.</p>
                    </div>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors text-xl">&times;</button>
                </div>

                {result ? (
                    <div className="text-center py-8">
                        <div className="text-5xl mb-4">🚀</div>
                        <p className="text-emerald-400 font-bold text-lg">{result.message}</p>
                        <p className="text-gray-500 text-xs mt-2 font-mono">ID: {result.instance_id}</p>
                    </div>
                ) : (
                    <form onSubmit={handleDeploy} className="space-y-5 relative z-10">
                        {/* Name & Provider */}
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Agent Name</label>
                                <input
                                    autoFocus
                                    value={form.name}
                                    onChange={e => update('name', e.target.value)}
                                    placeholder="e.g. System Monitor, QA Tester"
                                    className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100"
                                    required
                                />
                            </div>
                            <div>
                                <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Active LLM Provider</label>
                                <select
                                    value={form.provider_name}
                                    onChange={e => update('provider_name', e.target.value)}
                                    className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100"
                                >
                                    {userConfig?.effective?.llm?.providers && Object.keys(userConfig.effective.llm.providers).map(pid => (
                                        <option key={pid} value={pid}>{pid} {userConfig.effective.llm.providers[pid].model ? `(${userConfig.effective.llm.providers[pid].model})` : ''}</option>
                                    ))}
                                </select>
                            </div>
                        </div>

                        {/* Description */}
                        <div>
                            <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Description</label>
                            <input
                                value={form.description}
                                onChange={e => update('description', e.target.value)}
                                placeholder="Brief description of what this agent does"
                                className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100"
                            />
                        </div>

                        {/* System Prompt */}
                        <div>
                            <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">System Prompt (Persona)</label>
                            <textarea
                                value={form.system_prompt}
                                onChange={e => update('system_prompt', e.target.value)}
                                placeholder="Define the agent's role and constraints..."
                                rows={3}
                                className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100 resize-none"
                            />
                        </div>

                        {/* Node + Iterations row */}
                        <div className="grid grid-cols-2 gap-4">
                            <div>
                                <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Target Mesh Node</label>
                                <select
                                    value={form.mesh_node_id}
                                    onChange={e => update('mesh_node_id', e.target.value)}
                                    className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100"
                                    required
                                >
                                    {nodes.map(n => <option key={n.node_id} value={n.node_id}>{n.display_name}</option>)}
                                </select>
                            </div>
                            <div>
                                <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Max Iterations</label>
                                <input
                                    type="number"
                                    value={form.max_loop_iterations}
                                    onChange={e => update('max_loop_iterations', parseInt(e.target.value) || 20)}
                                    className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100"
                                />
                            </div>
                        </div>

                        {/* Initial Prompt */}
                        <div>
                            <label className="text-xs text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Initial Prompt (optional — starts loop immediately)</label>
                            <textarea
                                value={form.initial_prompt}
                                onChange={e => update('initial_prompt', e.target.value)}
                                placeholder="What should the agent do first? Leave empty for idle mode."
                                rows={2}
                                className="w-full bg-gray-50 dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 text-gray-900 dark:text-gray-100 resize-none"
                            />
                        </div>

                        {/* Automation & Triggers */}
                        <div className="bg-gray-50 dark:bg-gray-950/50 p-5 rounded-xl border border-gray-200 dark:border-gray-800 space-y-4">
                            <h4 className="text-xs font-bold text-gray-500 dark:text-gray-400 uppercase tracking-widest flex items-center">
                                <span className="mr-2">⚙️</span> Automation & Triggers
                            </h4>
                            
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="text-xs text-gray-400 block mb-1">Trigger Type</label>
                                    <select
                                        value={form.trigger_type}
                                        onChange={e => update('trigger_type', e.target.value)}
                                        className="w-full bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 text-gray-900 dark:text-gray-100"
                                    >
                                        <option value="manual">Off-hand Request (Manual)</option>
                                        <option value="cron">Fixed Schedule (CRON)</option>
                                        <option value="interval">Recurrent (Interval-based)</option>
                                        <option value="webhook">External Webhook</option>
                                    </select>
                                </div>
                                {form.trigger_type === 'cron' && (
                                    <div>
                                        <label className="text-xs text-gray-400 block mb-1">Cron Expression (e.g. 0 * * * *)</label>
                                        <input
                                            value={form.cron_expression}
                                            onChange={e => update('cron_expression', e.target.value)}
                                            placeholder="*/5 * * * *"
                                            className="w-full bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 text-gray-900 dark:text-gray-100"
                                            required={form.trigger_type === 'cron'}
                                        />
                                    </div>
                                )}
                                {form.trigger_type === 'interval' && (
                                    <div>
                                        <label className="text-xs text-gray-400 block mb-1">Wait Time (seconds after completion)</label>
                                        <input
                                            type="number"
                                            value={form.interval_seconds}
                                            onChange={e => update('interval_seconds', parseInt(e.target.value) || 60)}
                                            placeholder="60"
                                            className="w-full bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 text-gray-900 dark:text-gray-100"
                                            required={form.trigger_type === 'interval'}
                                        />
                                    </div>
                                )}
                            </div>

                            <div>
                                <label className="text-xs text-gray-400 block mb-1">
                                    {form.trigger_type === 'cron' || form.trigger_type === 'interval' ? 'Fixed Automation Prompt' : 'Default Predefined Prompt'}
                                </label>
                                <textarea
                                    value={form.default_prompt}
                                    onChange={e => update('default_prompt', e.target.value)}
                                    placeholder={form.trigger_type === 'manual' || form.trigger_type === 'webhook' ? "Used if no data is provided in the request" : "Command to execute on each cycle"}
                                    rows={2}
                                    className="w-full bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-indigo-500 text-gray-900 dark:text-gray-100 resize-none"
                                />
                                {(form.trigger_type === 'manual' || form.trigger_type === 'webhook') && (
                                    <p className="text-[10px] text-gray-500 mt-1 italic">
                                        * For passive triggers, incoming request data can override this prompt.
                                    </p>
                                )}
                            </div>
                        </div>

                        {/* Co-Worker Quality Gate Settings */}
                        <div className="bg-gradient-to-br from-indigo-50/50 to-purple-50/50 dark:from-indigo-500/5 dark:to-purple-500/5 p-5 rounded-xl border border-indigo-100 dark:border-indigo-500/20 space-y-4">
                            <div className="flex items-center justify-between">
                                <h4 className="text-xs font-bold text-indigo-600 dark:text-indigo-400 uppercase tracking-widest flex items-center">
                                    <span className="mr-2">🛡️</span> Co-Worker Quality Gate
                                </h4>
                                <label className="relative inline-flex items-center cursor-pointer">
                                    <input 
                                        type="checkbox" 
                                        className="sr-only peer"
                                        checked={form.co_worker_quality_gate}
                                        onChange={(e) => update('co_worker_quality_gate', e.target.checked)}
                                    />
                                    <div className="w-9 h-5 bg-gray-200 peer-focus:outline-none rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-indigo-500"></div>
                                </label>
                            </div>

                            {form.co_worker_quality_gate && (
                                <div className="space-y-4 animate-in slide-in-from-top-2 duration-200">
                                    <div className="grid grid-cols-2 gap-4">
                                        <div>
                                            <div className="flex justify-between items-center mb-1.5">
                                                <label className="text-[10px] text-gray-500 dark:text-gray-400 uppercase tracking-widest">Rework Threshold</label>
                                                <span className="text-[10px] font-bold text-indigo-500">{form.rework_threshold}%</span>
                                            </div>
                                            <input 
                                                type="range" 
                                                min="1" 
                                                max="100" 
                                                value={form.rework_threshold} 
                                                onChange={(e) => update('rework_threshold', parseInt(e.target.value))}
                                                className="w-full h-1.5 bg-gray-200 dark:bg-gray-700 rounded-lg appearance-none cursor-pointer accent-indigo-500" 
                                            />
                                        </div>
                                        <div>
                                            <label className="text-[10px] text-gray-500 dark:text-gray-400 uppercase tracking-widest block mb-1.5">Max Attempts</label>
                                            <input 
                                                type="number" 
                                                min="1" 
                                                max="10" 
                                                value={form.max_rework_attempts} 
                                                onChange={(e) => update('max_rework_attempts', parseInt(e.target.value) || 1)}
                                                className="w-full bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg px-3 py-1.5 text-xs focus:outline-none focus:border-indigo-500 text-gray-900 dark:text-gray-100" 
                                            />
                                        </div>
                                    </div>
                                    <p className="text-[9px] text-gray-500 italic">
                                        * If enabled, a Co-Worker agent will evaluate the Main Agent's output. If the score is below {form.rework_threshold}%, up to {form.max_rework_attempts} rework cycles will be triggered.
                                    </p>
                                </div>
                            )}
                        </div>

                        {deployError && (
                            <div className="bg-red-900/30 border border-red-500/30 text-red-300 text-sm px-4 py-2 rounded-lg">
                                {deployError}
                            </div>
                        )}

                        <button
                            type="submit"
                            disabled={deploying || !form.name.trim()}
                            className="w-full py-3 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white font-bold tracking-wide transition-all disabled:opacity-40 disabled:cursor-not-allowed"
                        >
                            {deploying ? 'Deploying...' : '🚀 Deploy Agent'}
                        </button>
                    </form>
                )}
            </div>
        </div>
    );
};


// ─────────────────────────────────────────────────────────────
// Agent Card Component
// ─────────────────────────────────────────────────────────────
const AgentCard = ({ agent, onNavigate, onStatusChange }) => {
    const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
    const [deleteError, setDeleteError] = useState(null);
    const [isDeleting, setIsDeleting] = useState(false);
    const [triggers, setTriggers] = useState([]);
    const [copiedId, setCopiedId] = useState(null);

    // Live Trace States
    const [runningSeconds, setRunningSeconds] = useState(0);
    const [lastTotalConsumption, setLastTotalConsumption] = useState(null);
    const [previousStatus, setPreviousStatus] = useState(agent.status || 'idle');

    useEffect(() => {
        let isMounted = true;
        const fetchTriggers = async () => {
            try {
                const t = await getAgentTriggers(agent.id);
                if (isMounted) setTriggers(t);
            } catch (err) {}
        };
        fetchTriggers();
        return () => { isMounted = false; };
    }, [agent.id]);

    useEffect(() => {
        let interval = null;
        if (agent.status === 'active') {
            if (previousStatus !== 'active') {
                setRunningSeconds(0);
                setLastTotalConsumption(null);
            }
            interval = setInterval(() => {
                setRunningSeconds(s => s + 1);
            }, 1000);
        } else if (previousStatus === 'active' && agent.status !== 'active') {
            setLastTotalConsumption(runningSeconds);
        }
        setPreviousStatus(agent.status || 'idle');
        return () => clearInterval(interval);
    }, [agent.status, runningSeconds, previousStatus]);

    const handleAction = async (status) => {
        try {
            await updateAgentStatus(agent.id, status);
            onStatusChange();
        } catch (e) {
            console.error('Failed to update status: ', e);
        }
    };

    const confirmDelete = async () => {
        setIsDeleting(true);
        setDeleteError(null);
        try {
            await deleteAgent(agent.id);
            onStatusChange();
        } catch (e) {
            setDeleteError(e.message);
            setIsDeleting(false);
        }
    };

    const isError = agent.status === 'error_suspended';
    const isPaused = agent.status === 'paused_mid_loop' || agent.status === 'suspended';
    
    const statusTheme = isError ? 'text-rose-400 bg-rose-500/10 border-rose-500/30 ring-rose-500/20' : 
                        isPaused ? 'text-amber-400 bg-amber-500/10 border-amber-500/30 ring-amber-500/20' : 
                        'text-emerald-400 bg-emerald-500/10 border-emerald-500/30 ring-emerald-500/20';

    return (
        <div className="group relative rounded-2xl bg-white dark:bg-gray-800 shadow-lg border border-gray-200 dark:border-gray-700 p-6 flex flex-col justify-between overflow-hidden transition-all duration-300 hover:shadow-indigo-500/10 hover:border-indigo-500/30">
            <div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/5 blur-[80px] group-hover:bg-indigo-500/10 transition-colors pointer-events-none" />

            {showDeleteConfirm && (
                <div className="absolute inset-0 z-50 bg-gray-900/60 backdrop-blur-sm flex items-center justify-center p-4 rounded-2xl">
                    <div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 shadow-2xl rounded-xl p-5 w-full max-w-sm animate-in fade-in zoom-in duration-200">
                        <h3 className="text-lg font-bold text-gray-900 dark:text-gray-100 mb-2">Confirm Deletion</h3>
                        <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">Are you sure you want to delete this agent? This cannot be undone.</p>
                        {deleteError && (
                            <p className="text-xs text-red-500 mb-4 p-2 bg-red-50 dark:bg-red-500/10 rounded">{deleteError}</p>
                        )}
                        <div className="flex gap-3 justify-end mt-2">
                            <button 
                                onClick={() => setShowDeleteConfirm(false)}
                                disabled={isDeleting}
                                className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
                            >
                                Cancel
                            </button>
                            <button 
                                onClick={confirmDelete}
                                disabled={isDeleting}
                                className="px-4 py-2 text-sm font-bold text-white bg-red-600 hover:bg-red-500 rounded-lg shadow transition-colors disabled:opacity-50 flex items-center gap-2"
                            >
                                {isDeleting ? 'Deleting...' : 'Delete'}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            <div className="relative z-10">
                <div className="flex justify-between items-start mb-4">
                    <div className="truncate pr-4 relative group cursor-help">
                        {/* Tooltip */}
                        <div className="absolute top-full left-0 mt-2 w-64 bg-gray-900 text-white text-xs rounded-lg shadow-xl p-3 opacity-0 group-hover:opacity-100 transition-opacity z-50 pointer-events-none">
                            <div className="mb-1 font-bold">Execution Stats</div>
                            <div className="grid grid-cols-2 gap-y-1 mt-2 text-[10px] text-gray-300">
                                <span>Max Iterations:</span> <span className="text-right text-gray-100">{agent.template?.max_loop_iterations || 20}</span>
                                <span>Run Iterations:</span> <span className="text-right text-emerald-400">{agent?.total_runs || 0}</span>
                                <span>Success Rate:</span> <span className="text-right text-emerald-400">{agent?.total_runs ? Math.round(((agent?.successful_runs || 0) / agent.total_runs) * 100) : 0}%</span>
                            </div>
                        </div>

                        <h2 className="text-xl font-bold flex items-center gap-2 text-gray-900 dark:text-gray-100 truncate cursor-pointer hover:text-indigo-600 dark:hover:text-indigo-400 transition-colors"
                            onClick={() => onNavigate(`/agents/drilldown/${agent.id}`)}
                            title={agent.id}>
                            <span className="truncate">{agent.template?.name || 'Agent'}</span>
                            <svg className="w-4 h-4 text-gray-400 opacity-50 group-hover:opacity-100 group-hover:text-indigo-500 transition-all flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
                            </svg>
                        </h2>
                        <div className="flex items-center gap-2 mt-1">
                            <span className="text-[10px] uppercase tracking-widest text-gray-500 dark:text-gray-400 block" title={agent.id}>ID: {agent.id.split('-')[0]}</span>
                            {agent.template?.co_worker_quality_gate && (
                                <span className="text-[8px] font-bold px-1.5 py-0.5 rounded-full bg-indigo-500/10 text-indigo-500 border border-indigo-500/20">SHIELD-ON</span>
                            )}
                        </div>
                    </div>
                    <div className="flex flex-col items-end gap-1.5">
                        <div className={`px-2.5 py-1 rounded-md text-[10px] font-bold uppercase tracking-widest border ring-1 ring-inset shadow-inner whitespace-nowrap ${statusTheme}`}>
                            {agent.status}
                        </div>
                        {agent.evaluation_status && (
                             <div className="flex items-center gap-1.5 mt-1">
                                {(agent.status === 'active' || lastTotalConsumption) && (
                                    <div className={`px-1.5 py-0.5 rounded-[4px] text-[8px] font-mono font-bold flex items-center gap-1 tracking-tight ${
                                        agent.status === 'active' ? 'bg-indigo-500/10 text-indigo-500 border border-indigo-500/20 animate-pulse' : 'bg-emerald-500/10 text-emerald-500 border border-emerald-500/20'
                                    }`}>
                                        <svg className={`w-2 h-2 ${agent.status === 'active' ? 'animate-spin' : ''}`} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                                        {agent.status === 'active' ? `${runningSeconds}s` : `${lastTotalConsumption}s`}
                                    </div>
                                )}
                                <div className={`px-2 py-0.5 rounded text-[8px] font-black uppercase tracking-widest animate-pulse border transition-all duration-500 truncate max-w-[120px] ${
                                    agent.evaluation_status.includes('passed') ? 'bg-emerald-500/5 text-emerald-500 border-emerald-500/20' : 
                                    agent.evaluation_status.includes('reworking') ? 'bg-amber-500/5 text-amber-500 border-amber-500/20' : 
                                    'bg-indigo-500/5 text-indigo-500 border-indigo-500/20'
                                }`}>
                                    {agent.evaluation_status.includes('reworking') ? `Reworking (${agent.current_rework_attempt}/${agent.template?.max_rework_attempts || 3})` : agent.evaluation_status}
                                </div>
                            </div>
                        )}
                    </div>
                </div>

                <div className="flex items-center gap-4 mb-4">
                    <BuddyAvatar score={agent.latest_quality_score} status={agent.evaluation_status} />
                    <div className="flex-1">
                        {agent.mesh_node_id && (
                            <div className="text-[10px] uppercase tracking-wider text-gray-500 dark:text-gray-400">
                                Node: <span className="text-indigo-600 dark:text-indigo-400 font-bold">{agent.mesh_node_id}</span>
                            </div>
                        )}
                        <div className="flex items-center gap-2 mt-0.5">
                            <div className="h-1 flex-1 bg-gray-100 dark:bg-gray-800 rounded-full overflow-hidden">
                                <div 
                                    className={`h-full transition-all duration-1000 ${agent.latest_quality_score >= 80 ? 'bg-emerald-500' : agent.latest_quality_score >= 60 ? 'bg-amber-500' : 'bg-rose-500'}`}
                                    style={{ width: `${agent.latest_quality_score || 0}%` }}
                                />
                            </div>
                            <span className="text-[10px] font-black text-gray-500 font-mono">{agent.latest_quality_score || 0}%</span>
                        </div>
                    </div>
                </div>

                {isError && agent.last_error && (
                    <div className="mb-4 p-3 rounded-xl bg-rose-500/10 border border-rose-500/30 text-rose-400 animate-in fade-in slide-in-from-top-1 duration-300">
                        <div className="flex items-center gap-2 mb-1">
                            <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                            </svg>
                            <span className="text-[10px] font-black uppercase tracking-widest">Diagnostic Error</span>
                        </div>
                        <p className="text-[11px] font-mono leading-relaxed line-clamp-3 overflow-hidden break-words">
                            {agent.last_error}
                        </p>
                    </div>
                )}

                {/* Triggers Summary */}
                <div className="mb-3 flex flex-wrap gap-1.5 min-h-[20px]">
                    {triggers.length === 0 ? (
                        <span className="text-[10px] text-gray-400 dark:text-gray-600 uppercase font-mono tracking-widest bg-gray-50 dark:bg-gray-800/50 px-2 py-0.5 rounded border border-gray-100 dark:border-gray-800">No Triggers</span>
                    ) : (
                        triggers.map(t => (
                            <div key={t.id}>
                                {t.trigger_type === 'cron' && <span className="text-[9px] font-bold text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800/80 px-2 py-0.5 rounded-full border border-gray-200 dark:border-gray-700 flex items-center shadow-sm">⏰ {t.cron_expression}</span>}
                                {t.trigger_type === 'interval' && <span className="text-[9px] font-bold text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800/80 px-2 py-0.5 rounded-full border border-gray-200 dark:border-gray-700 flex items-center shadow-sm">🔄 {t.interval_seconds}s</span>}
                                {t.trigger_type === 'webhook' && (
                                    <button 
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            const url = `${window.location.origin}/api/v1/agents/${agent.id}/webhook?token=${t.webhook_secret}`;
                                            navigator.clipboard.writeText(url);
                                            setCopiedId(t.id);
                                            setTimeout(() => setCopiedId(null), 2000);
                                        }}
                                        className={`text-[9px] font-bold px-2 py-0.5 rounded-full border flex items-center shadow-sm transition-all focus:outline-none ${
                                            copiedId === t.id 
                                            ? 'text-emerald-500 bg-emerald-500/10 border-emerald-500/30' 
                                            : 'text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800/80 border-gray-200 dark:border-gray-700 hover:border-indigo-400 hover:text-indigo-500'
                                        }`}
                                        title="Click to copy Webhook URL"
                                    >
                                        {copiedId === t.id ? '✅ Copied' : '🔗 Webhook'}
                                    </button>
                                )}
                                {t.trigger_type === 'manual' && <span className="text-[9px] font-bold text-gray-600 dark:text-gray-300 bg-gray-100 dark:bg-gray-800/80 px-2 py-0.5 rounded-full border border-gray-200 dark:border-gray-700 flex items-center shadow-sm">🖐️ Manual</span>}
                            </div>
                        ))
                    )}
                </div>

                <div className="mb-4 grid grid-cols-3 gap-3">
                     <div className="bg-gray-50 dark:bg-gray-900 border border-gray-100 dark:border-gray-800 rounded-lg p-2.5 shadow-sm">
                         <span className="text-[10px] text-gray-500 font-bold block mb-0.5 uppercase tracking-wider">Runs</span>
                         <span className="text-lg font-black text-indigo-500">{agent?.total_runs || 0}</span>
                     </div>
                     <div 
                         className="bg-gray-50 dark:bg-gray-900 border border-gray-100 dark:border-gray-800 rounded-lg p-2.5 shadow-sm cursor-help"
                         title={`${agent?.successful_runs || 0} / ${agent?.total_runs || 0} (${(agent?.total_runs || 0) - (agent?.successful_runs || 0)})`}
                     >
                         <span className="text-[10px] text-gray-500 font-bold block mb-0.5 uppercase tracking-wider">Success</span>
                         <span className="text-lg font-black text-emerald-500">{agent?.total_runs ? Math.round(((agent?.successful_runs || 0) / agent.total_runs) * 100) : 0}%</span>
                     </div>
                     <div className="bg-gray-50 dark:bg-gray-900 border border-gray-100 dark:border-gray-800 rounded-lg p-2.5 shadow-sm">
                         <span className="text-[10px] text-gray-500 font-bold block mb-0.5 uppercase tracking-wider">Last Run</span>
                         <span className="text-[10px] font-black text-blue-500 block pt-1.5">{formatTimeLocal(agent?.last_heartbeat)}</span>
                     </div>
                </div>


            </div>

            <div className="flex gap-2 relative z-10 border-t border-gray-200 dark:border-gray-800/50 pt-4 mt-auto">
                <button
                    onClick={() => setShowDeleteConfirm(true)}
                    className="p-2 rounded-lg bg-gray-100 hover:bg-red-50 text-gray-500 hover:text-red-500 dark:bg-gray-800/50 dark:hover:bg-red-500/10 dark:hover:text-red-400 border border-gray-200 dark:border-gray-700 dark:hover:border-red-500/30 hover:border-red-200 transition-all duration-200"
                    title="Delete Agent"
                >
                    <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                </button>
                
                <div className="flex-1 flex justify-end">
                    {isPaused || isError ? (
                        <button
                            onClick={() => handleAction('idle')}
                            title="Resume Agent"
                            className="flex-1 flex justify-center items-center py-1.5 rounded-lg bg-emerald-50 dark:bg-emerald-500/10 hover:bg-emerald-100 dark:hover:bg-emerald-500/20 border border-emerald-200 dark:border-emerald-500/20 text-emerald-600 dark:text-emerald-400 transition-colors"
                        >
                            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clipRule="evenodd" /></svg>
                            <span className="ml-2 text-xs font-bold uppercase tracking-wider">Resume</span>
                        </button>
                    ) : (
                        <button
                            onClick={() => handleAction('suspended')}
                            title="Stop/Pause Loop"
                            className="flex-1 flex justify-center items-center py-1.5 rounded-lg bg-amber-50 dark:bg-amber-500/10 hover:bg-amber-100 dark:hover:bg-amber-500/20 border border-amber-200 dark:border-amber-500/20 text-amber-600 dark:text-amber-500 transition-colors"
                        >
                            <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20"><path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" /></svg>
                            <span className="ml-2 text-xs font-bold uppercase tracking-wider">Pause</span>
                        </button>
                    )}
                </div>
            </div>
        </div>
    );
};
