// Root: state, chat (window.claude.complete + fallback), report data, cohort email capture, mount.
function App() {
  const d = window.SANDY;
  const [avatar, setAvatar] = useState(2);
  const [pickerOpen, setPickerOpen] = useState(false);
  const [copied, setCopied] = useState(false);
  const [linkSent, setLinkSent] = useState(false);
  const [reportOpen, setReportOpen] = useState(false);
  const [voiceOpen, setVoiceOpen] = useState(false);
  const [cohortEmail, setCohortEmail] = useState("");
  const [cohortSent, setCohortSent] = useState("");
  const [cohortErr, setCohortErr] = useState("");
  const [tab, setTab] = useState("chat");
  const [messages, setMessages] = useState([{ from: "pod", text: window.SANDY_CHAT.seed }]);
  const [typing, setTyping] = useState(false);
  const [draft, setDraft] = useState("");
  const [posts, setPosts] = useState(window.SANDY_POSTS.map((p) => ({ ...p })));
  const [feedDraft, setFeedDraft] = useState("");
  const threadEl = useRef(null);
  const turn = useRef(0);
  const timers = useRef([]);

  useEffect(() => () => timers.current.forEach(clearTimeout), []);
  useEffect(() => { const el = threadEl.current; if (el) requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; }); }, [messages, typing, tab]);
  useEffect(() => { document.body.style.overflow = reportOpen ? "hidden" : ""; return () => { document.body.style.overflow = ""; }; }, [reportOpen]);

  const claudeUrl = "https://claude.ai/new?q=" + encodeURIComponent("Tell me about the ActionBoard CEO profile for " + d.name + " (" + d.mcpUri + ") and help me draft an AI leadership brief.");

  const cannedReply = () => { const r = window.SANDY_CHAT.replies; const i = Math.min(turn.current, r.length - 1); turn.current++; return r[i]; };

  const respond = useCallback(async (history) => {
    setTyping(true);
    const finish = (text) => { setTyping(false); setMessages((m) => [...m, { from: "pod", text }]); };
    if (window.claude && typeof window.claude.complete === "function") {
      const convo = history.map((m) => (m.from === "you" ? "User: " : "Assistant: ") + m.text).join("\n");
      const prompt = "You are Sandy Carter's Agentic Leadership Assistant on her ActionBoard CEO profile. Sandy is CEO of Equs.AI (privacy-first trust layer for the agentic era), a Forbes AI Senior Contributor, former VP at AWS and 14-year IBM executive, and founder of Unstoppable Women of AI & Blockchain. She runs the Agentic CEO Cohort — a 90-day peer program built on the Agentic Leadership Index (7 ranks, Curious→Category-Defining) scored across AI strategy, agent trust & governance, go-to-market, org & talent, and responsible-AI culture. Reply in 2-4 sentences, practical and warm, in Sandy's customer-obsessed, privacy-first voice. Map the user's situation to a leadership level and a concrete next step; offer to loop in Sandy for the cohort when relevant. Do not use markdown headings.\n\n" + convo + "\nAssistant:";
      try {
        const out = await window.claude.complete(prompt);
        finish((out || "").trim() || cannedReply());
      } catch (e) { const t = setTimeout(() => finish(cannedReply()), 400); timers.current.push(t); }
    } else {
      const t = setTimeout(() => finish(cannedReply()), 1200); timers.current.push(t);
    }
  }, [d]);

  const sendText = useCallback((text) => {
    const t = (text || "").trim(); if (!t) return;
    setMessages((m) => { const next = [...m, { from: "you", text: t }]; respond(next); return next; });
    setDraft("");
  }, [respond]);

  const postFeedNow = () => {
    const txt = (feedDraft || "").trim(); if (!txt) return;
    setPosts((s) => [{ author: "Sandy Carter", handle: "@sandyacarter · CEO, Equs.AI", init: "SC", bg: "linear-gradient(135deg,#5B21B6,#7C3AED)", time: "now", text: txt, tag: "Cohort", likes: 0, comments: 0, liked: false }, ...s]);
    setFeedDraft("");
  };

  const copyMcp = () => { if (navigator.clipboard) navigator.clipboard.writeText(d.mcpUri).catch(() => {}); setCopied(true); const t = setTimeout(() => setCopied(false), 2000); timers.current.push(t); };
  const sendLink = () => { setLinkSent(true); const t = setTimeout(() => setLinkSent(false), 2600); timers.current.push(t); };

  const submitCohort = (e) => {
    e.preventDefault();
    const v = (cohortEmail || "").trim();
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v)) { setCohortErr("Please enter a valid email address."); return; }
    setCohortErr(""); setCohortSent(v);
  };

  const avatars = window.SANDY_AVATARS.map((a, i) => ({ ...a, active: i === avatar, pick: () => { setAvatar(i); setPickerOpen(false); } }));

  const report = (() => {
    const m = window.SANDY_MATURITY;
    const nums = m.dims.map((x) => parseFloat(x.score) || 0);
    const overall = (nums.reduce((a, b) => a + b, 0) / nums.length).toFixed(1);
    const tierOf = (p) => p >= 90 ? { t: "Leading", c: "#34D399" } : p >= 80 ? { t: "Strong", c: "#a78bfa" } : p >= 70 ? { t: "Developing", c: "#F5B301" } : { t: "Emerging", c: "#8B7FB0" };
    const dims = m.dims.map((x) => { const tc = tierOf(x.pct); return { name: x.name, score: x.score, pctStr: x.pct + "%", tier: tc.t, tierColor: tc.c }; });
    const xpPct = (() => { const n = parseFloat(String(m.xpNow).replace(/[^0-9.]/g, "")) || 0; const mx = parseFloat(String(m.xpMax).replace(/[^0-9.]/g, "")) || 1; return Math.round((n / mx) * 100) + "%"; })();
    const ranks = window.SANDY_RANK_NAMES.map((label, i) => { const n = i + 1; const state = n < m.level ? "done" : (n === m.level ? "current" : "locked"); return { n: "L" + n, label, state, stateText: state === "done" ? "Achieved" : (state === "current" ? "Current" : "Locked") }; });
    return { name: d.name, level: m.level, rankLabel: m.rankLabel, nextRank: m.nextRank, xpNow: m.xpNow, xpMax: m.xpMax, xpPct, overall, dims, ranks };
  })();

  return (
    <>
      <BloomBackground />
      <div className="page">
        <Hero d={d} avatars={avatars} selAvatar={window.SANDY_AVATARS[avatar]} pickerOpen={pickerOpen} togglePicker={() => setPickerOpen((v) => !v)}
          copyLabel={copied ? "Copied ✓" : "Copy link"} copyMcp={copyMcp}
          sendLabel={linkSent ? "Link sent ✓" : "Send link to me"} sendLink={sendLink} claudeUrl={claudeUrl} openVoice={() => setVoiceOpen(true)} />
        <main>
          <VerificationBand items={window.SANDY_CREDENTIALS} />
          <Framework m={window.SANDY_MATURITY} onOpenReport={() => setReportOpen(true)} />
          <Cohort c={window.SANDY_COHORT} />
          <Collaborate email={cohortEmail} setEmail={(v) => { setCohortEmail(v); if (cohortErr) setCohortErr(""); }} sent={cohortSent} error={cohortErr} onSubmit={submitCohort} />
          <ActionChat assistantName={window.SANDY_CHAT.assistantName} tab={tab} showChat={() => setTab("chat")} showFeed={() => setTab("feed")}
            messages={messages} typing={typing} threadRef={threadEl} draft={draft} setDraft={(e) => setDraft(e.target.value)}
            onKey={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendText(draft); } }} send={() => sendText(draft)}
            suggestions={window.SANDY_CHAT.suggestions} onPick={(s) => sendText(s)}
            posts={posts} onLike={(i) => setPosts((s) => s.map((q, j) => j === i ? { ...q, liked: !q.liked } : q))}
            feedDraft={feedDraft} setFeedDraft={(e) => setFeedDraft(e.target.value)} onFeedKey={(e) => { if (e.key === "Enter") { e.preventDefault(); postFeedNow(); } }} postFeed={postFeedNow} />
          <Journal />
        </main>
        <Footer />
      </div>
      {reportOpen && <ReportModal report={report} onClose={() => setReportOpen(false)} />}
      <VoiceNoteModal open={voiceOpen} onClose={() => setVoiceOpen(false)} onSent={() => {}} sandy={d} />
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
