// Ticker, stats, download, footer

function Ticker({ accent = '#00E0B8', accent2 = '#FF3D6E' }) {
  // Pairs to display, with Frankfurter base/quote mapping (XAU handled via metals API)
  const PAIRS = [
    { display: 'XAU/USD', base: 'XAU', quote: 'USD', dp: 2 },
    { display: 'EUR/USD', base: 'EUR', quote: 'USD', dp: 5 },
    { display: 'GBP/USD', base: 'GBP', quote: 'USD', dp: 5 },
    { display: 'USD/JPY', base: 'USD', quote: 'JPY', dp: 3 },
    { display: 'USD/CHF', base: 'USD', quote: 'CHF', dp: 5 },
    { display: 'NZD/USD', base: 'NZD', quote: 'USD', dp: 5 },
    { display: 'USD/CAD', base: 'USD', quote: 'CAD', dp: 5 },
    { display: 'EUR/JPY', base: 'EUR', quote: 'JPY', dp: 3 },
    { display: 'GBP/JPY', base: 'GBP', quote: 'JPY', dp: 3 },
    { display: 'AUD/USD', base: 'AUD', quote: 'USD', dp: 5 },
  ];

  // Reasonable static fallbacks (used until live data arrives, or if fetch fails)
  const FALLBACK = {
    'XAU/USD': 2408.10, 'EUR/USD': 1.08410, 'GBP/USD': 1.27120, 'USD/JPY': 151.482,
    'USD/CHF': 0.90120, 'NZD/USD': 0.59410, 'USD/CAD': 1.36210, 'EUR/JPY': 164.218,
    'GBP/JPY': 192.604, 'AUD/USD': 0.65820,
  };

  const [quotes, setQuotes] = React.useState(() =>
    PAIRS.map(p => ({ ...p, px: FALLBACK[p.display], ch: 0, prev: FALLBACK[p.display] }))
  );

  React.useEffect(() => {
    let cancelled = false;

    async function fetchOne(pair) {
      try {
        // open.er-api.com is keyless + CORS-enabled and supports XAU
        const r = await fetch(`https://open.er-api.com/v6/latest/${pair.base}`);
        const j = await r.json();
        if (j && j.rates && j.rates[pair.quote]) return j.rates[pair.quote];
      } catch (e) { /* ignore */ }
      return null;
    }

    async function refresh() {
      const results = await Promise.all(PAIRS.map(fetchOne));
      if (cancelled) return;
      setQuotes(prev => prev.map((q, i) => {
        const live = results[i];
        if (live == null) return q;
        // tiny micro-jitter so the ticker visibly "moves" between full refreshes
        const px = live;
        const prevPx = q.prev || px;
        const ch = ((px - prevPx) / prevPx) * 100;
        return { ...q, px, prev: prevPx, ch };
      }));
    }

    refresh();
    const id = setInterval(refresh, 60_000); // refresh every minute
    // Local micro-jitter every 3s to feel alive between refreshes
    const jit = setInterval(() => {
      if (cancelled) return;
      setQuotes(prev => prev.map(q => {
        const noise = (Math.random() - 0.5) * q.px * 0.0004; // ±0.04%
        const px = q.px + noise;
        const ch = ((px - (q.prev || px)) / (q.prev || px)) * 100;
        return { ...q, px, ch };
      }));
    }, 3000);
    return () => { cancelled = true; clearInterval(id); clearInterval(jit); };
  }, []);

  function fmt(n, dp) {
    if (n == null) return '—';
    return n.toLocaleString('en-US', { minimumFractionDigits: dp >= 3 ? Math.min(dp, 3) : dp, maximumFractionDigits: dp });
  }
  function fmtCh(c) {
    const s = c >= 0 ? '+' : '';
    return `${s}${c.toFixed(2)}%`;
  }

  const row = [...quotes, ...quotes];
  return (
    <div className="ticker-wrap">
      <div className="ticker-track">
        {row.map((q, i) => {
          const up = q.ch >= 0;
          return (
            <span className="tk" key={i}>
              <span className="tk-sym">{q.display}</span>
              <span className="tk-px">{fmt(q.px, q.dp)}</span>
              <span className="tk-ch" style={{ color: up ? accent : accent2 }}>{up ? '▲' : '▼'} {fmtCh(q.ch)}</span>
            </span>
          );
        })}
        <span className="tk" style={{ opacity: 0.5 }}>
          <span className="tk-sym" style={{ color: accent }}>● LIVE</span>
        </span>
      </div>
    </div>
  );
}

function StatsStrip({ accent = '#00E0B8' }) {
  const stats = [
    { v: '$2.4B', l: 'Notional traded · last 30d' },
    { v: '8 ms', l: 'Median order latency' },
    { v: '71.4%', l: 'Aggregate hit rate' },
    { v: '24/7', l: 'Always on the tape' },
  ];
  return (
    <div className="stats-strip">
      {stats.map((s, i) => (
        <div className="stat" key={i} data-reveal>
          <div className="stat-v" style={{ color: accent }}>{s.v}</div>
          <div className="stat-l">{s.l}</div>
        </div>
      ))}
    </div>
  );
}

function HowItWorks({ accent = '#00E0B8', accent2 = '#FF3D6E' }) {
  const steps = [
    { n: '01', t: 'Install the desk', d: 'One-click installer for macOS and Windows. Connects to your broker via OAuth — keys never leave your machine.' },
    { n: '02', t: 'Pick your agents', d: 'Six autonomous agents out of the box. Mix them, throttle them, lock them to specific universes.' },
    { n: '03', t: 'Press the green button', d: 'The desk goes live. You watch. You override. You sleep. The machines do not.' },
  ];
  return (
    <div className="how-grid">
      {steps.map((s, i) => (
        <div className="how-step" key={s.n} data-reveal>
          <div className="how-n" style={{ color: i === 1 ? accent2 : accent }}>{s.n}</div>
          <h3 className="how-t">{s.t}</h3>
          <p className="how-d">{s.d}</p>
          <div className="how-line"></div>
        </div>
      ))}
    </div>
  );
}

// Stable filenames in R2 (bucket: aican-downloads, custom domain
// dl.aican.trade). Each release re-uploads the same key so links never
// break. To roll out a new build, run:
//   wrangler r2 object put aican-downloads/<filename> --file <path>
const DL_BASE = 'https://dl.aican.trade';
const DL_FILES = {
  'mac-arm': 'aican-trade-macos-arm64.dmg',
  'mac-x86': 'aican-trade-macos-intel.dmg',
  'win': 'aican-trade-windows.msi',
};

function DownloadBlock({ accent = '#00E0B8', accent2 = '#FF3D6E' }) {
  const [hover, setHover] = React.useState(null);
  const platforms = [
    { id: 'mac-arm', os: 'macOS', sub: 'Apple silicon', size: '6.3 MB', icon: '' },
    { id: 'mac-x86', os: 'macOS', sub: 'Intel', size: '6.5 MB', icon: '' },
    { id: 'win', os: 'Windows', sub: '10 / 11 · x64', size: 'Coming soon', icon: '⊞' },
  ];
  return (
    <div className="dl-block">
      <div className="dl-headline">
        <div className="dl-eyebrow">DOWNLOAD · v1.4.0</div>
        <h2 className="dl-title">
          Get the desk on your <span className="grad-text">machine</span>.
        </h2>
        <p className="dl-sub">No cloud. No middlemen. Your keys, your strategies, your latency.</p>
      </div>
      <div className="dl-platforms">
        {platforms.map(p => (
          <a
            key={p.id}
            href={`${DL_BASE}/${DL_FILES[p.id]}`}
            className={`dl-card ${hover === p.id ? 'hover' : ''}`}
            onMouseEnter={() => setHover(p.id)}
            onMouseLeave={() => setHover(null)}
          >
            <div className="dl-os-icon">{p.icon}</div>
            <div className="dl-os-text">
              <div className="dl-os">{p.os}</div>
              <div className="dl-os-sub">{p.sub}</div>
            </div>
            <div className="dl-arrow">↓</div>
            <div className="dl-size">{p.size}</div>
            <div className="dl-shimmer"></div>
          </a>
        ))}
      </div>
      <div className="dl-foot">
        <span><span className="dl-blink" style={{ background: accent }}></span> SHA-256 verified · Tauri-signed updates</span>
      </div>
    </div>
  );
}

window.Ticker = Ticker;
window.StatsStrip = StatsStrip;
window.HowItWorks = HowItWorks;
window.DownloadBlock = DownloadBlock;
