/* Meridian — App Screens: Analytics, Positions, Withdraw, Account, Help, Instrument */

/* ═══════ Analytics ═══════ */
function AnalyticsScreen({ onNavigate }) {
  const [timeWindow, setTimeWindow] = useState("30d");
  const dailyBars = [40,60,-30,80,-20,55,70,-25,90,45,-35,65,50,85,-15,60,75,-40,95,30,55,70,-45,65,50,80,-20,55,90,40];
  const instruments = [
    { name: "EURUSD", val: "+$612" }, { name: "XAUUSD", val: "+$487" },
    { name: "GBPJPY", val: "+$244" }, { name: "USDJPY", val: "+$118" },
    { name: "BTCUSD", val: "−$94" }, { name: "ETHUSD", val: "−$188" },
  ];
  const sessions = [
    { name: "London", val: "+$742" }, { name: "New York", val: "+$558" },
    { name: "Tokyo", val: "+$614" }, { name: "Sydney", val: "+$175" },
  ];

  return (
    <div className="app-page" data-screen-label="Analytics">
      <div className="page-head" style={{ marginBottom: "var(--space-5)" }}>
        <h1 style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)" }}>Analytics</h1>
        <div style={{ display: "flex", alignItems: "center", gap: "var(--space-3)", flexWrap: "wrap" }}>
          <div className="m-chips">
            {["7d","30d","90d","YTD","Custom"].map(w => (
              <button key={w} className={`m-chip ${timeWindow === w ? "active" : ""}`} onClick={() => setTimeWindow(w)}>{w}</button>
            ))}
          </div>
          <button className="m-btn m-btn-ghost" style={{ fontSize: 13, padding: "6px 14px" }}>Export CSV</button>
        </div>
      </div>

      {/* Top stats */}
      <div className="stat-grid" style={{ marginBottom: "var(--space-5)" }}>
        {[
          { label: "Net P&L", val: "+$1,881", delta: "▲ $178 vs prior", up: true },
          { label: "Win rate", val: "68%", delta: "▲ +0.9% vs prior", up: true },
          { label: "Profit factor", val: "4.13", delta: "▲ +1.70 vs prior", up: true },
          { label: "Avg R", val: "1.93R", delta: "▲ +1.78 vs prior", up: true },
          { label: "Max drawdown", val: "−$253", delta: "▼ −$61 vs prior", down: true },
          { label: "Total trades", val: "22", delta: "▲ +5 vs prior", up: true },
        ].map((s, i) => (
          <div key={i} className="stat-card">
            <div className="stat-card-label">{s.label}</div>
            <div className={`stat-card-value ${s.val.startsWith("−") ? "down" : ""}`}>{s.val}</div>
            <div className={`stat-card-delta ${s.up ? "up" : s.down ? "down" : ""}`}>{s.delta}</div>
          </div>
        ))}
      </div>

      {/* Cumulative P&L */}
      <div className="chart-placeholder" style={{ marginBottom: "var(--space-5)", minHeight: 240 }}>
        <div className="chart-placeholder-header">
          <span className="label-upper">Cumulative P&L</span>
          <div className="m-chips" style={{ gap: 4 }}>
            <button className="m-chip active" style={{ fontSize: 11, padding: "3px 8px" }}>$</button>
            <button className="m-chip" style={{ fontSize: 11, padding: "3px 8px" }}>R</button>
          </div>
        </div>
        <div style={{ flex: 1, display: "flex", alignItems: "flex-end", gap: 2, borderBottom: "1px solid var(--border)", paddingTop: "var(--space-4)" }}>
          {Array.from({ length: 40 }, (_, i) => {
            const h = 20 + Math.sin(i * 0.3) * 15 + (i / 40) * 60;
            return <div key={i} style={{ flex: 1, height: `${Math.max(5, h)}%`, background: "var(--accent)", opacity: 0.5 + (i / 40) * 0.5, borderRadius: "1px 1px 0 0" }}></div>;
          })}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", fontSize: "var(--text-xs)", color: "var(--fg-subtle)", marginTop: 4 }}>
          <span>Apr 14</span><span>May 13</span>
        </div>
      </div>

      {/* Performance breakdown */}
      <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-4)", letterSpacing: "var(--track-label)", textTransform: "uppercase", fontSize: "var(--text-xs)", color: "var(--fg-subtle)" }}>Performance breakdown</h3>
      <div className="grid-2" style={{ marginBottom: "var(--space-5)" }}>
        <div className="m-card" style={{ padding: "var(--space-4)" }}>
          <span className="label-upper" style={{ marginBottom: "var(--space-3)", display: "block" }}>By instrument</span>
          {instruments.map((inst, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 0", fontSize: "var(--text-sm)" }}>
              <span className="tnum" style={{ width: 60, fontWeight: "var(--w-medium)" }}>{inst.name}</span>
              <div style={{ flex: 1, height: 12, background: "var(--bg-raised)", borderRadius: 2, overflow: "hidden" }}>
                <div style={{ width: `${50 + Math.random() * 50}%`, height: "100%", background: inst.val.startsWith("−") ? "var(--sell)" : "var(--accent)", borderRadius: 2 }}></div>
              </div>
              <span className={`tnum ${inst.val.startsWith("−") ? "down" : "up"}`} style={{ width: 55, textAlign: "right", fontSize: "var(--text-xs)" }}>{inst.val}</span>
            </div>
          ))}
        </div>
        <div className="m-card" style={{ padding: "var(--space-4)" }}>
          <span className="label-upper" style={{ marginBottom: "var(--space-3)", display: "block" }}>By session</span>
          {sessions.map((s, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", gap: 8, padding: "4px 0", fontSize: "var(--text-sm)" }}>
              <span style={{ width: 70, fontWeight: "var(--w-medium)" }}>{s.name}</span>
              <div style={{ flex: 1, height: 12, background: "var(--bg-raised)", borderRadius: 2, overflow: "hidden" }}>
                <div style={{ width: `${40 + Math.random() * 60}%`, height: "100%", background: "var(--accent)", borderRadius: 2 }}></div>
              </div>
              <span className="tnum up" style={{ width: 55, textAlign: "right", fontSize: "var(--text-xs)" }}>{s.val}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Risk section */}
      <h3 style={{ letterSpacing: "var(--track-label)", textTransform: "uppercase", fontSize: "var(--text-xs)", color: "var(--fg-subtle)", marginBottom: "var(--space-4)" }}>Risk</h3>
      <div className="stat-grid" style={{ marginBottom: "var(--space-5)" }}>
        <div className="stat-card"><div className="stat-card-label">Drawdown</div><div className="stat-card-value down">−$253</div></div>
        <div className="stat-card"><div className="stat-card-label">Risk per trade</div><div className="stat-card-value">% of account</div></div>
        <div className="stat-card">
          <div className="stat-card-label">Streaks</div>
          <div style={{ display: "flex", gap: "var(--space-6)", marginTop: 4 }}>
            <div><div className="label-upper" style={{ fontSize: 9 }}>Current</div><div className="tnum" style={{ fontWeight: "var(--w-semibold)" }}>4W</div></div>
            <div><div className="label-upper" style={{ fontSize: 9 }}>Longest win</div><div className="tnum" style={{ fontWeight: "var(--w-semibold)" }}>7W</div></div>
            <div><div className="label-upper" style={{ fontSize: 9 }}>Longest lose</div><div className="tnum" style={{ fontWeight: "var(--w-semibold)" }}>4L</div></div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ═══════ Positions ═══════ */
function PositionCard({ p, onNavigate }) {
  const [open, setOpen] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const plClass = parseFloat(p.pl) > 0 ? "up" : parseFloat(p.pl) < 0 ? "down" : "";
  const receipt = `0x${p.inst.slice(0, 2).toUpperCase()}…${(p.id * 7 + 11).toString().padStart(2, "0")}`;
  const rows = [
    ["Side", p.side], ["Size", p.size], ["Entry", p.entry], ["Mark", p.mark],
    ["Funding (8h)", p.funding], ["Exchange", p.exchange],
  ];
  return (
    <div className={`pos-card ${open ? "open" : ""}`} onClick={() => setOpen(o => !o)}>
      <div className="pos-card-top">
        <span className="pos-card-inst">{p.inst}</span>
        <span className="pos-card-top-right">
          <span className={`pos-card-pl ${plClass}`}>{p.pl}</span>
          <span className={`pos-card-caret ${open ? "open" : ""}`}><Icon name="chevDown" size={16} color="var(--fg-subtle)" /></span>
        </span>
      </div>
      <div className="pos-card-sub">{p.side} · {p.size}</div>
      {open && (
        <div className="pos-card-detail" onClick={e => e.stopPropagation()}>
          {rows.map(([label, val]) => (
            <div className="pos-kv" key={label}>
              <span className="pos-kv-label">{label}</span>
              <span className="pos-kv-val">{val}</span>
            </div>
          ))}
          <div className="pos-kv">
            <span className="pos-kv-label">Receipt</span>
            <a className="pos-kv-link" href="#" onClick={e => { e.preventDefault(); onNavigate("instrument"); }}>{receipt}</a>
          </div>
          <div className="pos-card-actions">
            <button className="m-btn m-btn-ghost" style={{ flex: 1, fontSize: 14 }} onClick={() => onNavigate("instrument")}>Open detail</button>
            {confirming
              ? <button className="m-btn m-btn-dark" style={{ flex: 1, fontSize: 14, background: "var(--sell)", borderColor: "var(--sell)" }} onClick={() => setConfirming(false)}>Confirm close</button>
              : <button className="m-btn m-btn-dark" style={{ flex: 1, fontSize: 14 }} onClick={() => setConfirming(true)}>Close</button>}
          </div>
        </div>
      )}
    </div>
  );
}

function PositionsScreen({ onNavigate }) {
  const [tab, setTab] = useState("open");
  const [filter, setFilter] = useState("All");
  const [closingId, setClosingId] = useState(null);

  const positions = [
    { id: 1, inst: "EURUSD", side: "Long", size: "0.10", entry: "1.0823", mark: "1.0831", pl: "+8.20", funding: "0.04", exchange: "Meridian One" },
    { id: 2, inst: "XAUUSD", side: "Short", size: "0.05", entry: "2,341.50", mark: "2,338.70", pl: "+4.14", funding: "0.02", exchange: "Meridian One" },
    { id: 3, inst: "BTCUSD", side: "Long", size: "0.01", entry: "68,420.00", mark: "68,420.00", pl: "0.00", funding: "0.01", exchange: "Meridian One" },
    { id: 4, inst: "GBPUSD", side: "Short", size: "0.25", entry: "1.2614", mark: "1.2598", pl: "+40.00", funding: "0.18", exchange: "Meridian One" },
    { id: 5, inst: "USDJPY", side: "Long", size: "0.20", entry: "151.20", mark: "151.42", pl: "+29.10", funding: "0.06", exchange: "Meridian One" },
    { id: 6, inst: "AUDUSD", side: "Short", size: "0.15", entry: "0.6588", mark: "0.6571", pl: "+25.50", funding: "0.03", exchange: "Meridian One" },
    { id: 7, inst: "ETHUSD", side: "Long", size: "0.10", entry: "3,290.00", mark: "3,318.50", pl: "+28.50", funding: "0.05", exchange: "Meridian One" },
    { id: 8, inst: "US500", side: "Long", size: "0.50", entry: "5,210.00", mark: "5,224.40", pl: "+72.00", funding: "0.10", exchange: "Meridian One" },
  ];

  const filters = ["All", "EURUSD", "XAUUSD", "BTCUSD", "Today"];
  const shown = filter === "All" ? positions : positions.filter(p => p.inst === filter || filter === "Today");

  return (
    <div className="app-page" data-screen-label="Positions">
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-4)" }}>
        <h1 style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)" }}>Positions</h1>
        <button className="m-btn m-btn-ghost" style={{ fontSize: 13, padding: "6px 14px" }}>Export CSV</button>
      </div>
      <div className="m-tabs">
        <button className={`m-tab ${tab === "open" ? "active" : ""}`} onClick={() => setTab("open")}>Open positions</button>
        <button className={`m-tab ${tab === "closed" ? "active" : ""}`} onClick={() => setTab("closed")}>Closed positions</button>
      </div>
      <div className="m-chips" style={{ marginBottom: "var(--space-4)" }}>
        {filters.map((f, i) => (
          <React.Fragment key={f}>
            {f === "Today" && <div className="m-chip-divider"></div>}
            <button className={`m-chip ${filter === f ? "active" : ""}`} onClick={() => setFilter(f)}>{f}</button>
          </React.Fragment>
        ))}
      </div>

      {/* Mobile: stacked cards */}
      <div className="pos-cards">
        {shown.map(p => <PositionCard key={p.id} p={p} onNavigate={onNavigate} />)}
      </div>

      {/* Desktop: table */}
      <div className="m-card pos-table-wrap" style={{ padding: 0, overflow: "auto" }}>
        <table className="m-table">
          <thead><tr><th>Instrument</th><th>Side</th><th>Size</th><th>Entry</th><th>Mark</th><th>P/L</th><th>Funding</th><th>Exchange</th><th>Action</th><th></th></tr></thead>
          <tbody>
            {shown.map(p => (
              <tr key={p.id}>
                <td><a href="#" onClick={e => { e.preventDefault(); onNavigate("instrument"); }}>{p.inst}</a></td>
                <td>{p.side}</td>
                <td className="tnum">{p.size}</td>
                <td className="tnum">{p.entry}</td>
                <td className="tnum">{p.mark}</td>
                <td className={`tnum ${parseFloat(p.pl) > 0 ? "up" : parseFloat(p.pl) < 0 ? "down" : ""}`}>{p.pl}</td>
                <td className="tnum">{p.funding}</td>
                <td>{p.exchange}</td>
                <td>
                  {closingId === p.id
                    ? <button className="m-btn m-btn-ghost" style={{ fontSize: 12, padding: "4px 12px", color: "var(--sell)" }} onClick={() => setClosingId(null)}>Confirm close</button>
                    : <button className="m-btn m-btn-ghost" style={{ fontSize: 12, padding: "4px 12px" }} onClick={() => setClosingId(p.id)}>Close</button>
                  }
                </td>
                <td><a href="#" style={{ fontSize: "var(--text-xs)" }}>View tx</a></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ═══════ Withdraw ═══════ */
function WithdrawScreen({ onNavigate }) {
  const [amount, setAmount] = useState("");
  const [addressChecked, setAddressChecked] = useState(false);
  const history = [
    { date: "May 5, 2026", amount: "$100.00", to: "0xAB...12", status: "Sending · 22s" },
    { date: "Apr 30, 2026", amount: "$800.00", to: "0xAB...12", status: "Completed" },
    { date: "Apr 24, 2026", amount: "$250.00", to: "0xAB...12", status: "Completed" },
    { date: "Apr 17, 2026", amount: "$1,200.00", to: "0xAB...12", status: "Completed" },
    { date: "Apr 10, 2026", amount: "$300.00", to: "0xAB...12", status: "Completed" },
  ];

  return (
    <div className="app-page" data-screen-label="Withdraw">
      <div className="breadcrumb">Account › Withdraw</div>
      <h1 style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-6)" }}>Withdraw funds</h1>
      <div className="two-col">
        <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
          <div className="m-card">
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Send to an exchange or a wallet</h3>
            <p style={{ fontSize: "var(--text-sm)", fontWeight: "var(--w-semibold)", marginBottom: 4 }}>Transfers cannot be reversed. Check addresses twice.</p>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", lineHeight: 1.6 }}>Withdrawals leave Meridian as soon as you sign. We can't pause, queue, or claw them back.</p>
          </div>
          <Accordion title="How long does this take?"><p>Most withdrawals confirm in under 1 minute on Arbitrum. If the network is congested it may take up to 15 minutes.</p></Accordion>
          <Accordion title="What if I sent to the wrong address?"><p>On-chain transactions are irreversible. Meridian cannot recover funds sent to the wrong address. Always double-check before confirming.</p></Accordion>
          <Accordion title="Can Meridian pause this withdrawal?"><p>No. The withdrawal is a direct on-chain transaction from your account. No one — including Meridian — can block or pause it.</p></Accordion>
        </div>
        <div>
          <div className="m-card" style={{ marginBottom: "var(--space-5)" }}>
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-4)" }}>Pre-check summary</h3>
            <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-4)" }}>
              <div>
                <span className="m-input-label">Destination</span>
                <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 4 }}>
                  <span className="tnum" style={{ fontSize: "var(--text-sm)", wordBreak: "break-all" }}>0xAB12CD34EF56789012345678901234567890ABCD</span>
                  <a href="#" style={{ fontSize: "var(--text-sm)", whiteSpace: "nowrap" }}>Change</a>
                </div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Network</span>
                <span style={{ fontSize: "var(--text-sm)", fontWeight: "var(--w-semibold)" }}>Exchange or wallet</span>
              </div>
              <div>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 4 }}>
                  <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Amount</span>
                  <span className="tnum" style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Available $12,450.32</span>
                </div>
                <div style={{ display: "flex", gap: 0 }}>
                  <input className="m-input tnum" value={amount} onChange={e => setAmount(e.target.value)} placeholder="0.00" style={{ flex: 1, borderRadius: "var(--radius-sm) 0 0 var(--radius-sm)", borderRight: "none" }} />
                  <button className="m-btn m-btn-ghost" style={{ borderRadius: "0 var(--radius-sm) var(--radius-sm) 0", padding: "10px 14px", fontSize: 13 }} onClick={() => setAmount("12450.32")}>MAX</button>
                </div>
              </div>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>ETA</span>
                <span className="tnum" style={{ fontSize: "var(--text-sm)", fontWeight: "var(--w-semibold)" }}>~1 minute</span>
              </div>
            </div>
            <p style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)", fontStyle: "italic", marginTop: "var(--space-4)" }}>Funds will leave Meridian. This cannot be undone once confirmed.</p>
          </div>
          <div className={`m-checkbox ${addressChecked ? "checked" : ""}`} onClick={() => setAddressChecked(!addressChecked)} style={{ marginBottom: "var(--space-4)" }}>
            <div className="m-check-box">{addressChecked && <Icon name="check" size={14} stroke={3} color="#fff" />}</div>
            <span style={{ fontSize: "var(--text-sm)", fontWeight: "var(--w-semibold)" }}>I have checked the destination address.</span>
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <button className="m-btn m-btn-ghost">Cancel</button>
            <button className="m-btn m-btn-primary m-btn-lg" disabled={!addressChecked || !amount}>Withdraw</button>
          </div>
          <div style={{ textAlign: "center", marginTop: "var(--space-2)" }}>
            <a href="#" onClick={e => { e.preventDefault(); onNavigate("positions"); }} style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>View positions first</a>
          </div>
        </div>
      </div>

      <h2 style={{ fontSize: "var(--text-h3)", fontWeight: "var(--w-semibold)", marginTop: "var(--space-8)", marginBottom: "var(--space-4)" }}>Withdrawal history</h2>
      <div className="m-card" style={{ padding: 0, overflow: "hidden" }}>
        <table className="m-table">
          <tbody>
            {history.map((h, i) => (
              <tr key={i}>
                <td style={{ color: "var(--fg-muted)" }}>{h.date}</td>
                <td className="tnum" style={{ fontWeight: "var(--w-semibold)" }}>{h.amount}</td>
                <td className="tnum" style={{ color: "var(--fg-muted)" }}>to {h.to}</td>
                <td style={{ textAlign: "right" }}>
                  <span style={{ fontSize: "var(--text-xs)", padding: "3px 10px", borderRadius: "var(--radius-pill)", border: "1px solid var(--border)", color: h.status.includes("Sending") ? "var(--warning)" : "var(--fg-muted)" }}>{h.status}</span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* ═══════ Account ═══════ */
function AccountScreen({ onNavigate }) {
  const [partialFills, setPartialFills] = useState("no");
  return (
    <div className="app-page" data-screen-label="Account">
      <div className="account-layout">
        {/* Page nav */}
        <div className="account-toc">
          <div className="label-upper" style={{ marginBottom: "var(--space-3)" }}>On this page</div>
          <div className="account-toc-links">
            {["Accounts","Agent key status","MT5 account","Trading preferences","Emergency close","Settings"].map(s => (
              <a key={s} href={`#${s.toLowerCase().replace(/\s/g,"-")}`} className="account-toc-link">{s}</a>
            ))}
          </div>
        </div>
        <div style={{ flex: 1, maxWidth: 700 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "var(--space-6)" }}>
            <h1 style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)" }}>Account</h1>
            <button className="m-btn m-btn-ghost" style={{ fontSize: 13 }}>+ Open new account</button>
          </div>

          {/* Accounts */}
          <h2 id="accounts" style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-4)" }}>Accounts</h2>
          <div className="grid-2" style={{ marginBottom: "var(--space-8)" }}>
            <div className="m-card-highlight" style={{ padding: "var(--space-5)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "var(--space-2)" }}>
                <span className="label-upper">Real · Standard <span style={{ background: "var(--accent)", color: "#fff", padding: "2px 8px", borderRadius: "var(--radius-pill)", fontSize: 10, marginLeft: 6 }}>Active</span></span>
                <span className="tnum" style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)" }}>#50047231</span>
              </div>
              <div className="tnum" style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>12,450.32 <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>USD</span></div>
              <div style={{ display: "flex", gap: "var(--space-6)", fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>
                <span>Equity <strong className="tnum" style={{ color: "var(--fg)" }}>12,488.32</strong></span>
                <span>Leverage <strong className="tnum" style={{ color: "var(--fg)" }}>1:500</strong></span>
              </div>
              <button className="m-btn m-btn-ghost m-btn-full" style={{ fontSize: 13 }}>Show MT5 credentials</button>
            </div>
            <div className="m-card" style={{ padding: "var(--space-5)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "var(--space-2)" }}>
                <span className="label-upper">Demo · Standard</span>
                <span className="tnum" style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)" }}>#50047301</span>
              </div>
              <div className="tnum" style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>10,000.00 <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>USD</span></div>
              <div style={{ display: "flex", gap: "var(--space-6)", fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>
                <span>Equity <strong className="tnum" style={{ color: "var(--fg)" }}>10,142.50</strong></span>
                <span>Leverage <strong className="tnum" style={{ color: "var(--fg)" }}>1:500</strong></span>
              </div>
              <button className="m-btn m-btn-ghost m-btn-full" style={{ fontSize: 13, marginBottom: 8 }}>Switch to this account</button>
              <button className="m-btn m-btn-ghost m-btn-full" style={{ fontSize: 13 }}>Show MT5 credentials</button>
            </div>
          </div>

          {/* Agent key status */}
          <div className="m-card" style={{ marginBottom: "var(--space-5)" }} id="agent-key-status">
            <span className="label-upper" style={{ display: "block", marginBottom: "var(--space-3)" }}>Account settings</span>
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Agent key status</h3>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>Status: <span className="m-status-dot connected" style={{ display: "inline-block", width: 7, height: 7, marginRight: 4 }}></span> <strong style={{ color: "var(--fg)" }}>Active.</strong> This key can place trades. It cannot move your money.</p>
            <button className="m-btn m-btn-ghost" style={{ marginBottom: 8 }}>Re-authorize</button>
            <div><a href="#" style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Revoke this key</a> — pauses trading. Your money stays where it is.</div>
          </div>

          {/* MT5 account */}
          <div className="m-card" style={{ marginBottom: "var(--space-5)" }} id="mt5-account">
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>MT5 account</h3>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-2)" }}>
              Status: <span className="m-status-dot connected" style={{ display: "inline-block", width: 7, height: 7, marginRight: 4 }}></span> <strong style={{ color: "var(--fg)" }}>Connected</strong> · Server: <span className="tnum">meridian-live-01</span>
            </p>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Connection problem? <a href="#">See diagnostics</a></p>
          </div>

          {/* Trading preferences */}
          <div className="m-card" style={{ marginBottom: "var(--space-5)" }} id="trading-preferences">
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Trading preferences</h3>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>Allow partial fills?</p>
            <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)" }}>
              <div className={`m-radio ${partialFills === "no" ? "selected" : ""}`} onClick={() => setPartialFills("no")}>
                <div className="m-radio-dot"></div>
                <div>
                  <span style={{ fontWeight: "var(--w-semibold)" }}>No, do not allow partial fills </span>
                  <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>default</span>
                  <div style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Orders that can't fill in full will be rejected.</div>
                </div>
              </div>
              <div className={`m-radio ${partialFills === "yes" ? "selected" : ""}`} onClick={() => setPartialFills("yes")}>
                <div className="m-radio-dot"></div>
                <div>
                  <span style={{ fontWeight: "var(--w-semibold)" }}>Yes, allow partial fills</span>
                  <div style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Orders may execute in pieces at different prices.</div>
                </div>
              </div>
            </div>
            <p style={{ fontSize: "var(--text-xs)", color: "var(--fg-subtle)", marginTop: "var(--space-3)" }}>Changes apply to new orders only. <a href="#">Learn more</a></p>
          </div>

          {/* Emergency close */}
          <div className="m-card" style={{ marginBottom: "var(--space-5)" }} id="emergency-close">
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Emergency close</h3>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>Open positions: <strong style={{ color: "var(--fg)" }}>3</strong></p>
            <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>Close any position from the positions dashboard, works even if MT5 is down.</p>
            <button className="m-btn m-btn-ghost" onClick={() => onNavigate("positions")}>Close positions</button>
          </div>

          {/* Settings */}
          <div className="m-card" id="settings">
            <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-4)" }}>Settings</h3>
            <ul style={{ listStyle: "disc", paddingLeft: 18, fontSize: "var(--text-sm)", color: "var(--fg-muted)", display: "flex", flexDirection: "column", gap: 6 }}>
              <li>Language: <strong style={{ color: "var(--fg)" }}>English</strong></li>
              <li>Notifications: <strong style={{ color: "var(--fg)" }}>Email + push</strong></li>
              <li>Session: <a href="#">Sign out</a></li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ═══════ Help ═══════ */
function HelpScreen({ onNavigate }) {
  return (
    <div className="app-page" data-screen-label="Help" style={{ maxWidth: 700 }}>
      <h1 style={{ fontSize: "var(--text-h2)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-5)" }}>Help</h1>
      <div style={{ display: "flex", gap: 0, marginBottom: "var(--space-2)" }}>
        <input className="m-input" placeholder={"Ask anything \u2014 \"my deposit didn\u2019t arrive\", \"how do I withdraw?\""} style={{ flex: 1, borderRadius: "var(--radius-sm) 0 0 var(--radius-sm)", borderRight: "none" }} />
        <button className="m-btn m-btn-dark" style={{ borderRadius: "0 var(--radius-sm) var(--radius-sm) 0", padding: "12px 20px" }}>Ask</button>
      </div>
      <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-subtle)", marginBottom: "var(--space-6)" }}>Or browse common questions below.</p>

      <div className="m-card" style={{ marginBottom: "var(--space-6)", background: "var(--bg-elevated)" }}>
        <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>What to do if this goes down</h3>
        <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)", lineHeight: 1.6 }}>If MT5 or the exchange is degraded, your positions are still here. Close them from the dashboard.</p>
        <button className="m-btn m-btn-dark" onClick={() => onNavigate("positions")}>Open positions dashboard</button>
      </div>

      <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Fix something that broke</h3>
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)", marginBottom: "var(--space-6)" }}>
        {["My deposit hasn't arrived","MT5 won't connect / login fails","I can't withdraw / withdrawal looks stuck","I closed the popup / rejected a signature"].map(q => (
          <Accordion key={q} title={q}><p>Step-by-step troubleshooting guide for this issue. Check our status page first, then try the specific steps listed here.</p></Accordion>
        ))}
      </div>

      <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Understand how Meridian works</h3>
      <div style={{ display: "flex", flexDirection: "column", gap: "var(--space-2)", marginBottom: "var(--space-6)" }}>
        {["How does Meridian protect my money?","What is an agent key?","Where do my trades actually happen?","What is funding rate?","Where are my dollars held?"].map(q => (
          <Accordion key={q} title={q}><p>Detailed explanation of this concept and how it applies to your Meridian account.</p></Accordion>
        ))}
      </div>

      <div className="m-card" style={{ marginBottom: "var(--space-4)" }}>
        <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>Talk to the community</h3>
        <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>Get answers from other traders and the Meridian team in real-time.</p>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "var(--space-3)" }}>
          <button className="m-btn m-btn-ghost">Join Discord</button>
          <button className="m-btn m-btn-ghost">Open Telegram</button>
        </div>
      </div>

      <div className="m-card">
        <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>Still stuck? Talk to a human.</h3>
        <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-4)" }}>Chat opens in your browser. Replies typically within an hour during market hours.</p>
        <button className="m-btn m-btn-ghost">Open chat</button>
      </div>
    </div>
  );
}

/* ═══════ Instrument Detail ═══════ */
function InstrumentScreen({ onNavigate }) {
  return (
    <div className="app-page" data-screen-label="Instrument Detail" style={{ maxWidth: 900 }}>
      <div className="breadcrumb"><a href="#" onClick={e => { e.preventDefault(); onNavigate("dashboard"); }}>Dashboard</a> › EURUSD</div>
      <h1 style={{ fontSize: "var(--text-h1)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-2)" }}>EURUSD</h1>
      <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-6)" }}>
        Live: <strong className="tnum" style={{ color: "var(--fg)" }}>1.0823</strong> · 24h: <span className="up">+0.12%</span> · Meridian One
      </p>

      <div className="m-card" style={{ marginBottom: "var(--space-5)", background: "var(--bg-elevated)" }}>
        <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-3)" }}>Trading happens in MetaTrader 5</h3>
        <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)", marginBottom: "var(--space-5)", lineHeight: 1.6 }}>
          Orders for EURUSD are placed inside your MetaTrader 5 app, not here. To trade, open MT5 and use the symbol <strong style={{ color: "var(--fg)" }}>EURUSD</strong>.
        </p>
        <div className="grid-2" style={{ gap: "var(--space-3)" }}>
          <button className="m-btn m-btn-dark m-btn-lg">Open MetaTrader 5</button>
          <button className="m-btn m-btn-ghost m-btn-lg">Show MT5 setup</button>
        </div>
      </div>

      <div className="m-card" style={{ marginBottom: "var(--space-5)" }}>
        <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-4)" }}>MT5 setup reference</h3>
        {[
          { label: "Server", val: "meridian-live" },
          { label: "Login", val: "12345678" },
          { label: "Symbol", val: "EURUSD" },
        ].map((r, i) => (
          <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "10px 0", borderBottom: "1px dashed var(--border)" }}>
            <span style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>{r.label}</span>
            <span className="tnum" style={{ fontWeight: "var(--w-semibold)" }}>{r.val}</span>
          </div>
        ))}
        <a href="#" style={{ fontSize: "var(--text-sm)", display: "block", marginTop: "var(--space-3)" }}>Copy credentials again</a>
      </div>

      <h3 style={{ fontSize: "var(--text-h4)", fontWeight: "var(--w-semibold)", marginBottom: "var(--space-4)" }}>Other things you can do here</h3>
      <div className="grid-2">
        <div className="m-card" style={{ cursor: "pointer" }} onClick={() => onNavigate("positions")}>
          <h4 style={{ fontWeight: "var(--w-semibold)", marginBottom: 4 }}>View your positions</h4>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>See open trades and P/L.</p>
        </div>
        <div className="m-card" style={{ cursor: "pointer" }} onClick={() => onNavigate("account")}>
          <h4 style={{ fontWeight: "var(--w-semibold)", marginBottom: 4 }}>Manage your account</h4>
          <p style={{ fontSize: "var(--text-sm)", color: "var(--fg-muted)" }}>Wallet, deposits, withdrawals.</p>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { AnalyticsScreen, PositionsScreen, WithdrawScreen, AccountScreen, HelpScreen, InstrumentScreen });
