/* global React, ReactDOM */
const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = { accent: "#00e0ff", density: "balanced", showTape: true, monoEverything: false };

function AuthShell() {
  const [authPage, setAuthPage] = useState("login");
  window._setAuthPage = setAuthPage;

  const onLogin = () => window.location.reload();

  if (authPage === "register") return <window.RegisterPage onLogin={onLogin} />;
  return <window.LoginPage onLogin={onLogin} />;
}

function App() {
  const [user, setUser] = useState(window.Auth.getUser());
  const [route, setRoute] = useState("dashboard");
  const [tweaks, setTweak] = window.useTweaks(TWEAK_DEFAULTS);
  const [theme, setTheme] = useState(() => {
    const saved = localStorage.getItem("aura-theme");
    return saved === "light" ? "light" : "dark";
  });

  // Shared state — fetched from API
  const [accounts, setAccounts] = useState([]);
  const [activeAccount, setActiveAccount] = useState(null);
  const [openTrades, setOpenTrades] = useState([]);
  const [botStatus, setBotStatus] = useState(null);
  const [perf, setPerf] = useState(null);
  const [strategies, setStrategies] = useState([]);
  const [activeStrategy, setActiveStrategy] = useState(null);

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("aura-theme", theme); } catch (e) {}
  }, [theme]);

  useEffect(() => {
    document.documentElement.style.setProperty("--accent", tweaks.accent);
  }, [tweaks.accent]);

  useEffect(() => {
    document.body.style.fontFamily = tweaks.monoEverything ? "var(--font-mono)" : "var(--font-sans)";
  }, [tweaks.monoEverything]);

  useEffect(() => {
    if (!user) {
      window.api.me().then((u) => { if (u) { setUser(u); window.Auth.setUser(u); } }).catch(() => {});
    }
  }, []);

  useEffect(() => {
    window.api.listAccounts().then((accts) => {
      if (accts && accts.length > 0) {
        setAccounts(accts);
        const def = accts.find((a) => a.is_default) || accts[0];
        setActiveAccount(def);
      }
    }).catch(() => {});
  }, []);

  useEffect(() => {
    if (!activeAccount) return;
    const refresh = () => {
      window.api.openTrades(activeAccount.id).then(setOpenTrades).catch(() => {});
      window.api.botStatus(activeAccount.id).then(setBotStatus).catch(() => {});
      window.api.performance(activeAccount.id, 60).then(setPerf).catch(() => {});
    };
    refresh();
    const id = setInterval(refresh, 15000);
    return () => clearInterval(id);
  }, [activeAccount]);

  // Strategy catalog (once) + the active account's selected strategy.
  useEffect(() => {
    window.api.listStrategies().then((s) => { if (s) setStrategies(s); }).catch(() => {});
  }, []);

  useEffect(() => {
    if (!activeAccount) { setActiveStrategy(null); return; }
    window.api.getBotSettings(activeAccount.id)
      .then((s) => { if (s) setActiveStrategy(s.strategy || "ema_crossover"); })
      .catch(() => {});
  }, [activeAccount]);

  // Switch strategy globally for the active account — persists immediately.
  const onChangeStrategy = async (name) => {
    if (!activeAccount || !name || name === activeStrategy) return;
    const prev = activeStrategy;
    setActiveStrategy(name); // optimistic
    try {
      await window.api.saveBotSettings(activeAccount.id, { strategy: name });
    } catch (e) {
      setActiveStrategy(prev); // revert on failure
    }
  };

  const marketOpen = useMemo(() => {
    const d = new Date();
    const day = d.getUTCDay();
    return day >= 1 && day <= 5;
  }, []);

  // Today's P&L = realized on trades closed today (live from MT5) + unrealized
  // floating P&L on currently-open positions.
  const dayPnL = useMemo(() => {
    const realizedToday = perf && perf.today_pnl != null ? perf.today_pnl : 0;
    const unrealized = openTrades.reduce((sum, t) => sum + (t.pnl || 0), 0);
    return realizedToday + unrealized;
  }, [perf, openTrades]);

  const sharedState = {
    user, accounts, activeAccount, setActiveAccount,
    openTrades, setOpenTrades, botStatus, setBotStatus,
    accounts, setAccounts,
    strategies, activeStrategy, onChangeStrategy,
    balance: activeAccount ? activeAccount.balance : null,
    equity: activeAccount ? activeAccount.equity : null,
    dayPnL,
  };

  const toggleTheme = () => setTheme((t) => t === "dark" ? "light" : "dark");

  let page;
  switch (route) {
    case "dashboard": page = <window.Dashboard state={sharedState} />; break;
    case "active": page = <window.ActiveTrades state={sharedState} />; break;
    case "history": page = <window.TradeHistory state={sharedState} />; break;
    case "signals": page = <window.SignalLog state={sharedState} />; break;
    case "performance":
    case "analytics": page = <window.Performance state={sharedState} />; break;
    case "bot":
    case "risk": page = <window.BotSettings state={sharedState} />; break;
    case "accounts": page = <window.MT5Accounts state={sharedState} onAccountsChange={setAccounts} />; break;
    case "profile": page = <window.Profile user={user} onUserUpdate={setUser} />; break;
    case "help": page = <PlaceholderPage title="Help & Documentation" />; break;
    default: page = <window.Dashboard state={sharedState} />;
  }

  return (
    <>
      <div className="app">
        <window.TopBar onNav={setRoute} marketOpen={marketOpen} theme={theme} onToggleTheme={toggleTheme} user={user}
          strategies={strategies} activeStrategy={activeStrategy} onChangeStrategy={onChangeStrategy} hasAccount={!!activeAccount} />
        <window.Sidebar active={route} onNav={setRoute} balance={sharedState.balance} dayPnL={dayPnL} openCount={openTrades.length} />
        <div className="main">
          {tweaks.showTape && <window.Tape />}
          {page}
        </div>
      </div>
      <Tweaks tweaks={tweaks} setTweak={setTweak} theme={theme} setTheme={setTheme} />
    </>
  );
}

function PlaceholderPage({ title }) {
  return (
    <>
      <div className="page-header"><h1 className="page-title">{title}</h1></div>
      <div className="page-content">
        <div className="panel" style={{ padding: 60, textAlign: "center", color: "var(--text-2)" }}>
          <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: ".18em", textTransform: "uppercase" }}>Coming soon</div>
        </div>
      </div>
    </>
  );
}

function Tweaks({ tweaks, setTweak, theme, setTheme }) {
  const { TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakColor } = window;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakRadio label="Mode" value={theme} options={[{ label: "Dark", value: "dark" }, { label: "Light", value: "light" }]} onChange={(v) => setTheme(v)} />
        <TweakColor label="Accent color" value={tweaks.accent} onChange={(v) => setTweak("accent", v)} />
        <TweakToggle label="Monospace everywhere" value={tweaks.monoEverything} onChange={(v) => setTweak("monoEverything", v)} />
      </TweakSection>
      <TweakSection title="Layout">
        <TweakRadio label="Density" value={tweaks.density} options={[{ label: "Compact", value: "compact" }, { label: "Balanced", value: "balanced" }, { label: "Roomy", value: "roomy" }]} onChange={(v) => setTweak("density", v)} />
        <TweakToggle label="Show ticker tape" value={tweaks.showTape} onChange={(v) => setTweak("showTape", v)} />
      </TweakSection>
      <TweakSection title="Account">
        <window.TweakButton label="Sign Out" onClick={() => window.Auth.logout()} />
      </TweakSection>
    </TweaksPanel>
  );
}

function Root() {
  if (!window.Auth.isLoggedIn()) return <AuthShell />;
  return <App />;
}

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