/* v3/app.jsx */
const { useState: useA3S, useEffect: useA3E } = React;

const TWEAK_DEFAULTS_V3 = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "comfy",
  "sectionOrder": ["macro", "news", "movers", "scanners", "tools"]
}/*EDITMODE-END*/;

const SECTION_LINKS = {
  macro: "/macro.html",
  news: "/bulletin.html",
  movers: "/heatmap.html",
  scanners: "/13f.html",
  tools: "/screener.html",
};

const SECTIONS_V3 = {
  macro:    { kicker: "The macro picture",    title: <>Rates, credit & <em>inflation</em></>,  tone: "warm", hint: "The pulse of the global macro backdrop — yield curve, spreads, inflation, the sector leaderboard.", render: () => <MacroRow /> },
  news:     { kicker: "News & signals",       title: <>The desk's <em>morning brief</em></>,   tone: "warm", hint: "Live headlines, earnings this week, the economic calendar, breadth, and the intelligence bulletin.", render: () => <NewsRow /> },
  movers:   { kicker: "Today's flow",         title: <>Winners & <em>losers</em></>,           tone: "cool", hint: "Largest intraday moves across the S&P 500 — ranked, with volume context.",                           render: () => <MoversRow /> },
  scanners: { kicker: "Research feeds",       title: <>Smart money, insiders & <em>AI</em></>, tone: "cool", hint: "What insiders filed, how hedge funds moved last quarter, new research, and the IPO pipeline.",        render: () => (
    <>
      <ScannersRow />
      <div style={{ marginTop: 18 }}><ActivityFeed /></div>
    </>
  ) },
  tools:    { kicker: "Deep dives",           title: <>The <em>workbench</em></>,              tone: "warm", hint: "Heatmap, screener, and the earnings calendar — the deep-dive panels you'll live in.", render: () => (
    <>
      <div className="tools-row"><HeatmapCard /><ScreenerCard /></div>
      <div style={{ marginTop: 18 }}><EarningsCalCard /></div>
    </>
  )},
};

function AppV3() {
  const [state, setState] = useA3S(() => {
    try { return { ...TWEAK_DEFAULTS_V3, ...JSON.parse(localStorage.getItem("tmt.v3.state") || "{}") }; }
    catch { return { ...TWEAK_DEFAULTS_V3 }; }
  });
  const [sectionOrder, setSectionOrder] = useA3S(state.sectionOrder || TWEAK_DEFAULTS_V3.sectionOrder);
  const [drawerOpen, setDrawerOpen] = useA3S(false);
  const [cmdOpen, setCmdOpen] = useA3S(false);
  const [tweaksOpen, setTweaksOpen] = useA3S(false);

  useA3E(() => {
    document.documentElement.setAttribute("data-theme", state.theme);
    document.documentElement.setAttribute("data-density", state.density || "comfy");
    const next = { ...state, sectionOrder };
    try { localStorage.setItem("tmt.v3.state", JSON.stringify(next)); } catch {}
    try { window.parent.postMessage({ type: "__edit_mode_set_keys", edits: next }, "*"); } catch {}
  }, [state, sectionOrder]);

  useA3E(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setCmdOpen(o => !o); }
      if (e.key === "w" && !e.metaKey && !e.ctrlKey && document.activeElement?.tagName !== "INPUT") { setDrawerOpen(o => !o); }
      if (e.key === "Escape") {
        // Close the front-most modal layer. Order matters: command palette
        // sits above the drawer, drawer above tweaks.
        if (cmdOpen) setCmdOpen(false);
        else if (drawerOpen) setDrawerOpen(false);
        else if (tweaksOpen) setTweaksOpen(false);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [cmdOpen, drawerOpen, tweaksOpen]);

  useA3E(() => {
    const on = (e) => {
      if (e.data?.type === "__activate_edit_mode") setTweaksOpen(true);
      if (e.data?.type === "__deactivate_edit_mode") setTweaksOpen(false);
    };
    window.addEventListener("message", on);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", on);
  }, []);

  const livePrices = useLivePrices(today, 2200);

  useA3E(() => {
    document.documentElement.classList.toggle("drawer-open", !!drawerOpen);
  }, [drawerOpen]);

  const handleCmd = (item) => {
    if (item.type === "cmd") {
      if (item.data.s === "theme.toggle") setState(s => ({ ...s, theme: s.theme === "dark" ? "light" : "dark" }));
      if (item.data.s === "density.toggle") setState(s => ({ ...s, density: s.density === "compact" ? "comfy" : "compact" }));
      if (item.data.s === "watchlist.add" || item.data.s === "watchlist.export") setDrawerOpen(true);
    }
    if (item.type === "sym") setDrawerOpen(true);
  };

  // Minimal SECTIONS adapter shape for TweaksPanel
  const TWEAK_SECTIONS = Object.fromEntries(Object.entries(SECTIONS_V3).map(([k, v]) => [k, { title: typeof v.title === "string" ? v.title : k.charAt(0).toUpperCase() + k.slice(1), hint: v.hint }]));

  return (
    <>
      <TopbarV3
        onOpenWatchlist={() => setDrawerOpen(o => !o)}
        onOpenTweaks={() => setTweaksOpen(o => !o)}
        onOpenCmd={() => setCmdOpen(true)}
      />
      <IndicesRibbon livePrices={livePrices} />
      <HeroStrip livePrices={livePrices} />
      <main className="dash">
        {sectionOrder.map(id => {
          const s = SECTIONS_V3[id]; if (!s) return null;
          return (
            <section key={id} className="section" data-tone={s.tone}>
              <div className="section-hd">
                <div className="sh-title">
                  <div className="kicker" style={{ color: s.tone === "cool" ? "var(--cool)" : "var(--warm)" }}>{s.kicker}</div>
                  <h2 className="serif">{s.title}</h2>
                </div>
                <div className="hd-actions">
                  <span className="chip-live"><span className="d" />live</span>
                  <a className="sec-link" href={SECTION_LINKS[id] || "#"}>See full view →</a>
                </div>
                <span className="expl">{s.hint}</span>
              </div>
              {s.render()}
            </section>
          );
        })}
        <Trailhead />
        <footer style={{ padding: "28px 4px 40px", color: "var(--ink-3)", fontSize: 11.5, display: "flex", gap: 14, borderTop: "1px solid var(--rule)", marginTop: 24, fontFamily: "var(--sans)" }}>
          <span style={{ fontFamily: "var(--serif)", fontStyle: "italic", color: "var(--ink-1)" }}>The Market Terminal</span>
          <span style={{ color: "var(--ink-4)" }}>·</span>
          <span>Research preview — data is synthetic. Not investment advice.</span>
          <span style={{ marginLeft: "auto" }}>
            Press <kbd style={{ padding: "1px 5px", border: "1px solid var(--rule)", borderRadius: 3, fontSize: 10, fontFamily: "var(--mono)" }}>⌘K</kbd> for search ·
            <kbd style={{ padding: "1px 5px", border: "1px solid var(--rule)", borderRadius: 3, fontSize: 10, fontFamily: "var(--mono)", marginLeft: 6 }}>W</kbd> for watchlist
          </span>
        </footer>
      </main>
      <WatchlistDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} livePrices={livePrices} />
      <CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} onCmd={handleCmd} />
      <TweaksPanel
        open={tweaksOpen}
        onClose={() => setTweaksOpen(false)}
        state={state} setState={setState}
        sectionOrder={sectionOrder} setSectionOrder={setSectionOrder}
        SECTIONS={TWEAK_SECTIONS}
      />
    </>
  );
}

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