// Main App — routes between pages, owns tweaks.
const { useState: usS, useEffect: usE, useMemo: usM } = React;

const ACCENT_SOFT = {
  "#00D4AA": "rgba(0,212,170,0.12)",
  "#7C5CFF": "rgba(124,92,255,0.14)",
  "#3B82F6": "rgba(59,130,246,0.14)",
  "#F5A623": "rgba(245,166,35,0.14)",
};

function App() {
  const [t, setT] = useTweaks(window.TWEAK_DEFAULTS);
  const [collapsed, setCollapsed] = usS(t.sidebarCollapsed);
  const [route, setRoute] = usS(() => location.hash.slice(1) || "dash");

  usE(() => setCollapsed(t.sidebarCollapsed), [t.sidebarCollapsed]);
  usE(() => {
    const onHash = () => setRoute(location.hash.slice(1) || "dash");
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const goto = (r) => { location.hash = r; setRoute(r); };
  const setActiveExchange = (id) => setT("activeExchange", id);

  const accent = { base: t.accent, soft: ACCENT_SOFT[t.accent] || "rgba(0,212,170,0.12)" };

  usE(() => {
    document.documentElement.style.setProperty("--accent", accent.base);
    document.documentElement.style.setProperty("--accent-soft", accent.soft);
    document.documentElement.dataset.density = t.density;
  }, [t.accent, t.density]);

  // Auto-bump mode to paper when switching to Kraken (no public testnet)
  usE(() => {
    if (t.activeExchange === "kraken" && t.mode === "testnet") setT("mode", "paper");
    if (t.activeExchange === "binance" && t.mode === "paper") setT("mode", "testnet");
  }, [t.activeExchange]);

  return (
    <div style={{ display: "flex", minHeight: "100vh" }}>
      <Sidebar collapsed={collapsed} onToggle={() => setCollapsed((c) => !c)}
        route={route} setRoute={goto} plan={t.plan}
        activeExchange={t.activeExchange} mode={t.mode} />
      <main style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column" }}>
        <TopBar route={route} onNew={() => alert("Emergency stop confirmed — would halt and close positions.")}
          activeExchange={t.activeExchange} />
        <div style={{ padding: "24px 32px 32px", display: "flex", flexDirection: "column", gap: "var(--row-gap)" }}
             data-screen-label={route}>
          {route === "dash"    && <DashboardPage   scenario={t.scenario} accent={accent} livePrices={t.livePrices}
                                                    activeExchange={t.activeExchange} setActiveExchange={setActiveExchange} mode={t.mode} />}
          {route === "signals" && <SignalsPage     accent={accent} activeExchange={t.activeExchange} />}
          {route === "trades"  && <TradesPage      accent={accent} activeExchange={t.activeExchange} />}
          {route === "risk"    && <RiskPage        accent={accent} scenario={t.scenario} activeExchange={t.activeExchange} />}
          {route === "back"    && <BacktesterPage  accent={accent} />}
          {route === "alerts"  && <AlertsPage      accent={accent} />}
          {route === "logs"    && <LogsPage        accent={accent} />}
          {route === "build"   && <RoadmapPage     accent={accent} />}
          {route === "docs"    && <DocsPage        accent={accent} activeExchange={t.activeExchange} />}
          {route === "set"     && <SettingsPage    accent={accent} activeExchange={t.activeExchange} setActiveExchange={setActiveExchange} />}
          <Footer />
        </div>
      </main>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Exchange (v3 spec)">
          <TweakRadio label="Active exchange" value={t.activeExchange}
            options={["binance", "kraken"]}
            onChange={(v) => setT("activeExchange", v)} />
          <TweakSelect label="Trading mode" value={t.mode}
            options={["testnet", "paper", "live"]}
            onChange={(v) => setT("mode", v)} />
        </TweakSection>

        <TweakSection label="Theme">
          <TweakColor label="Accent" value={t.accent}
            options={["#00D4AA", "#7C5CFF", "#3B82F6", "#F5A623"]}
            onChange={(v) => setT("accent", v)} />
          <TweakRadio label="Density" value={t.density}
            options={["compact", "comfy", "spacious"]}
            onChange={(v) => setT("density", v)} />
        </TweakSection>

        <TweakSection label="Page">
          <TweakSelect label="Navigate to" value={route}
            options={["dash", "signals", "trades", "risk", "back", "alerts", "logs", "build", "docs", "set"]}
            onChange={(v) => goto(v)} />
        </TweakSection>

        <TweakSection label="Scenario">
          <TweakSelect label="Performance" value={t.scenario}
            options={["winning", "losing", "volatile"]}
            onChange={(v) => setT("scenario", v)} />
          <TweakToggle label="Live ticking prices" value={t.livePrices}
            onChange={(v) => setT("livePrices", v)} />
        </TweakSection>

        <TweakSection label="State">
          <TweakToggle label="Sidebar collapsed" value={t.sidebarCollapsed}
            onChange={(v) => setT("sidebarCollapsed", v)} />
          <TweakRadio label="Plan" value={t.plan}
            options={["Free", "Pro"]}
            onChange={(v) => setT("plan", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function Footer() {
  return (
    <footer style={{
      marginTop: 8, padding: "16px 4px", display: "flex", justifyContent: "space-between",
      fontSize: 12, color: "var(--text-3)", borderTop: "1px solid var(--line)",
    }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
          <span className="pulse-dot" style={{ width: 7, height: 7, borderRadius: 999, background: "var(--profit)", color: "var(--profit)" }} />
          All systems operational
        </span>
        <span>·</span>
        <span className="mono">Auto-Trader v1.1.0 · spec v3.0</span>
        <span>·</span>
        <span className="mono">Dubai · 3.2ms RTT</span>
      </div>
      <div style={{ display: "flex", gap: 16 }}>
        <a href="index.html" style={{ color: "var(--text-2)", textDecoration: "none" }}>← Marketing site</a>
        <a href="#docs" style={{ color: "var(--text-3)", textDecoration: "none" }}>Docs</a>
        <a href="https://github.com/aminbassam/Auto-Trader" target="_blank" style={{ color: "var(--text-3)", textDecoration: "none" }}>GitHub</a>
      </div>
    </footer>
  );
}

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