/* ============================================================
   MTOPS Academy — main application
   ============================================================ */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

const DATA = window.ACADEMY;
/* Display order — "approach" (the positioning / conversion pitch) moved to the end.
   Module numbers derive from position so everything stays consistent. */
const ORDER = ["mindset", "gann", "execution", "cycles", "risk", "institutional", "tools", "approach", "course"];
const MODULES = ORDER.map((id) => DATA.modules.find((m) => m.id === id)).filter(Boolean);
DATA.modules.forEach((m) => { if (!ORDER.includes(m.id)) MODULES.push(m); });
MODULES.forEach((m, i) => { m.n = String(i + 1).padStart(2, "0"); });

const topicId = (m, gi, ti) => `${m}.${gi}.${ti}`;
const moduleTopicIds = (mod) => mod.groups.flatMap((g, gi) => g.topics.map((_, ti) => topicId(mod.id, gi, ti)));
const ALL_TOPIC_IDS = MODULES.flatMap(moduleTopicIds);
const moduleAccent = (mod) => mod.accent || "mint";

/* ============ Top bar ============ */
function TopBar({ progress, onHome, onSearch, layout, setLayout, light, setLight, view }) {
  const done = ALL_TOPIC_IDS.filter((id) => progress[id]).length;
  const pct = done / ALL_TOPIC_IDS.length;
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 40, background: "color-mix(in srgb, var(--bg) 86%, transparent)",
      backdropFilter: "blur(14px)", borderBottom: "1px solid var(--line)" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "12px 24px", display: "flex", alignItems: "center", gap: 18 }}>
        <button onClick={onHome} className="disp" style={{ display: "flex", alignItems: "center", gap: 10, background: "none", border: "none", cursor: "pointer", padding: 0, color: "var(--tx)" }}>
          <img src="/mtops-logo.svg" width="22" height="22" alt="MTOPS AI" style={{ display: "block", borderRadius: 5 }} />
          <span style={{ fontWeight: 600, fontSize: 16, letterSpacing: "-0.01em" }}>MTOPS<span style={{ color: "var(--tx-4)" }}>·</span>AI</span>
          <span className="mono" style={{ fontSize: 11, color: "var(--tx-3)", letterSpacing: ".18em", paddingLeft: 8, borderLeft: "1px solid var(--line-2)" }}>ACADEMY</span>
        </button>

        <div style={{ flex: 1 }} />

        <button onClick={onSearch} className="btn" style={{ minWidth: 168, justifyContent: "space-between" }}>
          <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><circle cx="7" cy="7" r="5" stroke="currentColor" strokeWidth="1.5"/><path d="M11 11l3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
            Search topics
          </span>
          <span className="mono" style={{ fontSize: 10, color: "var(--tx-4)", border: "1px solid var(--line-2)", borderRadius: 4, padding: "1px 5px" }}>/</span>
        </button>

        {view === "map" && (
          <div style={{ display: "flex", gap: 4, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 8, padding: 3 }}>
            {[["grid", "Atlas"], ["stack", "Pipeline"], ["path", "Path"]].map(([k, lab]) => (
              <button key={k} onClick={() => setLayout(k)} className="mono" title={`${lab} layout`}
                style={{ fontSize: 11, padding: "6px 11px", borderRadius: 5, cursor: "pointer", border: "none",
                  background: layout === k ? "var(--accent-soft)" : "transparent", color: layout === k ? "var(--accent)" : "var(--tx-3)", transition: "all .15s" }}>{lab}</button>
            ))}
          </div>
        )}

        <button onClick={() => setLight((v) => !v)} className="btn ghost" title="Toggle reading mode" style={{ padding: "9px 11px" }}>
          {light ? "◐" : "◑"}
        </button>

        <div style={{ display: "flex", alignItems: "center", gap: 9 }} title={`${done} of ${ALL_TOPIC_IDS.length} topics complete`}>
          <ProgressRing pct={pct} size={34} stroke={3}>{Math.round(pct * 100)}</ProgressRing>
        </div>
      </div>
    </header>
  );
}

/* ============ Search overlay ============ */
function SearchOverlay({ onClose, onPick }) {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { inputRef.current && inputRef.current.focus(); }, []);
  const results = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) return [];
    const out = [];
    MODULES.forEach((mod) => mod.groups.forEach((g, gi) => g.topics.forEach((t, ti) => {
      const hay = (t.title + " " + t.body + " " + g.title + " " + mod.title).toLowerCase();
      if (hay.includes(term)) out.push({ mod, gi, ti, t, g });
    })));
    return out.slice(0, 40);
  }, [q]);

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 80, background: "rgba(4,7,14,.66)", backdropFilter: "blur(6px)", display: "flex", justifyContent: "center", paddingTop: "10vh" }}>
      <div onClick={(e) => e.stopPropagation()} className="panel" style={{ width: "min(680px, 92vw)", maxHeight: "76vh", display: "flex", flexDirection: "column", overflow: "hidden", boxShadow: "0 30px 80px rgba(0,0,0,.5)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 20px", borderBottom: "1px solid var(--line)" }}>
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><circle cx="7" cy="7" r="5" stroke="var(--tx-3)" strokeWidth="1.5"/><path d="M11 11l3 3" stroke="var(--tx-3)" strokeWidth="1.5" strokeLinecap="round"/></svg>
          <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search all 10 modules…"
            style={{ flex: 1, background: "none", border: "none", outline: "none", color: "var(--tx)", font: "inherit", fontSize: 16 }} />
          <button onClick={onClose} className="mono btn ghost" style={{ fontSize: 10, padding: "4px 8px" }}>ESC</button>
        </div>
        <div style={{ overflowY: "auto", padding: q.trim() ? "8px" : "40px 20px" }}>
          {!q.trim() && <p className="mono" style={{ textAlign: "center", color: "var(--tx-4)", fontSize: 13 }}>Type to filter topics across the curriculum</p>}
          {q.trim() && !results.length && <p className="mono" style={{ textAlign: "center", color: "var(--tx-4)", fontSize: 13, padding: 24 }}>No matches for “{q}”</p>}
          {results.map((r, i) => (
            <button key={i} onClick={() => onPick(r.mod.id, topicId(r.mod.id, r.gi, r.ti))}
              style={{ width: "100%", textAlign: "left", display: "flex", gap: 12, alignItems: "center", padding: "11px 13px", borderRadius: 8, border: "none", background: "none", cursor: "pointer" }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-3)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "none"}>
              <span className="mono" data-accent={moduleAccent(r.mod)} style={{ fontSize: 12, color: "var(--accent)", flex: "none", width: 22 }}>{r.mod.n}</span>
              <span style={{ flex: 1, minWidth: 0 }}>
                <span style={{ display: "block", fontSize: 14.5, color: "var(--tx)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.t.title}</span>
                <span className="mono" style={{ fontSize: 11, color: "var(--tx-4)" }}>{r.mod.title} · {r.g.title}</span>
              </span>
              <span style={{ color: "var(--tx-4)", flex: "none" }}>↵</span>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ============ Module card (grid + path layouts) ============ */
function ModuleCard({ mod, progress, onOpen, variant }) {
  const ids = moduleTopicIds(mod);
  const done = ids.filter((id) => progress[id]).length;
  const pct = done / ids.length;
  const topics = ids.length;
  const acc = moduleAccent(mod);
  return (
    <button data-accent={acc} onClick={() => onOpen(mod.id)} className="panel ticked"
      style={{ textAlign: "left", cursor: "pointer", padding: "22px 22px 20px", display: "flex", flexDirection: "column", gap: 14,
        position: "relative", overflow: "hidden", transition: "transform .18s, border-color .18s, box-shadow .18s", minHeight: variant === "grid" ? 196 : "auto" }}
      onMouseEnter={(e) => { e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.borderColor = "var(--accent-line)"; e.currentTarget.style.boxShadow = "0 14px 40px rgba(0,0,0,.28)"; }}
      onMouseLeave={(e) => { e.currentTarget.style.transform = "none"; e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.boxShadow = "none"; }}>
      <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--accent)", opacity: pct > 0 ? 1 : .35 }} />
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12 }}>
        <span className="mono disp" style={{ fontSize: 30, fontWeight: 600, color: "var(--accent)", lineHeight: 1 }}>{mod.n}</span>
        <ProgressRing pct={pct} size={40} stroke={3}>{done === topics && topics > 0 ? "✓" : `${done}`}</ProgressRing>
      </div>
      <div>
        <span className="pill" style={{ marginBottom: 9 }}>{mod.tag}</span>
        <h3 className="disp" style={{ margin: "0 0 6px", fontSize: 19, fontWeight: 600, lineHeight: 1.15, color: "var(--tx)" }}>{mod.title}</h3>
        <p style={{ margin: 0, fontSize: 13.5, color: "var(--tx-3)", lineHeight: 1.45 }}>{mod.blurb}</p>
      </div>
      <div style={{ marginTop: "auto", display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
        <span className="mono" style={{ fontSize: 11, color: "var(--tx-4)" }}>{mod.groups.length} groups · {topics} topics</span>
        <span className="mono" style={{ fontSize: 11, color: "var(--tx-4)" }}>·</span>
        <span className="mono" style={{ fontSize: 12, color: "var(--accent)" }}>OPEN →</span>
      </div>
    </button>
  );
}

/* ============ Map view ============ */
function MapView({ progress, layout, onOpen }) {
  const done = ALL_TOPIC_IDS.filter((id) => progress[id]).length;
  const pct = done / ALL_TOPIC_IDS.length;
  return (
    <main className="fade-in" style={{ maxWidth: 1180, margin: "0 auto", padding: "0 24px 100px" }}>
      {/* hero */}
      <section style={{ padding: "60px 0 44px", borderBottom: "1px solid var(--line)", marginBottom: 44 }}>
        <div style={{ display: "flex", gap: 10, marginBottom: 22, flexWrap: "wrap" }}>
          <span className="pill mint live"><span className="dot"></span>LIVE CURRICULUM</span>
          <span className="pill">{MODULES.length} MODULES</span>
          <span className="pill">{ALL_TOPIC_IDS.length} TOPICS</span>
        </div>
        <h1 className="disp" style={{ fontSize: "clamp(34px, 5vw, 58px)", fontWeight: 600, letterSpacing: "-0.02em", lineHeight: 1.04, margin: "0 0 18px", maxWidth: 820, textWrap: "balance" }}>
          {DATA.meta.title.split(" ").slice(0, -1).join(" ")} <span style={{ color: "var(--mint)" }}>{DATA.meta.title.split(" ").slice(-1)}</span>
        </h1>
        <p style={{ fontSize: 17, color: "var(--tx-2)", maxWidth: 640, lineHeight: 1.55, margin: "0 0 30px", textWrap: "pretty" }}>{DATA.meta.subtitle}</p>
        <div style={{ display: "flex", alignItems: "center", gap: 18, maxWidth: 520 }}>
          <ProgressBar pct={pct} height={6} />
          <span className="mono" style={{ fontSize: 12.5, color: pct > 0 ? "var(--mint)" : "var(--tx-3)", flex: "none" }}>{done}/{ALL_TOPIC_IDS.length}</span>
        </div>
      </section>

      {layout === "grid" && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(270px, 1fr))", gap: 18 }}>
          {MODULES.map((m) => <ModuleCard key={m.id} mod={m} progress={progress} onOpen={onOpen} variant="grid" />)}
        </div>
      )}

      {layout === "stack" && (
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {MODULES.map((m) => {
            const ids = moduleTopicIds(m); const d = ids.filter((id) => progress[id]).length; const p = d / ids.length;
            return (
              <button key={m.id} data-accent={moduleAccent(m)} onClick={() => onOpen(m.id)} className="panel ticked"
                style={{ textAlign: "left", cursor: "pointer", padding: "20px 24px", display: "flex", alignItems: "center", gap: 24, position: "relative", overflow: "hidden", transition: "border-color .18s, background .18s" }}
                onMouseEnter={(e) => { e.currentTarget.style.borderColor = "var(--accent-line)"; e.currentTarget.style.background = "var(--bg-3)"; }}
                onMouseLeave={(e) => { e.currentTarget.style.borderColor = "var(--line)"; e.currentTarget.style.background = "var(--bg-2)"; }}>
                <span style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: 3, background: "var(--accent)", opacity: p > 0 ? 1 : .35 }} />
                <span className="mono disp" style={{ fontSize: 34, fontWeight: 600, color: "var(--accent)", width: 52, flex: "none" }}>{m.n}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 4, flexWrap: "wrap" }}>
                    <h3 className="disp" style={{ margin: 0, fontSize: 20, fontWeight: 600, color: "var(--tx)" }}>{m.title}</h3>
                    <span className="pill">{m.tag}</span>
                  </div>
                  <p style={{ margin: 0, fontSize: 14, color: "var(--tx-3)", lineHeight: 1.45 }}>{m.blurb}</p>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 18, flex: "none" }}>
                  <div style={{ width: 130, display: "none" }} className="bar-wrap"><ProgressBar pct={p} /></div>
                  <span className="mono" style={{ fontSize: 11, color: "var(--tx-4)", whiteSpace: "nowrap" }}>{d}/{ids.length}</span>
                  <ProgressRing pct={p} size={38} stroke={3}>{d === ids.length ? "✓" : `${d}`}</ProgressRing>
                </div>
              </button>
            );
          })}
        </div>
      )}

      {layout === "path" && (
        <div style={{ position: "relative" }}>
          <div style={{ position: "absolute", left: "50%", top: 10, bottom: 10, width: 2, background: "var(--line-2)", transform: "translateX(-50%)" }} />
          <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
            {MODULES.map((m, i) => {
              const left = i % 2 === 0;
              const ids = moduleTopicIds(m); const d = ids.filter((id) => progress[id]).length;
              return (
                <div key={m.id} style={{ display: "flex", justifyContent: left ? "flex-start" : "flex-end", position: "relative" }}>
                  <span data-accent={moduleAccent(m)} style={{ position: "absolute", left: "50%", top: 28, transform: "translate(-50%,-50%)", width: 13, height: 13, borderRadius: "50%", background: d > 0 ? "var(--accent)" : "var(--bg-2)", border: "2px solid var(--accent)", boxShadow: d > 0 ? "0 0 12px var(--accent-glow)" : "none", zIndex: 2 }} />
                  <div style={{ width: "calc(50% - 34px)" }}>
                    <ModuleCard mod={m} progress={progress} onOpen={onOpen} variant="path" />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      <p className="mono" style={{ marginTop: 50, fontSize: 11.5, color: "var(--tx-4)", lineHeight: 1.6, maxWidth: 720, borderTop: "1px solid var(--line)", paddingTop: 20 }}>{DATA.meta.note}</p>
    </main>
  );
}

window.AcademyParts = { TopBar, SearchOverlay, ModuleCard, MapView, topicId, moduleTopicIds, ALL_TOPIC_IDS, MODULES, DATA, moduleAccent };
