// Account — the signed-in user's in-house paper trading engine. Reached from
// the ☰ menu. The system is fully in-house (no real-money path), so there are
// no Alpaca credentials to manage: each user just gets their own paper account.
// This tab is engine start/stop + autostart only.

function Account() {
  const [info, setInfo] = React.useState(null);     // GET /api/account
  const [msg, setMsg] = React.useState(null);       // {ok, text}
  const [busy, setBusy] = React.useState(false);

  const load = async () => {
    try {
      setInfo(await (await apiFetch("/api/account")).json());
    } catch { setInfo({ error: true }); }
  };
  React.useEffect(() => { load(); }, []);

  const engineAction = async (action) => {
    setBusy(true); setMsg(null);
    try {
      const r = await apiPost(`/api/account/engine/${action}`);
      const d = await r.json();
      if (!r.ok) setMsg({ ok: false, text: d.detail || `Engine ${action} failed.` });
      else setMsg({ ok: true, text: action === "start" ? "Engine started." : "Engine stopped." });
      load();
      refreshStatus();   // header running chip reflects it immediately
    } catch (e) { setMsg({ ok: false, text: String(e) }); }
    setBusy(false);
  };

  const setAutostart = async (enabled) => {
    setInfo(i => ({ ...i, engine_autostart: enabled }));   // optimistic
    try { await apiPost("/api/account/engine/autostart", { enabled }); } catch {}
    load();
  };

  if (!info) return <div><PageHeader title="Account" /><Skeleton height={180} /></div>;
  if (info.auth_enabled === false) {
    return (
      <div>
        <PageHeader title="Account" subtitle="In-house paper trading" />
        <Card><div style={{ color: UI.c.dim, fontSize: 13 }}>
          Auth is disabled (local/dev mode) — the engine trades the single in-house paper account.
        </div></Card>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: 640 }}>
      <PageHeader title="Account" subtitle={info.email} />

      <Card title="Your trading engine">
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ fontSize: 13, color: UI.c.dim }}>
            Your engine trades an <b>in-house paper account</b> — orders fill against live
            market data; no broker account or credentials are involved.
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 13 }}>
            <Dot tone={info.engine_running ? "green" : "gray"} />
            {info.engine_running
              ? "Running — scanning and trading your paper account."
              : "Stopped. Start it to begin scanning and trading your paper account."}
          </div>
          <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
            {info.engine_running
              ? <PillButton disabled={busy} onClick={() => engineAction("stop")}>Stop engine</PillButton>
              : <PillButton disabled={busy} onClick={() => engineAction("start")}>Start engine</PillButton>}
            <label style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 13 }}>
              <input type="checkbox" checked={!!info.engine_autostart}
                onChange={e => setAutostart(e.target.checked)} disabled={busy} />
              Start automatically when the server boots
            </label>
          </div>
          {msg && <div style={{ color: msg.ok ? UI.c.green : UI.c.red, fontSize: 13 }}>{msg.text}</div>}
        </div>
      </Card>
    </div>
  );
}
