"use client"; import { useState, useEffect, useRef } from "react"; const AGENT_CONFIG: Record = { horus: { name: "Horus", avatar: "πŸ‘οΈ", color: "#ff7bc0", role: "Master Orchestrator", description: "Command center, delegates tasks, manages all agents", skills: ["Task delegation", "System orchestration", "Strategic planning"] }, thoth: { name: "Thoth", avatar: "🧠", color: "#8b5cf6", role: "Strategy & Research", description: "SiteMente planning, research, analysis", skills: ["Market research", "Competitor analysis", "AI trends", "Lead research"] }, "thoth-trading": { name: "Thoth Trading", avatar: "πŸ“ˆ", color: "#f59e0b", role: "Market Research", description: "Crypto market analysis and research", skills: ["Technical analysis", "Price alerts", "Portfolio tracking"] }, ptah: { name: "Ptah", avatar: "πŸ—οΈ", color: "#10b981", role: "Dev & Ops", description: "Development, deployment, technical implementation", skills: ["Code review", "Deployments", "Infra management", "Bug fixes"] }, seshat: { name: "Seshat", avatar: "πŸ“œ", color: "#ec4899", role: "Content & SEO", description: "Content strategy, SEO, marketing copy", skills: ["SEO optimization", "Copywriting", "Blog posts", "Social media"] }, anubis: { name: "Anubis", avatar: "🐺", color: "#6366f1", role: "Outreach & Growth", description: "Lead generation, client acquisition", skills: ["Lead research", "Cold outreach", "Follow-ups", "Deal closing"] }, sekhmet: { name: "Sekhmet", avatar: "βš”οΈ", color: "#ef4444", role: "Risk Management", description: "Trade execution and risk", skills: ["Risk assessment", "Trade execution", "Stop-loss management"] }, }; interface AgentModalProps { agentId: string; onClose: () => void; } export default function AgentModal({ agentId, onClose }: AgentModalProps) { const agent = AGENT_CONFIG[agentId] || { name: agentId, avatar: "πŸ€–", color: "#666", role: "Agent", description: "", skills: [] }; const [tasks, setTasks] = useState([]); const [templates, setTemplates] = useState([]); const [logs, setLogs] = useState([]); const [changelog, setChangelog] = useState([]); const [brainownNotes, setBrainownNotes] = useState([]); const [loading, setLoading] = useState(true); const [agentStatus, setAgentStatus] = useState<"idle" | "active" | "error">("idle"); const [tokens, setTokens] = useState("0"); const [lastRun, setLastRun] = useState(null); // Command input const [command, setCommand] = useState(""); const [conversation, setConversation] = useState<{role: string, content: string}[]>([]); const [processing, setProcessing] = useState(false); const conversationEndRef = useRef(null); const [expanded, setExpanded] = useState>({ tasks: true, recurring: true, logs: true, changelog: true, brainown: true, }); useEffect(() => { fetchAllData(); }, [agentId]); useEffect(() => { conversationEndRef.current?.scrollIntoView({ behavior: "smooth" }); }, [conversation]); const fetchAllData = async () => { setLoading(true); try { const tRes = await fetch("/api/tasks"); if (tRes.ok) { const allTasks = await tRes.json(); const agentTasks = allTasks.filter((t: any) => t.assignee === agentId || t.project === getAgentProject(agentId) ); setTasks(agentTasks); } } catch {} try { const rRes = await fetch("/api/recurring"); if (rRes.ok) { const allTemplates = await rRes.json(); const agentTemplates = allTemplates.filter((t: any) => t.agent === agentId); setTemplates(agentTemplates); if (agentTemplates.length > 0) { const last = agentTemplates.reduce((prev: any, curr: any) => (!curr.lastRun || new Date(curr.lastRun) > new Date(prev.lastRun || 0) ? curr : prev), {}); if (last.lastRun) setLastRun(last.lastRun); } } } catch {} try { const lRes = await fetch(`/api/execution-logs?agent=${agentId}&limit=20`); if (lRes.ok) { const agentLogs = await lRes.json(); setLogs(agentLogs); if (agentLogs.length > 0) { setLastRun(agentLogs[0].startedAt); const running = agentLogs.find((l: any) => l.status === "running"); setAgentStatus(running ? "active" : "idle"); } } } catch {} try { const cRes = await fetch(`/api/changelog?agent=${agentId}&limit=20`); if (cRes.ok) setChangelog(await cRes.json()); } catch {} try { const bRes = await fetch(`/api/agent-outputs?agent=${agentId}`); if (bRes.ok) { const dates = await bRes.json(); const notes: any[] = []; for (const date of dates.slice(0, 10)) { const noteRes = await fetch(`/api/agent-outputs?agent=${agentId}&date=${date}`); if (noteRes.ok) { const note = await noteRes.json(); if (note.content) notes.push({ date, content: note.content }); } } setBrainownNotes(notes); } } catch {} setTokens((Math.random() * 2).toFixed(1)); setLoading(false); }; const getAgentProject = (id: string): string => { const map: Record = { thoth: "sitemente", "thoth-trading": "trading", ptah: "infrastructure", seshat: "sitemente", anubis: "sitemente", sekhmet: "trading", }; return map[id] || "sitemente"; }; const toggleSection = (section: string) => { setExpanded(prev => ({ ...prev, [section]: !prev[section] })); }; const toggleTemplate = async (templateId: string, enabled: boolean) => { await fetch("/api/recurring", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "toggle", templateId, enabled }) }); fetchAllData(); }; const runNow = async (templateId: string) => { setAgentStatus("active"); await fetch("/api/recurring", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "run-now", templateId }) }); setTimeout(fetchAllData, 2000); }; const sendCommand = async () => { if (!command.trim() || processing) return; const userCommand = command; setCommand(""); setConversation(prev => [...prev, { role: "user", content: userCommand }]); setProcessing(true); // Simulate agent response setTimeout(() => { const responses: Record = { thoth: `I've researched "${userCommand}" for SiteMente. Here are my findings:\n\n1. Market trends show increasing demand for AI chatbots\n2. Local competitors: 3 agencies in MΓ‘laga\n3. Recommended approach: Focus on restaurants first`, "thoth-trading": `Market analysis for "${userCommand}":\n\nπŸ“Š BTC: $67,234 (+2.3%)\nπŸ“Š ETH: $3,456 (+1.8%)\nπŸ“Š SOL: $145 (+3.1%)\n\nNo significant alerts at this time.`, ptah: `Running "${userCommand}" on infrastructure...\n\nβœ… Completed: Code reviewed, no critical issues found.\nπŸ’‘ Suggestion: Consider adding unit tests for the new module.`, seshat: `Creating content for "${userCommand}"...\n\nπŸ“ Blog post outline generated\nπŸ“ 3 social media posts drafted\nπŸ“ SEO keywords optimized`, anubis: `Searching for leads for "${userCommand}"...\n\nπŸ” Found 12 potential restaurants in BenalmΓ‘dena\nπŸ“‹ Top prospect: Restaurante El Puerto (50 seats, no website)\nπŸ“ž Recommended: Schedule demo call this week`, sekhmet: `Risk assessment for "${userCommand}":\n\n⚠️ Current drawdown: 3.2%\nβœ… All positions within risk limits\nπŸ’‘ Recommendation: No action needed`, horus: `I've noted your request: "${userCommand}"\n\nI'll delegate this to the appropriate agent and track progress. You can see updates in the Mission Control dashboard.`, }; setConversation(prev => [...prev, { role: "agent", content: responses[agentId] || `Understood: "${userCommand}". I'm processing this request and will update you shortly.` }]); setProcessing(false); }, 1500); }; const todoTasks = tasks.filter((t: any) => t.status === "todo"); const inProgressTasks = tasks.filter((t: any) => t.status === "in_progress"); const doneTasks = tasks.filter((t: any) => t.status === "done"); const getStatusBadge = (status: string) => { switch (status) { case "active": return ● Active; case "idle": return ● Idle; case "error": return ● Error; default: return null; } }; return (
{/* Header */}
{agent.avatar}

{agent.name}

{agent.role}

{/* Status Bar */}
{getStatusBadge(agentStatus)} Tokens: {tokens}k {lastRun && Last: {new Date(lastRun).toLocaleTimeString()}}
{agent.project || getAgentProject(agentId)}
{/* Skills */}
{agent.skills.map((skill, i) => ( {skill} ))}
{/* Content - Scrollable */}
{/* πŸ’¬ CONVERSATION */}
πŸ’¬ Chat with {agent.name}
{conversation.length === 0 ? (

Ask {agent.name} anything about {agent.role}...

) : ( conversation.map((msg, i) => (
{msg.content}
)) )} {processing && (
⏳ Processing...
)}
setCommand(e.target.value)} onKeyDown={(e) => e.key === "Enter" && sendCommand()} placeholder={`Ask ${agent.name} to...`} className="flex-1 bg-white/10 border border-white/20 rounded-lg px-3 py-2 text-sm placeholder:text-white/40 focus:outline-none focus:border-brand-pink" disabled={processing} />
{/* πŸ“‹ TASKS */}
{expanded.tasks && (

To Do ({todoTasks.length})

{todoTasks.slice(0, 3).map((t: any) => (
{t.title}
))}

In Progress ({inProgressTasks.length})

{inProgressTasks.slice(0, 3).map((t: any) => (
{t.title}
))}

Done ({doneTasks.length})

{doneTasks.slice(0, 3).map((t: any) => (
{t.title}
))}
)}
{/* πŸ”„ RECURRING */}
{expanded.recurring && (
{templates.length === 0 ?

No recurring tasks

: templates.map((t: any) => (

{t.taskTemplate.title}

{t.schedule.type === "hourly" ? "Hourly" : t.schedule.time ? `${t.schedule.time} CET` : t.schedule.type}

)) }
)}
{/* πŸ“Š LOGS */}
{expanded.logs && (
{logs.length === 0 ?

No logs

: logs.slice(0, 5).map((l: any) => (
{l.taskTitle}
{l.status}
)) }
)}
{/* πŸ“ CHANGE LOG */}
{expanded.changelog && (
{changelog.length === 0 ?

No changes

: changelog.slice(0, 5).map((c: any) => (
v{c.version || "1.0"} {new Date(c.date).toLocaleDateString()}

{c.description}

)) }
)}
{/* 🧠 BRAINOWN */}
{expanded.brainown && (
{brainownNotes.length === 0 ?

No outputs

: brainownNotes.map((n: any) => (
πŸ“„ {n.date}
{n.content.substring(0, 80)}...
)) }
)}
); }