/* global React, AURA_DATA, Icon */
const D4 = window.AURA_DATA;
const { useState, useEffect } = React;

function BotSettings({ state }) {
  // Strategy selection is global (TopBar) and saved instantly, so it is read
  // from shared state here rather than the per-page settings object.
  const { activeAccount, strategies = [], activeStrategy, onChangeStrategy } = state;
  const [settings, setSettings] = useState(null);
  const [dirty, setDirty] = useState(false);
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState(null);

  useEffect(() => {
    if (!activeAccount) return;
    window.api.getBotSettings(activeAccount.id).then((s) => { if (s) setSettings(s); }).catch(() => {});
  }, [activeAccount]);

  const update = (key, val) => { setSettings((s) => ({ ...s, [key]: val })); setDirty(true); };
  const updateSession = (key, val) => {
    const sessions = JSON.parse(settings.sessions_json || "{}");
    const next = JSON.stringify({ ...sessions, [key]: val });
    update("sessions_json", next);
  };

  const save = async () => {
    if (!activeAccount || !settings) return;
    setSaving(true);
    try {
      // strategy is owned by the global selector (saved on change) — don't let
      // a bulk save here overwrite it with a possibly-stale value.
      const { strategy, ...payload } = settings;
      await window.api.saveBotSettings(activeAccount.id, payload);
      setDirty(false);
      setToast({ msg: "Settings saved", type: "success" });
      setTimeout(() => setToast(null), 2400);
    } catch (err) {
      setToast({ msg: err.message || "Save failed", type: "error" });
      setTimeout(() => setToast(null), 3000);
    } finally {
      setSaving(false);
    }
  };

  const Toggle = ({ on, onClick }) => <div className={`toggle ${on ? "on" : ""}`} onClick={onClick}></div>;
  const Slider = ({ value, set, min, max, step, suffix }) => (
    <div className="slider-wrap">
      <input className="slider" type="range" min={min} max={max} step={step} value={value} onChange={(e) => set(Number(e.target.value))} />
      <span className="val">{value}{suffix}</span>
    </div>
  );

  if (!settings) {
    return (
      <>
        <div className="page-header"><h1 className="page-title">Bot Settings</h1></div>
        <div className="page-content"><div style={{ color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11, padding: 32 }}>
          {activeAccount ? "Loading settings…" : "Select an MT5 account first"}
        </div></div>
      </>
    );
  }

  const sessions = JSON.parse(settings.sessions_json || '{"asian":false,"london":true,"ny":true,"overlap":true}');
  const rr = settings.tp_atr_mult / settings.sl_atr_mult;
  const activeStrategyName = activeStrategy || settings.strategy || "ema_crossover";
  const selectedStrat = strategies.find((s) => s.name === activeStrategyName);
  const strategyLabel = selectedStrat ? selectedStrat.label : activeStrategyName;

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Bot Settings</h1>
          <div className="page-subtitle">Strategy: {strategyLabel} · {activeAccount ? activeAccount.nickname || activeAccount.login : "—"}</div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          <button className="btn ghost" onClick={() => { window.api.getBotSettings(activeAccount.id).then(setSettings).catch(() => {}); setDirty(false); }}>Reset</button>
          <button className="btn primary" onClick={save} disabled={!dirty || saving}>{saving ? "Saving…" : "Save Settings"}</button>
        </div>
      </div>
      <div className="page-content col">
        <div className="banner info">
          <span style={{ width: 14, height: 14, color: "var(--accent)" }}>{Icon.zap}</span>
          <span>AURA trades XAUUSD 24/5 (Mon–Fri). Bot auto-pauses on weekends. Changes take effect on the next bot cycle.</span>
        </div>

        <div className="panel">
          <div className="panel-header"><div className="panel-title">Strategy</div></div>
          <div style={{ padding: 18 }}>
            <div className="field">
              <label>Active strategy <span style={{ color: "var(--text-3)", fontWeight: 400 }}>· saved instantly (also in the top bar)</span></label>
              <select value={activeStrategyName} disabled={!onChangeStrategy} onChange={(e) => onChangeStrategy && onChangeStrategy(e.target.value)}>
                {strategies.length === 0
                  ? <option value={activeStrategyName}>{strategyLabel}</option>
                  : strategies.map((s) => <option key={s.name} value={s.name}>{s.label}</option>)}
              </select>
            </div>
            {selectedStrat && selectedStrat.description && (
              <div style={{ padding: 12, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 4, fontSize: 11, color: "var(--text-2)", lineHeight: 1.5 }}>
                {selectedStrat.description}
              </div>
            )}
          </div>
        </div>

        <div className="grid-2">
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Risk Parameters</div></div>
            <div style={{ padding: 18 }}>
              <div className="field">
                <label>Risk per trade (% of balance)</label>
                <Slider value={settings.risk_pct} set={(v) => update("risk_pct", v)} min={0.1} max={2} step={0.1} suffix="%" />
              </div>
              <div className="field">
                <label>Stop loss (× ATR)</label>
                <Slider value={settings.sl_atr_mult} set={(v) => update("sl_atr_mult", v)} min={0.5} max={4} step={0.1} suffix="×" />
              </div>
              <div className="field">
                <label>Take profit (× ATR)</label>
                <Slider value={settings.tp_atr_mult} set={(v) => update("tp_atr_mult", v)} min={1} max={6} step={0.1} suffix="×" />
              </div>
              <div className="field">
                <label>Max concurrent positions</label>
                <Slider value={settings.max_positions} set={(v) => update("max_positions", v)} min={1} max={10} step={1} suffix="" />
              </div>
              <div style={{ padding: 12, background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 4, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-2)" }}>
                Risk-Reward Ratio: <span style={{ color: "var(--accent)", fontWeight: 600 }}>1 : {rr.toFixed(2)}</span>
              </div>
            </div>
          </div>
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Execution Filters</div></div>
            <div style={{ padding: 18 }}>
              <div className="field">
                <label>Spread gate (max pips)</label>
                <Slider value={settings.spread_gate_pips} set={(v) => update("spread_gate_pips", v)} min={0.5} max={10} step={0.1} suffix=" pips" />
              </div>
              <div className="field">
                <label>ATR entry sensitivity multiplier</label>
                <Slider value={settings.atr_entry_mult} set={(v) => update("atr_entry_mult", v)} min={0.5} max={3} step={0.1} suffix="×" />
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: "1px solid var(--line)" }}>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500 }}>Trailing Stop</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--text-2)" }}>Activates at 1× ATR profit</div>
                </div>
                <Toggle on={settings.use_trailing} onClick={() => update("use_trailing", !settings.use_trailing)} />
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", padding: "8px 0", borderTop: "1px solid var(--line)" }}>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 500 }}>Circuit Breakers</div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--text-2)" }}>Pause after {settings.max_loss_streak} losses or {settings.daily_loss_limit_pct}% daily DD</div>
                </div>
                <Toggle on={settings.use_circuit_breaker} onClick={() => update("use_circuit_breaker", !settings.use_circuit_breaker)} />
              </div>
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-header"><div className="panel-title">Trading Sessions (GMT)</div></div>
          <div style={{ padding: 18, display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 12 }}>
            {[
              { k: "asian", n: "Asian", h: "00:00 – 07:00", c: "Tokyo / Sydney" },
              { k: "london", n: "London", h: "07:00 – 16:00", c: "Highest liquidity" },
              { k: "ny", n: "New York", h: "13:00 – 22:00", c: "USD pairs strong" },
              { k: "overlap", n: "London / NY", h: "13:00 – 16:00", c: "Peak volatility" },
            ].map((s) => (
              <div key={s.k} onClick={() => updateSession(s.k, !sessions[s.k])} style={{ padding: 14, border: `1px solid ${sessions[s.k] ? "rgba(0,224,255,0.3)" : "var(--line)"}`, borderRadius: 4, background: sessions[s.k] ? "var(--accent-glow)" : "var(--bg-2)", cursor: "pointer" }}>
                <div className="row between">
                  <span style={{ fontWeight: 600 }}>{s.n}</span>
                  <div className={`toggle ${sessions[s.k] ? "on" : ""}`} onClick={(e) => { e.stopPropagation(); updateSession(s.k, !sessions[s.k]); }} />
                </div>
                <div className="mono" style={{ fontSize: 11, color: "var(--text-2)", marginTop: 6 }}>{s.h}</div>
                <div style={{ fontSize: 11, color: "var(--text-2)", marginTop: 2 }}>{s.c}</div>
              </div>
            ))}
          </div>
        </div>

        <div className="panel">
          <div className="panel-header"><div className="panel-title">Trading Symbol</div></div>
          <div style={{ padding: 18, display: "flex", alignItems: "center", gap: 18 }}>
            <div style={{ width: 56, height: 56, borderRadius: 8, background: "linear-gradient(135deg, #f5c451, #b45309)", display: "grid", placeItems: "center", color: "#1a1300", fontWeight: 800, fontFamily: "var(--font-mono)", fontSize: 20, boxShadow: "0 0 24px rgba(245,196,81,0.25)" }}>Au</div>
            <div style={{ flex: 1 }}>
              <div className="row" style={{ gap: 8, alignItems: "baseline" }}>
                <div style={{ fontSize: 18, fontWeight: 600, fontFamily: "var(--font-mono)" }}>XAUUSD</div>
                <div style={{ color: "var(--text-2)", fontSize: 12 }}>Spot Gold / US Dollar</div>
                <span className="pill buy" style={{ marginLeft: 8 }}>● ACTIVE</span>
              </div>
              <div className="mono" style={{ fontSize: 11, color: "var(--text-2)", marginTop: 6 }}>AURA trades XAUUSD exclusively on the M15 timeframe.</div>
            </div>
          </div>
        </div>
      </div>
      {toast && <div className={`toast ${toast.type}`}>{toast.msg}</div>}
    </>
  );
}

function MT5Accounts({ state, onAccountsChange }) {
  const { accounts, activeAccount, setActiveAccount } = state;
  const [showAdd, setShowAdd] = useState(false);
  const [form, setForm] = useState({ nickname: "", login: "", server: "OctaFX-Demo", password: "", terminal_path: "" });
  const [addError, setAddError] = useState("");
  const [addLoading, setAddLoading] = useState(false);
  const [testResults, setTestResults] = useState({});
  const [testLoading, setTestLoading] = useState({});
  const [toast, setToast] = useState(null);
  const [conn, setConn] = useState({});

  // Poll live MT5 connection status for accounts that are starting or active, so
  // onboarding shows "Connecting → Connected" or a clear "Login failed".
  React.useEffect(() => {
    const targets = accounts.filter((a) => a.bot_active || ["provisioning", "auth_failed", "error"].includes(a.container_status));
    if (targets.length === 0) return;
    let cancelled = false;
    const poll = () => targets.forEach((a) => {
      window.api.connectionStatus(a.id).then((r) => { if (!cancelled && r) setConn((c) => ({ ...c, [a.id]: r })); }).catch(() => {});
    });
    poll();
    const t = setInterval(poll, 8000);
    return () => { cancelled = true; clearInterval(t); };
  }, [accounts]);

  const connPill = (a) => {
    const cs = (conn[a.id] && conn[a.id].status) || a.container_status || "none";
    const map = {
      running: ["MT5 Connected", "buy"],
      provisioning: ["Connecting…", "neutral"],
      auth_failed: ["Login failed", "sell"],
      error: ["Connection error", "sell"],
      stopped: ["MT5 Stopped", "neutral"],
    };
    const entry = map[cs];
    if (!entry) return null;
    return <span className={`pill ${entry[1]}`} title={(conn[a.id] && conn[a.id].detail) || ""}>● {entry[0]}</span>;
  };

  const showToast = (msg, type = "success") => {
    setToast({ msg, type });
    setTimeout(() => setToast(null), 2400);
  };

  const addAccount = async () => {
    if (!form.login || !form.password) { setAddError("Login and password are required"); return; }
    setAddLoading(true);
    setAddError("");
    try {
      const acct = await window.api.createAccount(form);
      const updated = [...accounts, acct];
      onAccountsChange(updated);
      setShowAdd(false);
      setForm({ nickname: "", login: "", server: "OctaFX-Demo", password: "", terminal_path: "" });
      showToast("Account added — test the connection to verify");
    } catch (err) {
      setAddError(err.message || "Failed to add account");
    } finally {
      setAddLoading(false);
    }
  };

  const testConn = async (id) => {
    setTestLoading((t) => ({ ...t, [id]: true }));
    try {
      const res = await window.api.testConnection(id);
      setTestResults((r) => ({ ...r, [id]: res }));
      if (res.success) {
        showToast("Connection verified");
        // Refresh account data after successful test
        const updated = await window.api.listAccounts();
        if (updated) onAccountsChange(updated);
      } else {
        showToast(res.message, "error");
      }
    } catch (err) {
      setTestResults((r) => ({ ...r, [id]: { success: false, message: err.message } }));
    } finally {
      setTestLoading((t) => ({ ...t, [id]: false }));
    }
  };

  const deleteAccount = async (id) => {
    if (!confirm("Delete this account? This cannot be undone.")) return;
    try {
      await window.api.deleteAccount(id);
      const updated = accounts.filter((a) => a.id !== id);
      onAccountsChange(updated);
      if (activeAccount && activeAccount.id === id) setActiveAccount(updated[0] || null);
      showToast("Account deleted");
    } catch (err) {
      showToast(err.message || "Delete failed", "error");
    }
  };

  const openMt5 = async (id) => {
    try {
      const r = await window.api.mt5Url(id);
      if (r && r.url) {
        try { await navigator.clipboard.writeText(r.vnc_password || ""); } catch (e) {}
        window.open(r.url, "_blank", "noopener");
        showToast(`MT5 opening in a new tab. VNC password copied: ${r.vnc_password}`, "info");
      }
    } catch (err) {
      showToast(err.message || "MT5 not ready — start the bot first", "error");
    }
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">MT5 Accounts</h1>
          <div className="page-subtitle">{accounts.length} connected · OctaFX only</div>
        </div>
        <div style={{ marginLeft: "auto" }} className="row">
          <button className="btn primary" onClick={() => setShowAdd(true)}>{Icon.plus}Add MT5 Account</button>
        </div>
      </div>
      <div className="page-content col">
        <div className="banner info">
          <span style={{ width: 14, height: 14, color: "var(--accent)" }}>{Icon.shield}</span>
          <span>Credentials encrypted with AES-256-GCM and never returned by any API. OctaFX-Demo and OctaFX-Real supported.</span>
        </div>

        {accounts.length === 0 ? (
          <div className="panel" style={{ padding: 48, textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>
            No accounts yet — add your OctaFX MT5 account to get started
          </div>
        ) : (
          <div className="grid-3">
            {accounts.map((a) => {
              const test = testResults[a.id];
              return (
                <div key={a.id} className={`acct-card ${a.is_default ? "default" : ""}`}>
                  <div className="row between">
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 14 }}>{a.nickname || a.login}</div>
                      <div className="mono" style={{ fontSize: 11, color: "var(--text-2)", marginTop: 2 }}>#{a.login} · {a.server}</div>
                    </div>
                  </div>
                  <div className="row between" style={{ paddingTop: 12, borderTop: "1px solid var(--line)" }}>
                    <div>
                      <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".14em" }}>Balance</div>
                      <div className="mono" style={{ fontSize: 18, fontWeight: 600, marginTop: 2 }}>${a.balance.toLocaleString("en-US", { minimumFractionDigits: 2 })}</div>
                    </div>
                    <div style={{ textAlign: "right" }}>
                      <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", textTransform: "uppercase", letterSpacing: ".14em" }}>Equity</div>
                      <div className={`mono ${a.equity >= a.balance ? "pos" : ""}`} style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>${a.equity.toLocaleString("en-US", { minimumFractionDigits: 2 })}</div>
                    </div>
                  </div>
                  <div className="row" style={{ gap: 8, flexWrap: "wrap" }}>
                    {a.bot_active ? <span className="pill buy">● Bot Active</span> : <span className="pill neutral">Bot Idle</span>}
                    {connPill(a)}
                  </div>
                  {test && (
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 10, padding: "6px 8px", borderRadius: 3, background: test.success ? "var(--green-bg)" : "var(--red-bg)", color: test.success ? "var(--green)" : "var(--red)" }}>
                      {test.success ? "✓ " : "✗ "}{test.message}
                    </div>
                  )}
                  <div className="row" style={{ gap: 6 }}>
                    <button className="btn sm" style={{ flex: 1 }} onClick={() => { if (state.setActiveAccount) state.setActiveAccount(a); }}>Select</button>
                    <button className="btn ghost sm" style={{ flex: 1 }} onClick={() => testConn(a.id)} disabled={testLoading[a.id]}>
                      {testLoading[a.id] ? "Testing…" : "Test Connection"}
                    </button>
                    <button className="btn ghost sm" style={{ flex: 1 }} onClick={() => openMt5(a.id)} title="Open the MT5 terminal in your browser">Open MT5</button>
                    <button className="icon-btn" style={{ width: 28, height: 28, color: "var(--red)" }} onClick={() => deleteAccount(a.id)} disabled={a.bot_active}>{Icon.x}</button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {showAdd && (
        <div className="modal-backdrop" onClick={() => setShowAdd(false)}>
          <div className="modal" onClick={(e) => e.stopPropagation()} style={{ width: 480 }}>
            <h3>Connect MT5 Account</h3>
            <p style={{ color: "var(--text-2)", fontSize: 12 }}>Credentials are encrypted with AES-256-GCM. Only OctaFX servers are supported.</p>
            {addError && <div className="auth-error">{addError}</div>}
            <div className="field"><label>Account Nickname (optional)</label><input placeholder="e.g. Main Demo" value={form.nickname} onChange={(e) => setForm({ ...form, nickname: e.target.value })} /></div>
            <div className="field-row">
              <div className="field"><label>MT5 Login</label><input placeholder="12345678" value={form.login} onChange={(e) => setForm({ ...form, login: e.target.value })} /></div>
              <div className="field">
                <label>Server</label>
                <select value={form.server} onChange={(e) => setForm({ ...form, server: e.target.value })}>
                  <option value="OctaFX-Demo">OctaFX-Demo</option>
                  <option value="OctaFX-Real">OctaFX-Real</option>
                </select>
              </div>
            </div>
            <div className="field"><label>Password</label><input type="password" placeholder="••••••••" value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} /></div>
            <div className="field"><label>MT5 Terminal Path (leave blank — auto-assigned from the server's pool)</label><input placeholder="auto-assigned (e.g. C:\\MT5-2\\terminal64.exe)" value={form.terminal_path} onChange={(e) => setForm({ ...form, terminal_path: e.target.value })} /></div>
            <div className="modal-actions">
              <button className="btn ghost" onClick={() => setShowAdd(false)}>Cancel</button>
              <button className="btn primary" onClick={addAccount} disabled={addLoading}>{addLoading ? "Connecting…" : "Add Account"}</button>
            </div>
          </div>
        </div>
      )}
      {toast && <div className={`toast ${toast.type}`}>{toast.msg}</div>}
    </>
  );
}

function Profile({ user, onUserUpdate }) {
  const [tab, setTab] = useState("profile");
  const [form, setForm] = useState({ name: user ? user.name : "", timezone: user ? user.timezone : "UTC", currency: user ? user.currency : "USD" });
  const [saving, setSaving] = useState(false);
  const [toast, setToast] = useState(null);

  const save = async () => {
    setSaving(true);
    try {
      const updated = await window.api.updateMe(form);
      if (updated) { onUserUpdate(updated); window.Auth.setUser(updated); }
      setToast({ msg: "Profile saved", type: "success" });
      setTimeout(() => setToast(null), 2400);
    } catch (err) {
      setToast({ msg: err.message || "Save failed", type: "error" });
      setTimeout(() => setToast(null), 3000);
    } finally {
      setSaving(false);
    }
  };

  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Profile & Preferences</h1>
          <div className="page-subtitle">{user ? user.email : "—"}</div>
        </div>
      </div>
      <div className="page-content col">
        <div className="tabs">
          {["profile", "security", "notifications", "legal"].map((t) => (
            <button key={t} className={`tab ${tab === t ? "active" : ""}`} onClick={() => setTab(t)}>{t}</button>
          ))}
        </div>
        {tab === "profile" && (
          <div className="grid-2">
            <div className="panel">
              <div className="panel-header">
                <div className="panel-title">Personal</div>
                <button className="btn sm primary" onClick={save} disabled={saving}>{saving ? "Saving…" : "Save"}</button>
              </div>
              <div style={{ padding: 18 }}>
                <div className="field"><label>Display Name</label><input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
                <div className="field"><label>Email</label><input value={user ? user.email : ""} disabled /></div>
                <div className="field-row">
                  <div className="field"><label>Timezone</label>
                    <select value={form.timezone} onChange={(e) => setForm({ ...form, timezone: e.target.value })}>
                      <option value="UTC">UTC</option>
                      <option value="America/New_York">America/New York (UTC-5)</option>
                      <option value="Europe/London">Europe/London (UTC+0)</option>
                      <option value="Asia/Singapore">Asia/Singapore (UTC+8)</option>
                    </select>
                  </div>
                  <div className="field"><label>Currency</label>
                    <select value={form.currency} onChange={(e) => setForm({ ...form, currency: e.target.value })}>
                      <option value="USD">USD ($)</option>
                      <option value="EUR">EUR (€)</option>
                      <option value="GBP">GBP (£)</option>
                    </select>
                  </div>
                </div>
              </div>
            </div>
            <div className="panel">
              <div className="panel-header"><div className="panel-title">Plan</div></div>
              <div style={{ padding: 24, textAlign: "center" }}>
                <div className="mono" style={{ fontSize: 10, color: "var(--text-2)", letterSpacing: ".18em", textTransform: "uppercase" }}>Current Plan</div>
                <div style={{ fontSize: 36, fontWeight: 700, color: "var(--accent)", letterSpacing: "-0.02em", margin: "10px 0", textShadow: "0 0 20px var(--accent-glow)" }}>FREE</div>
                <div style={{ color: "var(--text-1)", fontSize: 13, maxWidth: 320, margin: "0 auto" }}>Forever. No credit card. Unlimited accounts. All features included.</div>
                <div style={{ marginTop: 18, padding: "12px 14px", background: "var(--bg-2)", borderRadius: 4, fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-2)", textAlign: "left" }}>
                  ● Unlimited MT5 accounts<br/>
                  ● 24/5 automated XAUUSD trading<br/>
                  ● EMA 8/21 M15 scalping strategy<br/>
                  ● Full analytics & signal log<br/>
                  ● No commissions, ever
                </div>
              </div>
            </div>
          </div>
        )}
        {tab === "security" && (
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Security</div></div>
            <div style={{ padding: 4 }}>
              <div className="kv"><span className="k">Last Login</span><span className="v">This session</span></div>
              <div className="kv"><span className="k">Sign Out</span><span className="v"><button className="btn danger sm" onClick={() => window.Auth.logout()}>Sign Out</button></span></div>
            </div>
          </div>
        )}
        {tab === "notifications" && (
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Notifications</div><span style={{ fontSize: 11, color: "var(--text-3)" }}>Coming soon</span></div>
            <div style={{ padding: 32, textAlign: "center", color: "var(--text-3)", fontFamily: "var(--font-mono)", fontSize: 11 }}>Email notifications in a future release</div>
          </div>
        )}
        {tab === "legal" && (
          <div className="panel">
            <div className="panel-header"><div className="panel-title">Legal & Data</div></div>
            <div style={{ padding: 4 }}>
              <div className="kv"><span className="k">Risk Disclosure</span><span className="v"><span style={{ fontSize: 11, color: "var(--text-2)" }}>Trading involves substantial risk of loss</span></span></div>
              <div className="kv"><span className="k" style={{ color: "var(--red)" }}>Delete Account</span><span className="v"><button className="btn danger sm">Request Deletion</button></span></div>
            </div>
          </div>
        )}
      </div>
      {toast && <div className={`toast ${toast.type}`}>{toast.msg}</div>}
    </>
  );
}

window.BotSettings = BotSettings;
window.MT5Accounts = MT5Accounts;
window.Profile = Profile;
