// Trading view — full layout with candlestick chart + privacy fog
function TradingView() {
  const [reveal, setReveal] = React.useState(false);
  // synthesized candlesticks for XAU
  const candles = React.useMemo(() => genCandles(60, 2380, 3.2), []);
  return (
    <div style={{ padding: "40px 48px 60px", position: "relative" }}>
      <div className="bg-aurora"/>
      <SectionHead
        eyebrow="Trading · Paper · XAU · XAG"
        title="Precious metals desk."
        sub="Live spot + futures tape, with an astrological transit overlay the team has asked to see but not to trade from. Sensitive numbers are fogged until you hover."
        action={<div style={{ display: "flex", gap: 8 }}>
          <button className="btn"><Icon.Shield size={13}/> Paper mode</button>
          <button className="btn" onClick={() => setReveal(r => !r)}>{reveal ? <Icon.EyeOff size={13}/> : <Icon.Eye size={13}/>} {reveal ? "Fog on" : "Reveal all"}</button>
        </div>}
      />

      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 14, marginTop: 14 }}>
        {/* Chart card */}
        <Card style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ padding: "18px 22px", display: "flex", alignItems: "center", justifyContent: "space-between", borderBottom: "1px solid var(--line-1)" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <div>
                <div className="eyebrow" style={{ display: "flex", gap: 8, alignItems: "center" }}><span className="dot gold"/> XAU / USD · 1h</div>
                <div style={{ marginTop: 6, display: "flex", alignItems: "baseline", gap: 12 }}>
                  <div className="display" style={{ fontSize: 40, lineHeight: 1 }}>2,384<span style={{ color: "var(--ink-3)" }}>.10</span></div>
                  <div className="mono" style={{ fontSize: 12, color: "var(--good)" }}>+9.84 (+0.42%)</div>
                </div>
              </div>
            </div>
            <div style={{ display: "flex", gap: 6 }}>
              {["1m","5m","1h","4h","1D"].map((t, i) => (
                <button key={t} className="btn" style={{ padding: "5px 10px", fontSize: 11.5, background: i === 2 ? "rgba(255,255,255,0.06)" : undefined }}>{t}</button>
              ))}
            </div>
          </div>
          <div style={{ position: "relative" }}>
            <div style={{ filter: reveal ? "none" : "blur(5px)", transition: "filter 300ms ease" }}>
              <Candles candles={candles} width={820} height={340}/>
              {/* Astro transit overlay */}
              <AstroOverlay/>
            </div>
            {!reveal && <FogLabel/>}
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", borderTop: "1px solid var(--line-1)" }}>
            {[
              { l: "Open", v: "2,374.26" },
              { l: "High", v: "2,389.11" },
              { l: "Low", v: "2,371.03" },
              { l: "Vol 24h", v: "182.4k" },
              { l: "Realized vol", v: "12.8%" },
            ].map((k, i) => (
              <div key={k.l} style={{ padding: "14px 16px", borderRight: i < 4 ? "1px solid var(--line-1)" : "none", filter: reveal ? "none" : "blur(4px)" }}>
                <div className="eyebrow" style={{ fontSize: 9.5 }}>{k.l}</div>
                <div className="mono" style={{ fontSize: 14, color: "var(--ink-1)", marginTop: 4 }}>{k.v}</div>
              </div>
            ))}
          </div>
        </Card>

        {/* Side panel */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <Card>
            <div className="eyebrow" style={{ marginBottom: 10 }}>XAG / USD</div>
            <div style={{ display: "flex", alignItems: "baseline", gap: 10 }}>
              <div className="display" style={{ fontSize: 30 }}>28.91</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--danger)" }}>−0.18%</div>
            </div>
            <div style={{ marginTop: 10 }}>
              <Sparkline data={[12,13,12,14,13,12,11,12,11,13,12,13,12,11]} color="var(--gold)" w={260} h={44}/>
            </div>
          </Card>

          <Card>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <div className="eyebrow">Sentry signals · 24h</div>
              <span className="mono" style={{ fontSize: 10, color: "var(--ink-3)" }}>4</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {[
                { t: "XAG realized vol → 38.2%", s: "above 35% threshold", tone: "warn", when: "2s" },
                { t: "XAU paper long · 0.25 @ 2,384.10", s: "stop 2,368 · TP 2,402", tone: "info", when: "8m" },
                { t: "Friday AM fix logged", s: "2,391.05 · PM pending", tone: "ok", when: "31m" },
                { t: "Mercury sq. Jupiter noted", s: "observed, no action", tone: "info", when: "2h" },
              ].map((s, i) => (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "6px 1fr auto", gap: 10, alignItems: "start" }}>
                  <span className={`dot ${s.tone === "warn" ? "warn" : ""}`} style={{ marginTop: 6, background: s.tone === "warn" ? undefined : s.tone === "ok" ? "var(--good)" : "var(--gold)", boxShadow: s.tone === "warn" ? undefined : `0 0 8px currentColor` }}/>
                  <div>
                    <div style={{ fontSize: 12.5, color: "var(--ink-1)" }}>{s.t}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--ink-3)", marginTop: 2 }}>{s.s}</div>
                  </div>
                  <div className="mono" style={{ fontSize: 10, color: "var(--ink-4)" }}>{s.when}</div>
                </div>
              ))}
            </div>
          </Card>

          <Card>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Astrological transit · 21 Apr</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-2)", lineHeight: 1.55 }}>
              Mercury square Jupiter · waxing gibbous · Venus in Taurus. Sentry notes a mild risk-on bias; the charter says we log, we do not act.
            </div>
            <div style={{ display: "flex", gap: 6, marginTop: 12 }}>
              <span className="mono" style={{ fontSize: 10, padding: "2px 6px", borderRadius: 3, border: "1px solid var(--line-1)", color: "var(--ink-3)" }}>☿ □ ♃</span>
              <span className="mono" style={{ fontSize: 10, padding: "2px 6px", borderRadius: 3, border: "1px solid var(--line-1)", color: "var(--ink-3)" }}>♀ in ♉</span>
              <span className="mono" style={{ fontSize: 10, padding: "2px 6px", borderRadius: 3, border: "1px solid var(--line-1)", color: "var(--ink-3)" }}>waxing</span>
            </div>
          </Card>
        </div>
      </div>

      {/* Ledger */}
      <div style={{ marginTop: 20 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
          <div>
            <div className="eyebrow">Paper ledger</div>
            <div className="display" style={{ fontSize: 22, marginTop: 4 }}>Today's orders</div>
          </div>
          <button className="btn">Export CSV <Icon.ArrowRight size={12}/></button>
        </div>
        <Card style={{ padding: 0, overflow: "hidden" }}>
          <div style={{ display: "grid", gridTemplateColumns: "80px 1fr 100px 100px 120px 120px 100px 80px", padding: "12px 20px", borderBottom: "1px solid var(--line-1)", fontSize: 10.5, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
            <div>Time</div><div>Agent</div><div>Side</div><div>Sym</div><div>Entry</div><div>Stop · TP</div><div>Size</div><div>PnL</div>
          </div>
          {[
            { t: "14:01:12", a: "Market Sentry", side: "LONG", sym: "XAU", e: "2,384.10", sl: "2,368 · 2,402", sz: "0.25", pnl: "+0.12" },
            { t: "11:28:04", a: "Market Sentry", side: "SHORT", sym: "XAG", e: "29.10", sl: "29.40 · 28.80", sz: "1.00", pnl: "+0.19" },
            { t: "09:04:57", a: "Tape Reader", side: "LONG", sym: "XAU", e: "2,376.40", sl: "2,368 · 2,395", sz: "0.10", pnl: "+0.08" },
          ].map((r, i) => (
            <div key={i} style={{ display: "grid", gridTemplateColumns: "80px 1fr 100px 100px 120px 120px 100px 80px", padding: "14px 20px", borderBottom: "1px solid var(--line-1)", alignItems: "center", fontSize: 12.5, filter: reveal ? "none" : "blur(4px)" }}>
              <div className="mono" style={{ color: "var(--ink-3)" }}>{r.t}</div>
              <div>{r.a}</div>
              <div className="mono" style={{ color: r.side === "LONG" ? "var(--good)" : "var(--danger)" }}>{r.side}</div>
              <div className="mono">{r.sym}</div>
              <div className="mono">{r.e}</div>
              <div className="mono" style={{ color: "var(--ink-3)" }}>{r.sl}</div>
              <div className="mono">{r.sz}</div>
              <div className="mono" style={{ color: "var(--good)" }}>{r.pnl}</div>
            </div>
          ))}
        </Card>
      </div>
    </div>
  );
}

function genCandles(n, base, vol) {
  const out = [];
  let price = base;
  for (let i = 0; i < n; i++) {
    const o = price;
    const c = price + (Math.random() - 0.5) * vol * 3;
    const h = Math.max(o, c) + Math.random() * vol;
    const l = Math.min(o, c) - Math.random() * vol;
    out.push({ o, h, l, c });
    price = c;
  }
  return out;
}

function Candles({ candles, width, height }) {
  const pad = 20;
  const W = width, H = height;
  const min = Math.min(...candles.map(c => c.l));
  const max = Math.max(...candles.map(c => c.h));
  const range = max - min || 1;
  const step = (W - pad*2) / candles.length;
  const y = (v) => pad + (1 - (v - min) / range) * (H - pad*2);
  return (
    <svg width="100%" height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: "block" }}>
      <defs>
        <linearGradient id="c-fill" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="oklch(0.82 0.14 80)" stopOpacity="0.2"/>
          <stop offset="1" stopColor="oklch(0.82 0.14 80)" stopOpacity="0"/>
        </linearGradient>
      </defs>
      {/* grid */}
      {[0.25, 0.5, 0.75].map(f => (
        <line key={f} x1={pad} x2={W-pad} y1={pad + f*(H-pad*2)} y2={pad + f*(H-pad*2)} stroke="var(--line-1)" strokeDasharray="2 4"/>
      ))}
      {/* envelope */}
      <path
        d={candles.map((c, i) => `${i?"L":"M"}${pad + i*step + step/2} ${y((c.h + c.l)/2)}`).join(" ") + ` L ${W-pad} ${H-pad} L ${pad} ${H-pad} Z`}
        fill="url(#c-fill)"
      />
      {candles.map((c, i) => {
        const x = pad + i*step + step/2;
        const up = c.c >= c.o;
        const color = up ? "oklch(0.78 0.15 155)" : "oklch(0.68 0.20 25)";
        return (
          <g key={i}>
            <line x1={x} x2={x} y1={y(c.h)} y2={y(c.l)} stroke={color} strokeWidth="0.8" opacity="0.7"/>
            <rect x={x - step*0.3} y={y(Math.max(c.o, c.c))} width={step*0.6} height={Math.max(1, Math.abs(y(c.o) - y(c.c)))} fill={color} opacity="0.85"/>
          </g>
        );
      })}
      {/* price label */}
      <g transform={`translate(${W - pad - 72}, ${y(candles[candles.length-1].c) - 10})`}>
        <rect width="68" height="20" rx="3" fill="oklch(0.82 0.14 80 / 0.15)" stroke="oklch(0.82 0.14 80 / 0.4)"/>
        <text x="8" y="14" fontFamily="var(--font-mono)" fontSize="10.5" fill="var(--gold)">2,384.10</text>
      </g>
    </svg>
  );
}

function AstroOverlay() {
  return (
    <div style={{ position: "absolute", right: 14, top: 14, display: "flex", gap: 6 }}>
      {[
        { l: "☿ □ ♃", t: "Mercury square Jupiter" },
        { l: "☾ ↑", t: "Waxing gibbous" },
      ].map((a) => (
        <div key={a.l} className="mono" style={{ fontSize: 10.5, padding: "3px 7px", borderRadius: 4, background: "rgba(0,0,0,0.4)", border: "1px solid var(--line-2)", color: "var(--ink-2)" }} title={a.t}>{a.l}</div>
      ))}
    </div>
  );
}

function FogLabel() {
  return (
    <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", pointerEvents: "none" }}>
      <div className="mono" style={{ fontSize: 11, color: "var(--ink-2)", padding: "6px 12px", borderRadius: 999, border: "1px solid var(--line-2)", background: "rgba(0,0,0,0.35)", display: "flex", gap: 8, alignItems: "center" }}>
        <Icon.EyeOff size={12}/> privacy fog · hover or toggle reveal
      </div>
    </div>
  );
}

// ---- Settings ----
function SettingsView() {
  return (
    <div style={{ padding: "40px 48px 60px", position: "relative", maxWidth: 980 }}>
      <div className="bg-aurora"/>
      <SectionHead
        eyebrow="Settings · Charter"
        title="House rules."
        sub="Everything an agent may or may not do. Scoped secrets, budgets, review gates. Change here ripples to every sub-agent at next orchestration tick."
      />

      <div style={{ display: "flex", flexDirection: "column", gap: 14, marginTop: 14 }}>
        <SettingsGroup title="VPS" lines={[
          { k: "Host", v: "NYC-03 · vps-03.gastronaut.internal" },
          { k: "CPU / Mem", v: "8 vCPU · 16 GB" },
          { k: "Runtime", v: "claude-code 0.9.2 · node 20" },
          { k: "Backup", v: "daily 04:00 UTC · rotated 12h ago" },
        ]}/>
        <SettingsGroup title="Identity" lines={[
          { k: "Anthropic key", v: "sk-ant-•••••••••••T4K2", toggle: true },
          { k: "Git identity", v: "scribe@gastronaut.ai · key ed25519:•••ZQx", toggle: true },
          { k: "Broker API", v: "paper only · no real keys provisioned", good: true },
        ]}/>
        <SettingsGroup title="Budgets" lines={[
          { k: "Daily spend cap", v: "$120.00 · 34% used" },
          { k: "Per-agent cap", v: "$30.00 / 24h" },
          { k: "Token ceiling", v: "4.0M tokens / 24h" },
        ]}/>
        <SettingsGroup title="Review gates" lines={[
          { k: "Outbound emails", v: "always require human approval", good: true },
          { k: "Code pushes to main", v: "require review from Prime", good: true },
          { k: "Real-money trades", v: "disabled · paper mode", good: true },
          { k: "Social posts", v: "require review from Sefa" },
        ]}/>
        <SettingsGroup title="Appearance" lines={[
          { k: "Theme", v: "use the sun/moon toggle in the top bar" },
          { k: "Density", v: "editorial" },
          { k: "Accent", v: "electric cyan + champagne" },
        ]}/>
      </div>
    </div>
  );
}

function SettingsGroup({ title, lines }) {
  return (
    <Card style={{ padding: 0 }}>
      <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line-1)" }}>
        <div className="eyebrow">{title}</div>
      </div>
      <div>
        {lines.map((l, i) => (
          <div key={i} style={{
            display: "grid", gridTemplateColumns: "220px 1fr auto", gap: 20,
            padding: "14px 20px",
            borderBottom: i < lines.length - 1 ? "1px solid var(--line-1)" : "none",
            alignItems: "center",
          }}>
            <div style={{ fontSize: 13, color: "var(--ink-2)" }}>{l.k}</div>
            <div className="mono" style={{ fontSize: 12, color: l.good ? "var(--good)" : "var(--ink-1)" }}>{l.v}</div>
            <div>
              {l.toggle ? (
                <button className="btn" style={{ padding: "4px 10px", fontSize: 11 }}>Rotate</button>
              ) : (
                <span style={{ color: "var(--ink-4)" }}>·</span>
              )}
            </div>
          </div>
        ))}
      </div>
    </Card>
  );
}

window.TradingView = TradingView;
window.SettingsView = SettingsView;
