/* Calibrated Ascension HQ — center views. Exports to window. */
const { useState: useStateV, useRef: useRefV, useEffect: useEffectV } = React;

function SectionHead({ title, n }) {
  return (
    <div className="section-head">
      <h2>{title}</h2>
      {n != null && <span className="n">{n}</span>}
      <span className="rule"></span>
    </div>
  );
}

function agentById(data, id) { return data.AGENTS.find((a) => a.id === id); }

/* ---------- TODAY / EOD brief ---------- */
function TodayView({ data, ctx, decisions, onDecide, agentObj, dateStr, client, projects, onCapture, onSend, sentDeliv, projStatus, onStatus, onWorkflow, projPM, onAssignPM, approvals, onResolveApproval, onboarding, onMarkOnboarding }) {
  const m = ctx.metrics;
  const none = decisions.length === 0;
  const [showDone, setShowDone] = useStateV(false);
  const eff = (p) => projStatus[p.id] || p.status || "active";
  const norm = (p) => { const s = eff(p); return s === "fresh" ? "active" : s; };
  const pmOf = (p) => (projPM && projPM[p.id]) || p.pm || "atlas";
  const agentById2 = (id) => data.AGENTS.find((a) => a.id === id) || data.AGENTS[0];
  const openProjects = projects.filter((p) => eff(p) !== "done");
  const doneProjects = projects.filter((p) => eff(p) === "done");
  const boardCols = [
    { k: "active", label: "Active", tone: "active" },
    { k: "blocked", label: "Blocked", tone: "blocked" },
    { k: "done", label: "Done", tone: "done" },
  ];
  return (
    <div className="center-pad fade">
      <div className="topline">
        <span className="kicker">{client.agency ? "End-of-day brief" : client.name + " · brief"}</span>
        <span className="date-pill">{dateStr}</span>
      </div>
      {none
        ? <h1 className="headline">You're <em>all caught up</em>. What's next?</h1>
        : <h1 className="headline">Everything's running. <em>{decisions.length} thing{decisions.length === 1 ? "" : "s"}</em> want{decisions.length === 1 ? "s" : ""} your eyes.</h1>}
      <p className="sub-intro">{ctx.greeting}{client.agency ? " Anubis and Sage synced the team at 5:00pm." : ""} Capture a goal below and the right agents pick it up.</p>

      <ApprovalsTriage approvals={approvals} client={client} data={data} onResolve={onResolveApproval} />

      <OnMind client={client} onCapture={onCapture} />

      {projects.length > 0 && (
        <React.Fragment>
          <SectionHead title="Project pipeline" n={`${projects.length} total`} />
          <div className="board">
            {boardCols.map((col) => {
              const items = projects.filter((p) => norm(p) === col.k);
              return (
                <div key={col.k} className={`board-col ${col.tone}`} data-bottleneck={col.k === "blocked" && items.length > 0 ? "1" : null}>
                  <div className="board-head">
                    <span className="board-dot"></span>{col.label}
                    <span className="board-n">{items.length}</span>
                  </div>
                  <div className="board-cards">
                    {items.length === 0 && <div className="board-empty">—</div>}
                    {items.map((p) => {
                      const pmA = agentById2(pmOf(p));
                      const needs = (p.deliverables || []).some((d) => !sentDeliv.includes(d.id));
                      return (
                        <div key={p.id} className="mini" onClick={() => onStatus(p.id, eff(p))}>
                          <div className="mini-title">{p.title}</div>
                          <div className="mini-foot">
                            <Avatar agent={pmA} size="sm" />
                            <span className="mini-pm">{pmA.name}</span>
                            {needs && <span className="mini-flag" title="A deliverable is waiting">{I.send}</span>}
                            <span className="mini-upd">{p.updated || "—"}</span>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>
        </React.Fragment>
      )}

      {openProjects.length > 0 && (
        <React.Fragment>
          <SectionHead title="Active projects" n={`${openProjects.length}`} />
          <div className="plan-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)" }}>
            {openProjects.map((p) => <ProjectCard key={p.id} project={p} status={eff(p)} sent={sentDeliv} onSend={onSend} onStatus={onStatus} agents={data.AGENTS} pm={pmOf(p)} onAssignPM={onAssignPM} approvals={(approvals || []).filter((a) => a.project_id === p.id)} onResolveApproval={onResolveApproval} onboarding={(onboarding || []).filter((t) => t.project_id === p.id)} onMarkOnboarding={onMarkOnboarding} />)}
          </div>
        </React.Fragment>
      )}
      {doneProjects.length > 0 && (
        <React.Fragment>
          <button className="done-toggle" onClick={() => setShowDone((s) => !s)}>
            <span className="chev" style={{ transform: showDone ? "none" : "rotate(-90deg)" }}>{I.chevron}</span>
            Completed <span className="n">{doneProjects.length}</span>
          </button>
          {showDone && (
            <div className="plan-grid" style={{ gridTemplateColumns: "repeat(2, 1fr)" }}>
              {doneProjects.map((p) => <ProjectCard key={p.id} project={p} status={eff(p)} sent={sentDeliv} onSend={onSend} onStatus={onStatus} agents={data.AGENTS} pm={pmOf(p)} onAssignPM={onAssignPM} approvals={(approvals || []).filter((a) => a.project_id === p.id)} onResolveApproval={onResolveApproval} onboarding={(onboarding || []).filter((t) => t.project_id === p.id)} onMarkOnboarding={onMarkOnboarding} />)}
            </div>
          )}
        </React.Fragment>
      )}

      <div className="metrics">
        {data.PILLARS.map((p) => {
          const d = m[p.id];
          return (
            <div className="metric" key={p.id}>
              <div className="mp">{p.label}</div>
              <div className="mv">{d.value}</div>
              <div className="ml">{d.label}</div>
              <div className={`md ${d.up ? "up" : "down"}`}>{d.up ? "▲" : "▼"} {d.delta}</div>
            </div>
          );
        })}
      </div>

      <SectionHead title="Decisions that need you" n={`${decisions.length} open`} />
      <div className="deck">
        {decisions.length === 0 && <div className="empty">All clear — nothing is blocked on you right now.</div>}
        {decisions.map((d) => {
          const ag = agentById(data, d.agent);
          return (
            <div key={d.id} className="card decision" data-urg={d.urgency}>
              <Avatar agent={ag} size="md" />
              <div className="body">
                <div className="dt">{d.title}</div>
                <div className="dd">{d.detail}</div>
                <div className="dmeta">
                  <span className="chip">{d.tag}</span>
                  <span className="byline">from {ag.name} · {ag.role}</span>
                </div>
                <div className="actions">
                  <button className="btn btn-primary btn-sm" onClick={() => onDecide(d.id, "approve")}>{I.check} Approve</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => onDecide(d.id, "decline")}>Not now</button>
                  <button className="btn btn-ghost btn-sm" onClick={() => onWorkflow(d)}>{I.flow} Workflow</button>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      <SectionHead title="Tomorrow's plan" n="by pillar" />
      <div className="plan-grid">
        {data.PILLARS.map((p) => (
          <div className="plan" key={p.id}>
            <div className="plan-h">
              <span className={`pill-dot ${p.id}`}></span>
              <span className="ph">{p.label}</span>
              <span className="pb">{ctx.tomorrow[p.id].length} moves</span>
            </div>
            <ul>{ctx.tomorrow[p.id].map((t, i) => <li key={i}>{t}</li>)}</ul>
          </div>
        ))}
      </div>

      <SectionHead title="Risks & things that broke" n={`${ctx.risks.length}`} />
      <div className="deck">
        {ctx.risks.map((r) => (
          <div key={r.id} className="card risk" data-lvl={r.level}>
            <div className="risk-ico">{I.warn}</div>
            <div>
              <div className="rt">{r.title}</div>
              <div className="rd">{r.detail}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- LIVE AGENT CENTER — Tree of Life ---------- */
const SEPHIROT = [
  { key: "keter",   agent: "atlas", title: "Keter",   sub: "Crown",         x: 300, y: 60 },
  { key: "chokmah", agent: "vera",  title: "Chokmah", sub: "Wisdom",        x: 476, y: 156 },
  { key: "binah",   agent: "margo", title: "Binah",   sub: "Understanding", x: 124, y: 156 },
  { key: "chesed",  agent: "ravi",  title: "Chesed",  sub: "Mercy",         x: 476, y: 314 },
  { key: "gevurah", agent: "quinn", title: "Gevurah", sub: "Strength",      x: 124, y: 314 },
  { key: "tiferet", agent: "juno",  title: "Tiferet", sub: "Beauty",        x: 300, y: 394 },
  { key: "netzach", agent: "max",   title: "Netzach", sub: "Victory",       x: 476, y: 502 },
  { key: "hod",     agent: "sage",  title: "Hod",     sub: "Splendor",      x: 124, y: 502 },
  { key: "yesod",   agent: "cole",  title: "Yesod",   sub: "Foundation",    x: 300, y: 588 },
  { key: "malkuth", agent: "soham", title: "Malkuth", sub: "Kingdom",       x: 300, y: 716 },
];
const TREE_PATHS = [
  ["keter", "chokmah"], ["keter", "binah"], ["keter", "tiferet"],
  ["chokmah", "binah"], ["chokmah", "tiferet"], ["chokmah", "chesed"],
  ["binah", "tiferet"], ["binah", "gevurah"],
  ["chesed", "gevurah"], ["chesed", "tiferet"], ["chesed", "netzach"],
  ["gevurah", "tiferet"], ["gevurah", "hod"],
  ["tiferet", "netzach"], ["tiferet", "hod"], ["tiferet", "yesod"],
  ["netzach", "hod"], ["netzach", "yesod"], ["netzach", "malkuth"],
  ["hod", "yesod"], ["hod", "malkuth"],
  ["yesod", "malkuth"],
];
const TREE_VW = 600, TREE_VH = 776;

/* adjacency + helpers for routing/lighting */
const TREE_ADJ = {};
SEPHIROT.forEach((s) => { TREE_ADJ[s.key] = []; });
TREE_PATHS.forEach(([a, b]) => { TREE_ADJ[a].push(b); TREE_ADJ[b].push(a); });
function treeEdgeIdx(a, b) { return TREE_PATHS.findIndex(([x, y]) => (x === a && y === b) || (x === b && y === a)); }
function treeBfs(start, goal) {
  if (start === goal) return [start];
  const q = [[start]]; const seen = new Set([start]);
  while (q.length) {
    const path = q.shift(); const last = path[path.length - 1];
    for (const k of TREE_ADJ[last]) {
      if (seen.has(k)) continue;
      const np = [...path, k];
      if (k === goal) return np;
      seen.add(k); q.push(np);
    }
  }
  return [start, goal];
}

function TreeOfLife({ data, onChat }) {
  const get = (id) => data.AGENTS.find((a) => a.id === id);
  const pos = {}; SEPHIROT.forEach((s) => { pos[s.key] = s; });
  const [hover, setHover] = useStateV(null);
  const [flowEdges, setFlowEdges] = useStateV([]);
  const [pulse, setPulse] = useStateV(null);
  const animRef = useRefV(null);
  const fadeRef = useRefV(null);
  const ambientRef = useRefV(null);
  const runningRef = useRefV(false);

  function runFlow(target) {
    if (target === "keter") target = "malkuth"; // tapping the crown flows to the base
    clearInterval(animRef.current); clearTimeout(fadeRef.current);
    const route = treeBfs("keter", target);
    const idxs = [];
    for (let i = 0; i < route.length - 1; i++) { const e = treeEdgeIdx(route[i], route[i + 1]); if (e >= 0) idxs.push(e); }
    setFlowEdges(idxs);
    const pts = route.map((k) => pos[k]);
    const segLen = []; let total = 0;
    for (let i = 0; i < pts.length - 1; i++) { const d = Math.hypot(pts[i + 1].x - pts[i].x, pts[i + 1].y - pts[i].y); segLen.push(d); total += d; }
    const dur = Math.max(650, total * 1.5);
    runningRef.current = true;
    let elapsed = 0;
    animRef.current = setInterval(() => {
      elapsed += 24; const t = Math.min(1, elapsed / dur);
      let d = t * total, i = 0;
      while (i < segLen.length && d > segLen[i]) { d -= segLen[i]; i++; }
      if (i >= segLen.length) i = segLen.length - 1;
      const A = pts[i], B = pts[i + 1] || pts[i]; const f = segLen[i] ? d / segLen[i] : 1;
      setPulse({ x: A.x + (B.x - A.x) * f, y: A.y + (B.y - A.y) * f });
      if (t >= 1) {
        clearInterval(animRef.current); runningRef.current = false; setPulse(null);
        fadeRef.current = setTimeout(() => setFlowEdges([]), 700);
      }
    }, 24);
  }

  useEffectV(() => {
    const targets = ["tiferet", "yesod", "malkuth", "netzach", "hod", "chesed", "gevurah", "binah"];
    ambientRef.current = setInterval(() => {
      if (runningRef.current) return;
      runFlow(targets[Math.floor(Math.random() * targets.length)]);
    }, 3400);
    return () => { clearInterval(ambientRef.current); clearInterval(animRef.current); clearTimeout(fadeRef.current); };
  }, []);

  const neighbors = hover ? new Set([hover, ...TREE_ADJ[hover]]) : null;

  return (
    <div className="tree-wrap" data-hover={hover ? "1" : null}>
      <svg className="tree-svg" viewBox={`0 0 ${TREE_VW} ${TREE_VH}`} preserveAspectRatio="none" aria-hidden="true">
        {TREE_PATHS.map(([a, b], i) => {
          const A = pos[a], B = pos[b];
          const lit = flowEdges.includes(i) || (hover && (a === hover || b === hover));
          return <line key={i} x1={A.x} y1={A.y} x2={B.x} y2={B.y} className={`tree-path ${lit ? "lit" : ""}`} />;
        })}
        {pulse && (
          <g>
            <circle className="tree-pulse-outer" cx={pulse.x} cy={pulse.y} r="11" />
            <circle className="tree-pulse-inner" cx={pulse.x} cy={pulse.y} r="4.5" />
          </g>
        )}
      </svg>
      {SEPHIROT.map((s) => {
        const a = get(s.agent); if (!a) return null;
        const cls = `tree-node ${a.lead ? "lead" : ""} ${neighbors ? (neighbors.has(s.key) ? "near" : "dim") : ""}`;
        return (
          <button key={s.key} className={cls}
            style={{ left: `${(s.x / TREE_VW) * 100}%`, top: `${(s.y / TREE_VH) * 100}%` }}
            onMouseEnter={() => setHover(s.key)} onMouseLeave={() => setHover(null)}
            onClick={() => { runFlow(s.key); onChat(a); }} title={`${a.name} · ${a.role} — tap to chat`}>
            <span className="tn-seph">{s.title}</span>
            <span className="tn-orb"><Avatar agent={a} size="lg" /></span>
            <span className="tn-labels">
              <span className="tn-name">{a.name}</span>
              <span className="tn-role">{a.role}</span>
            </span>
          </button>
        );
      })}
    </div>
  );
}

function AgentsView({ data, onAgent, onChat }) {
  return (
    <div className="center-pad fade">
      <div className="topline"><span className="kicker">Live agent center</span><span className="date-pill">{data.AGENTS.length} agents online</span></div>
      <h1 className="headline">How the team <em>connects</em>.</h1>
      <p className="sub-intro">Anubis crowns the tree as your master brain, with Sage beside him. Strategy flows down the pillars — through the specialists — and manifests at the base, where Soham ships it. Tap any node to chat; in most cases they resolve through Anubis &amp; Sage, then escalate to you.</p>

      <TreeOfLife data={data} onChat={onChat} />

      <div className="tree-legend">
        <span><span className="lg-dot lead"></span> Leads — Anubis &amp; Sage</span>
        <span><span className="lg-dot"></span> Specialists</span>
        <span className="lg-pillars">Mercy · Balance · Severity</span>
      </div>
    </div>
  );
}

/* ---------- PILLAR DETAIL (offers / automation / traffic) ---------- */
function PillarView({ data, ctx, pillar, onAgent }) {
  const p = data.PILLARS.find((x) => x.id === pillar);
  const d = ctx.metrics[pillar];
  const agents = data.AGENTS.filter((a) => a.pillar === pillar);
  return (
    <div className="center-pad fade">
      <div className="topline"><span className="kicker">{p.label} pillar</span></div>
      <h1 className="headline" style={{ textTransform: "capitalize" }}>{p.label}.</h1>
      <p className="sub-intro" style={{ textTransform: "capitalize" }}>{p.blurb}.</p>

      <div className="metrics" style={{ gridTemplateColumns: "1fr" }}>
        <div className="metric">
          <div className="mp">{d.label}</div>
          <div className="mv">{d.value}</div>
          <div className={`md ${d.up ? "up" : "down"}`}>{d.up ? "▲" : "▼"} {d.delta} · {d.sub}</div>
        </div>
      </div>

      <SectionHead title="Working this pillar" n={`${agents.length}`} />
      <div className="agent-grid">
        {agents.map((a) => (
          <button key={a.id} className="card agent-card" style={{ textAlign: "left" }} onClick={() => onAgent(a)}>
            <div className="agent-card-h">
              <Avatar agent={a} size="md" />
              <div style={{ flex: 1 }}>
                <div className="nm2">{a.name}</div>
                <div className="rl2">{a.role}</div>
              </div>
              <span className={`status-tag ${a.status}`}>{a.status.replace("-", " ")}</span>
            </div>
            <div className="agent-now"><b>Now ·</b> {a.now}</div>
          </button>
        ))}
      </div>

      <SectionHead title="Tomorrow's moves" n={`${ctx.tomorrow[pillar].length}`} />
      <div className="plan" style={{ maxWidth: "100%" }}>
        <ul>{ctx.tomorrow[pillar].map((t, i) => <li key={i}>{t}</li>)}</ul>
      </div>
    </div>
  );
}

/* ---------- AUTOMATIONS LIST ---------- */
function AutomationsView({ data }) {
  const statusMap = {
    running: { c: "running", t: "running" },
    ready: { c: "waiting", t: "ready" },
    attention: { c: "needs-you", t: "attention" },
  };
  return (
    <div className="center-pad fade">
      <div className="topline"><span className="kicker">Automations</span></div>
      <h1 className="headline">Work that runs <em>without you</em>.</h1>
      <p className="sub-intro">Recurring loops across your agency and client GoHighLevel accounts. The community-call workflow is loaded in the panel on the right — hit Run to watch it go.</p>
      <SectionHead title="All automations" n={`${data.AUTOMATIONS_LIST.length}`} />
      <div className="deck">
        {data.AUTOMATIONS_LIST.map((a) => {
          const ow = agentById(data, a.owner);
          const s = statusMap[a.status];
          return (
            <div key={a.id} className="card auto-row">
              <div className="ar-ico">{I.auto}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="ar-name">{a.name}</div>
                <div className="ar-note">{a.note} · {ow.name}</div>
              </div>
              <div className="ar-meta">
                <span className={`status-tag ${s.c}`}>{s.t}</span>
                <div className="ar-runs">{a.cadence} · {a.runs} runs</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ---------- APPROVALS — where work waits for a human ---------- */
function ApprovalsView({ data, client, approvals, onResolveApproval }) {
  const scoped = apprScoped(approvals, client);
  const open = scoped.filter(apprIsOpen);
  const done = scoped.filter((a) => !apprIsOpen(a));
  const showClient = !!(client && client.agency);
  return (
    <div className="center-pad fade">
      <div className="topline"><span className="kicker">Approvals · {client.name}</span></div>
      <h1 className="headline">Where work <em>waits</em> for a human.</h1>
      <p className="sub-intro">Everything blocked on a decision or an asset — grouped by who needs to act. Resolve it here and the team keeps moving. Nothing is deleted; closed items stay below as the record.</p>

      <ApprovalsTriage approvals={approvals} client={client} data={data} onResolve={onResolveApproval} />
      {open.length === 0 && <div className="empty">Inbox zero. Nothing is blocked right now. 🎉</div>}

      <SectionHead title="Resolved" n={`${done.length} logged`} />
      <div className="deck">
        {done.length === 0 && <div className="empty" style={{ padding: "24px" }}>Approved & resolved items will stay here as your record.</div>}
        {done.map((a) => (
          <div key={a.id} className="card log-row" style={{ cursor: "default" }}>
            <span className={`appr-prio ${a.priority}`} style={{ marginLeft: 4 }}></span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="log-title">{a.title}</div>
              <div className="log-meta">{APPR_TYPE_LABEL[a.type] || a.type}{showClient && a.account_name ? ` · ${a.account_name}` : ""}{a.project_title ? ` · ${a.project_title}` : ""}</div>
            </div>
            <span className={`log-status ${a.status === "declined" ? "declined" : "approved"}`}>{APPR_STATUS_LABEL[a.status] || a.status}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { TodayView, AgentsView, PillarView, AutomationsView, ApprovalsView, SectionHead });
