/* CRM Agents Hub — primary view: orchestrator + 4 specialist agents + activity */
const { useState: useAg, useEffect: useAge, useRef: useAr } = React;

/* ---------- Agent glyph mark (unique per role) ---------- */
function AgentMark({ kind, size = 28, color = "currentColor" }) {
  const s = { width: size, height: size };
  switch (kind) {
    case "procurement":
      return (
        <svg style={s} viewBox="0 0 40 40" fill="none" stroke={color} strokeWidth="1">
          <path d="M6 12h28l-3 18H9z" />
          <path d="M14 12V7h12v5" />
          <circle cx="14" cy="22" r="1.4" fill={color}/>
          <circle cx="20" cy="22" r="1.4" fill={color}/>
          <circle cx="26" cy="22" r="1.4" fill={color}/>
          <path d="M6 12L20 4 34 12" strokeDasharray="1.5 1.5" opacity="0.6"/>
        </svg>
      );
    case "finance":
      return (
        <svg style={s} viewBox="0 0 40 40" fill="none" stroke={color} strokeWidth="1">
          <circle cx="20" cy="20" r="14" />
          <path d="M20 8v24" />
          <path d="M14 14h9a3 3 0 010 6H14a3 3 0 000 6h12" />
          <circle cx="20" cy="8" r="1.4" fill={color} />
          <circle cx="20" cy="32" r="1.4" fill={color} />
        </svg>
      );
    case "production":
      return (
        <svg style={s} viewBox="0 0 40 40" fill="none" stroke={color} strokeWidth="1">
          <rect x="6" y="20" width="6" height="14"/>
          <rect x="14" y="14" width="6" height="20"/>
          <rect x="22" y="6" width="6" height="28"/>
          <rect x="30" y="22" width="4" height="12"/>
          <path d="M4 34h32" />
          <circle cx="9" cy="20" r="1.2" fill={color}/>
          <circle cx="17" cy="14" r="1.2" fill={color}/>
          <circle cx="25" cy="6" r="1.2" fill={color}/>
        </svg>
      );
    case "client":
      return (
        <svg style={s} viewBox="0 0 40 40" fill="none" stroke={color} strokeWidth="1">
          <circle cx="20" cy="14" r="6"/>
          <path d="M8 34c0-7 5-11 12-11s12 4 12 11"/>
          <path d="M28 6l3 3-3 3" strokeDasharray="1.5 1.5" opacity="0.7"/>
          <circle cx="20" cy="14" r="1.4" fill={color}/>
        </svg>
      );
    default: return null;
  }
}

/* ---------- Orchestrator (primary input + routing log) ---------- */
function Orchestrator({ onDispatch }) {
  const [text, setText] = useAg("");
  const [routes, setRoutes] = useAg([
    { ts: "14:02:18", target: "FINANCE", desc: "Pull Q2 burn report", state: "ok" },
    { ts: "14:03:42", target: "CLIENT",  desc: "Draft renewal email · Granite Sky", state: "ok" },
    { ts: "14:11:09", target: "PROCURE", desc: "Reorder galv. screws · 12 boxes", state: "run" },
  ]);

  const samples = [
    "Karen Liu's renewal is up next month — draft a check-in.",
    "We're low on #8 stainless screws. Get me 200 boxes from McFeely's.",
    "Pull production status for the Whistler job and flag anything overdue.",
    "Who hasn't paid their May invoice yet?"
  ];

  const dispatch = async (msg) => {
    if (!msg.trim()) return;
    const ts = new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit", hour12: false });
    const desc = msg.length > 50 ? msg.slice(0, 48) + "…" : msg;
    setRoutes(r => [{ ts, target: "…", desc, state: "queued" }, ...r].slice(0, 6));
    setText("");

    try {
      setRoutes(r => r.map((row, i) => i === 0 ? { ...row, state: "run" } : row));
      const res = await fetch(window.API_BASE + "/api/agents/dispatch/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: msg }),
      });
      const data = await res.json();
      const target = window.mapAgentLabel(data.routed_to || "aris");
      setRoutes(r => r.map((row, i) => i === 0 ? { ...row, target, state: "ok" } : row));
      if (onDispatch) onDispatch(target, msg, data.response);
    } catch (e) {
      /* Fallback: keyword route client-side when backend unreachable */
      const lower = msg.toLowerCase();
      let target = "ARIS";
      if (/invoice|paid|burn|revenue|expense|q[1-4]/.test(lower)) target = "FINANCE";
      else if (/order|stock|inventory|supplier|reorder/.test(lower)) target = "PROCURE";
      else if (/job|crew|production|overdue|schedule/.test(lower)) target = "PRODUCTION";
      else if (/client|renewal|customer|email|call/.test(lower)) target = "CLIENT";
      setRoutes(r => r.map((row, i) => i === 0 ? { ...row, target, state: "ok" } : row));
      if (onDispatch) onDispatch(target, msg, null);
    }
  };

  return (
    <div className="orchestrator">
      <svg className="orch-deco" viewBox="0 0 200 200" fill="none" stroke="currentColor" strokeWidth="0.8">
        <path d="M20 160 L80 60 L120 120 L160 70" />
        <path d="M40 160 L80 100 L120 140 L150 110" strokeDasharray="2 3" />
        <path d="M0 180 Q60 170 100 175 T200 165" />
        <path d="M0 190 Q60 185 100 188 T200 178" />
        <circle cx="80" cy="60" r="2" fill="currentColor" />
        <circle cx="120" cy="120" r="2" fill="currentColor" />
        <circle cx="160" cy="70" r="2" fill="currentColor" />
      </svg>

      <div className="orch-left">
        <div className="orch-eyebrow">§ 01 / Aris · Lead Agent</div>
        <h2 className="orch-title">Type a directive. <em>I'll route it.</em></h2>

        <div className="orch-input">
          <textarea
            placeholder="e.g. 'Karen Liu's renewal is up next month — draft a check-in.'"
            value={text}
            onChange={e => setText(e.target.value)}
            onKeyDown={e => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) dispatch(text); }}
          />
          <div className="orch-input-foot">
            <span className="hint">⌘ ↵ to dispatch · Routes to specialist agent</span>
            <button className="orch-send" onClick={() => dispatch(text)}>Dispatch →</button>
          </div>
        </div>

        <div style={{display:"flex", flexDirection:"column", gap:6, marginTop:4}}>
          <div className="orch-eyebrow" style={{fontSize:9, opacity:0.7}}>OR TRY A SAMPLE</div>
          <div style={{display:"flex", flexWrap:"wrap", gap:8}}>
            {samples.map((s, i) => (
              <button
                key={i}
                onClick={() => dispatch(s)}
                style={{
                  fontFamily:"var(--font-sans)", fontSize:12,
                  background:"transparent",
                  color:"rgba(242,237,227,0.85)",
                  border:"1px dashed rgba(242,237,227,0.25)",
                  padding:"6px 10px",
                  textAlign:"left",
                  borderRadius: 2,
                  maxWidth: 320,
                }}
              >
                <span style={{fontFamily:"var(--font-mono)", fontSize:9, color:"#9CB89E", letterSpacing:"0.12em", marginRight:8}}>EX_{String(i+1).padStart(2,"0")}</span>
                {s}
              </button>
            ))}
          </div>
        </div>
      </div>

      <div className="orch-right">
        <div className="orch-right-head">
          <span>Routing · Live</span>
          <span>NODE_07</span>
        </div>
        <div style={{display:"flex", flexDirection:"column", gap:0}}>
          {routes.map((r, i) => (
            <div key={r.ts+i} className="routing-line">
              <span className="ts">{r.ts}</span>
              <span><span className="target">{r.target}</span> · {r.desc}</span>
              <span className={`badge ${r.state}`}>{r.state}</span>
            </div>
          ))}
        </div>
        <div style={{marginTop:"auto", paddingTop:12, borderTop:"1px dashed rgba(242,237,227,0.15)", display:"flex", justifyContent:"space-between", fontSize:9, letterSpacing:"0.14em", textTransform:"uppercase", color:"rgba(242,237,227,0.4)"}}>
          <span>QUEUE 03</span>
          <span>AVG 1.4s</span>
          <span>ERR 0</span>
        </div>
      </div>
    </div>
  );
}

/* ---------- Specialist Agent Card ---------- */
function AgentCard({ kind, name, role, status, currentTask, stats }) {
  return (
    <div className={`agent-card ${status === "idle" ? "idle" : ""}`}>
      <div className="agent-card-head">
        <span style={{display:"flex", alignItems:"center", gap:8}}>
          <span className={`stat-dot ${status}`} />
          {status === "active" ? "Live" : status === "busy" ? "Busy" : "Idle"} · {name.toUpperCase()}
        </span>
        <span style={{color:"#9CB89E"}}>NODE_{(0xA+name.length).toString(16).toUpperCase()}{name[0].toUpperCase()}</span>
      </div>
      <div className="agent-card-axis">
        <span>t</span>
        <span>agent_id: {kind}</span>
      </div>
      <div className="agent-card-body">
        <div style={{display:"flex", gap:14, alignItems:"flex-start"}}>
          <span className="agent-glyph"><AgentMark kind={kind} size={32} /></span>
          <div style={{display:"flex", flexDirection:"column", gap:4, flex:1}}>
            <div className="agent-name">{name.split(' ')[0]} <em>{name.split(' ').slice(1).join(' ')}</em></div>
            <div className="agent-role">{role}</div>
          </div>
        </div>

        <div className="agent-stats">
          {stats.map((s, i) => (
            <div className="agent-stat" key={i}>
              <span className="lbl">{s.lbl}</span>
              <span className="val">{s.val}</span>
            </div>
          ))}
        </div>
      </div>
      {currentTask && (
        <div className="agent-task-strip">
          <span className="arrow">▸</span>
          <span style={{flex:1}}>{currentTask}</span>
          <span style={{color:"var(--fog)"}}>2m ago</span>
        </div>
      )}
    </div>
  );
}

const SEED_LOGS = [
  { ts: "14:11", id: "TX_0214", agent: "PROCURE",    desc: "Order placed — McFeely's · 12 boxes #8 stainless · $284.40", status: "OK",     state: "ok"  },
  { ts: "14:09", id: "TX_0213", agent: "FINANCE",    desc: "May invoice reminder sent to 4 customers · 2 paid",          status: "OK",     state: "ok"  },
  { ts: "13:58", id: "TX_0212", agent: "CLIENT",     desc: "Drafted renewal email — Granite Sky Inc. · awaiting review", status: "REVIEW", state: "run" },
  { ts: "13:42", id: "TX_0211", agent: "PRODUCTION", desc: "Whistler crew flagged — Tom B. vacation conflicts with install", status: "OK", state: "ok"  },
  { ts: "13:30", id: "TX_0210", agent: "ARIS",       desc: "Daily standup synthesized · 3 follow-ups assigned",          status: "OK",     state: "ok"  },
  { ts: "13:14", id: "TX_0209", agent: "FINANCE",    desc: "Q2 burn report compiled — within budget · $42.1k of $48k",  status: "OK",     state: "ok"  },
];

function adaptLog(l) {
  const d = new Date(l.created_at);
  const ts = d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", hour12: false });
  const stateMap = { ok: "ok", run: "run", err: "err" };
  const statusMap = { ok: "OK", run: "REVIEW", err: "ERR" };
  return {
    ts,
    id:     "TX_" + String(l.id).padStart(4, "0"),
    agent:  window.mapAgentLabel(l.agent),
    desc:   l.description,
    status: statusMap[l.state] || "OK",
    state:  stateMap[l.state]  || "ok",
  };
}

/* ---------- Activity log card ---------- */
function ActivityLog() {
  const [rows, setRows] = useAg(SEED_LOGS);

  useAge(() => {
    fetch(window.API_BASE + "/api/agent-logs/")
      .then(r => r.json())
      .then(data => {
        if (Array.isArray(data) && data.length > 0) {
          setRows(data.slice(0, 12).map(adaptLog));
        }
      })
      .catch(() => {/* keep seed logs */});
  }, []);
  return (
    <div className="card log-card">
      <div className="card-head">
        <span className="title"><span className="num">§ 04 /</span>TRANSMISSION LOG</span>
        <span className="meta">LAST 24H · 27 EVENTS</span>
      </div>
      <div className="card-body" style={{padding: "8px 22px 18px"}}>
        <div className="log-row" style={{borderBottom:"1px solid var(--rule)", paddingBottom:8}}>
          <span style={{fontFamily:"var(--font-mono)",fontSize:9,letterSpacing:"0.14em",color:"var(--fog)",textTransform:"uppercase"}}>TIME</span>
          <span style={{fontFamily:"var(--font-mono)",fontSize:9,letterSpacing:"0.14em",color:"var(--fog)",textTransform:"uppercase"}}>ID</span>
          <span style={{fontFamily:"var(--font-mono)",fontSize:9,letterSpacing:"0.14em",color:"var(--fog)",textTransform:"uppercase"}}>AGENT</span>
          <span style={{fontFamily:"var(--font-mono)",fontSize:9,letterSpacing:"0.14em",color:"var(--fog)",textTransform:"uppercase"}}>EVENT</span>
          <span style={{fontFamily:"var(--font-mono)",fontSize:9,letterSpacing:"0.14em",color:"var(--fog)",textTransform:"uppercase",textAlign:"right"}}>STATUS</span>
        </div>
        {rows.map((r, i) => (
          <div className="log-row" key={i}>
            <span className="ts">{r.ts}</span>
            <span className="id">{r.id}</span>
            <span className="agent">{r.agent}</span>
            <span className="desc">{r.desc}</span>
            <span className={`status ${r.state}`}>{r.status}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Agents Hub view ---------- */
function AgentsHub() {
  return (
    <>
      <div className="page-head">
        <div className="meta">
          <span className="coord">§ 01 / AGENTS HUB</span>
          <span className="coord" style={{opacity:0.6}}>FIG_001 · ORCHESTRATION</span>
        </div>
        <h1>Your <em>operations crew</em>, on standby.</h1>
        <div className="actions">
          <button className="btn-sm">+ New agent</button>
          <button className="btn-sm solid">Configure routing</button>
        </div>
      </div>

      <Orchestrator />

      <div style={{margin:"40px 0 16px", display:"flex", justifyContent:"space-between", alignItems:"baseline", borderBottom:"1px dashed var(--rule)", paddingBottom:12}}>
        <div>
          <span className="coord">§ 02 / SPECIALISTS</span>
          <h3 style={{margin:"6px 0 0", fontFamily:"var(--font-serif)", fontSize:24, fontWeight:400, letterSpacing:"-0.01em"}}>
            Four agents, each owning a <em style={{fontStyle:"italic", color:"var(--accent)", fontWeight:300}}>function</em>.
          </h3>
        </div>
        <span className="coord" style={{opacity:0.6}}>4 of 4 online</span>
      </div>

      <div className="specialists-grid">
        <AgentCard
          kind="procurement"
          name="Procurement Agent"
          role="Watches inventory, drafts purchase orders, talks to suppliers."
          status="active"
          currentTask="Reordering #8 stainless screws · McFeely's"
          stats={[
            { lbl: "POs/wk", val: "12" },
            { lbl: "Saved", val: "$1.4k" },
            { lbl: "SLA", val: "98%" },
          ]}
        />
        <AgentCard
          kind="finance"
          name="Finance Agent"
          role="Reconciles invoices, tracks burn, chases late payments."
          status="busy"
          currentTask="Compiling Q2 burn report · 88%"
          stats={[
            { lbl: "AR open", val: "$18k" },
            { lbl: "DSO", val: "27d" },
            { lbl: "Coll.", val: "92%" },
          ]}
        />
        <AgentCard
          kind="production"
          name="Production Agent"
          role="Schedules crews, tracks job status, surfaces bottlenecks."
          status="active"
          currentTask="Watching Whistler install · on track"
          stats={[
            { lbl: "Jobs", val: "8" },
            { lbl: "On time", val: "94%" },
            { lbl: "Crews", val: "3" },
          ]}
        />
        <AgentCard
          kind="client"
          name="Client Agent"
          role="Drafts emails, runs renewals, handles intake from the website."
          status="idle"
          currentTask="Awaiting input"
          stats={[
            { lbl: "Open", val: "24" },
            { lbl: "Resp.", val: "8m" },
            { lbl: "NPS", val: "62" },
          ]}
        />
      </div>

      <ActivityLog />

      <div style={{height: 40}} />
    </>
  );
}

Object.assign(window, { AgentMark, Orchestrator, AgentCard, ActivityLog, AgentsHub });
