// Root: state, chat (window.claude.complete + fallback), report data, mount.
function App() {
  const d = window.SME;
  const [avatar, setAvatar] = useState(0);
  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 [joinRequested, setJoinRequested] = useState(false);
  const [tab, setTab] = useState("chat");
  const [messages, setMessages] = useState([{ from: "pod", text: window.SME_CHAT.seed }]);
  const [typing, setTyping] = useState(false);
  const [draft, setDraft] = useState("");
  const [posts, setPosts] = useState(window.SME_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 SME profile for " + d.name + " (" + d.mcpUri + ") and help me draft an action briefing.");

  const cannedReply = () => { const r = window.SME_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 persona = d.assistantPrompt || "You are the ActionBoard AIOps Assistant on Jarjis Imam's SME profile. Jarjis is a Chief AIOps Architect and creator of the AIOps Maturity framework (7 ranks, Reactive→Autonomous) and the 90-Day AIOps Challenge, built on the RAOARA loop (Recognize, Acquire, Organize, Apply, Review, Amplify). Reply in 2-4 sentences, practical and warm. Map the user's problem to a maturity level and a concrete next step; offer to loop in Jarjis for the cohort when relevant. Do not use markdown headings.";
      const prompt = persona + "\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;
    const fa = d.feedAuthor || { author: "Jarjis Imam", handle: "@jarjis · AIOps Architect", init: "JI", bg: "linear-gradient(135deg,#5B21B6,#7C3AED)", tag: "Field notes" };
    setPosts((s) => [{ author: fa.author, handle: fa.handle, init: fa.init, bg: fa.bg, time: "now", text: txt, tag: fa.tag, 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 avatars = window.SME_AVATARS.map((a, i) => ({ ...a, active: i === avatar, pick: () => { setAvatar(i); setPickerOpen(false); } }));

  const report = (() => {
    const m = window.SME_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.SME_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") }; });
    const programName = d.programName || "90-Day AIOps Challenge";
    const recommend = d.reportRecommend || ("Enroll in the " + programName + " to advance from " + m.rankLabel + " toward " + m.nextRank + " — Recognize, Acquire, Organize, Apply, Review, Amplify.");
    return { name: d.name, level: m.level, rankLabel: m.rankLabel, nextRank: m.nextRank, xpNow: m.xpNow, xpMax: m.xpMax, xpPct, overall, dims, ranks, programName, recommend };
  })();

  return (
    <>
      <BloomBackground />
      <div className="page">
        <Hero d={d} avatars={avatars} selAvatar={window.SME_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.SME_CREDENTIALS} />
          <Framework m={window.SME_MATURITY} fw={d.framework} onOpenReport={() => setReportOpen(true)} />
          <Cohort c={window.SME_COHORT} />
          <Collaborate joinRequested={joinRequested} onRequestJoin={() => setJoinRequested(true)} collab={d.collab} />
          <ActionChat assistantName={window.SME_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.SME_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={() => {}} host={d} />
    </>
  );
}

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