// Neurasea Exchange — Spot marketplace view
// Exports to window: ExSpot

function BuySheet({ row, onClose }) {
  const t = useTheme();
  const T = useT();
  const c = exColors(t);
  const [amt, setAmt] = React.useState(2);
  const cost = (amt * row.price).toFixed(1);
  return (
    <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', backdropFilter: 'blur(3px)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 420, background: t.panel, border: `1px solid ${t.line}`, borderRadius: 20, boxShadow: t.shadow, overflow: 'hidden' }}>
        <div style={{ padding: '22px 24px', borderBottom: `1px solid ${t.line2}`, display: 'flex', alignItems: 'center', gap: 12 }}>
          <Avatar label={row.model[0]} bg={row.bg} fg={row.fg} size={40} radius={11}/>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 12, color: t.live, fontWeight: 650, fontFamily: t.mono }}>{T('Buy spot')}</div>
            <div style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em', color: t.ink }}>{row.model}</div>
          </div>
          <TierBadge tier={row.tier}/>
        </div>
        <div style={{ padding: 24 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, color: t.ink2, marginBottom: 8 }}>
            <span>{T('Amount')}</span><span style={{ fontFamily: t.mono }}>{amt.toFixed(1)} {T('Mtok')}</span>
          </div>
          <input type="range" min="0.5" max="20" step="0.5" value={amt} onChange={e => setAmt(+e.target.value)}
            style={{ width: '100%', accentColor: t.live }} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, marginTop: 20 }}>
            {[['Spot price', `${row.price.toFixed(2)} kWh/Mtok`], ['Est. cost', `${cost} kWh`], ['Quality guarantee', `≥ ${row.quality}%`]].map(([k, v], i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 13.5 }}>
                <span style={{ color: t.ink2 }}>{T(k)}</span>
                <span style={{ fontFamily: t.mono, fontWeight: 650, color: i === 1 ? t.ink : t.ink }}>{v}</span>
              </div>
            ))}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 16, padding: '11px 13px', background: t.liveSoft, borderRadius: 11, fontSize: 12, color: t.live, fontFamily: t.mono }}>
            <Icon name="shield" size={15} color={t.live}/> {T('Routed to cheapest healthy supply ≥ quality bar')}
          </div>
          <div style={{ display: 'flex', gap: 10, marginTop: 22 }}>
            <Btn kind="ghost" full onClick={onClose}>{T('Cancel')}</Btn>
            <Btn kind="accent" full color={t.live} icon="bolt" onClick={onClose}>{T('Place spot order')}</Btn>
          </div>
        </div>
      </div>
    </div>
  );
}

function ExSpot() {
  const t = useTheme();
  const T = useT();
  const c = exColors(t);
  const [filter, setFilter] = React.useState('all');
  const [buy, setBuy] = React.useState(null);
  const vendors = ['all', 'Anthropic', 'OpenAI', 'Google', 'xAI'];
  const rows = EX_DATA.spot.filter(r => filter === 'all' || r.vendor === filter);
  const index = (EX_DATA.spot.reduce((a, r) => a + r.price, 0) / EX_DATA.spot.length).toFixed(2);

  return (
    <div style={{ padding: '40px 44px 64px', maxWidth: 1240, margin: '0 auto' }}>
      <ExHead kicker={T('Spot · pay as you go')} title={T("Buy AI tokens at the market's lowest price")}
        sub={T("Spot pays as you go; futures lock a weekly rate. Either way Neurasea routes every request to the cheapest healthy supply at guaranteed quality — you never touch the upstream.")} />

      {/* KPI strip */}
      <div style={{ display: 'flex', gap: 0, padding: '20px 0', borderTop: `1px solid ${t.line}`, borderBottom: `1px solid ${t.line}`, marginBottom: 22 }}>
        <ExStat label={T('Index price')} value={index} unit="kWh/Mtok"/>
        <div style={{ width: 1, background: t.line2 }}/>
        <ExStat label={T('24h volume')} value="48.2k" unit="kWh"/>
        <div style={{ width: 1, background: t.line2 }}/>
        <ExStat label={T('Avg. quality SLA')} value="99.0%" accent={t.live}/>
        <div style={{ width: 1, background: t.line2 }}/>
        <ExStat label={T('Active suppliers')} value="94" sub={<span style={{ fontSize: 11.5, color: t.live, fontFamily: t.mono, display: 'inline-flex', alignItems: 'center', gap: 5 }}><StatusDot color={t.live} size={5} pulse/> {T('Live')}</span>}/>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
        <Segmented options={vendors.map(v => ({ value: v, label: v === 'all' ? T('All models') : v }))} value={filter} onChange={setFilter}/>
        <span style={{ fontSize: 12.5, color: t.ink3, fontFamily: t.mono }}>{T('1 kWh = 1M tokens · settled in credits')}</span>
      </div>

      {/* market table */}
      <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: 16, overflow: 'hidden' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1.1fr 0.9fr 1.1fr 1fr 0.9fr 0.9fr', gap: 12, padding: '13px 22px', fontSize: 10.5, fontFamily: t.mono, color: t.ink3, textTransform: 'uppercase', letterSpacing: '0.05em', background: t.panel2, borderBottom: `1px solid ${t.line}` }}>
          <span>{T('MODEL')}</span><span style={{ textAlign: 'right' }}>{T('SPOT PRICE')}</span><span style={{ textAlign: 'right' }}>{T('24H')}</span><span></span><span style={{ textAlign: 'right' }}>{T('SUPPLIERS')}</span><span style={{ textAlign: 'right' }}>{T('QUALITY')}</span><span></span>
        </div>
        {rows.map((r, i) => {
          const series = exSeries(r.model.length * 7 + i, 20, r.price, r.price * 0.18);
          return (
            <div key={r.id} style={{ display: 'grid', gridTemplateColumns: '2fr 1.1fr 0.9fr 1.1fr 1fr 0.9fr 0.9fr', gap: 12, alignItems: 'center', padding: '14px 22px', borderBottom: i < rows.length - 1 ? `1px solid ${t.line2}` : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
                <Avatar label={r.model[0]} bg={r.bg} fg={r.fg} size={30} radius={8}/>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 650, color: t.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.model}</div>
                  <div style={{ marginTop: 3 }}><TierBadge tier={r.tier}/></div>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 15, fontWeight: 680, fontFamily: t.mono, color: t.ink }}>{r.price.toFixed(2)}</div>
                <div style={{ fontSize: 10.5, color: t.ink3, fontFamily: t.mono, textDecoration: 'line-through' }}>{r.ref.toFixed(1)}</div>
              </div>
              <div style={{ textAlign: 'right' }}><ChangeTag v={r.chg}/></div>
              <div style={{ display: 'flex', justifyContent: 'center' }}><Sparkline data={series} color={r.chg >= 0 ? c.up : c.down} w={92} h={30}/></div>
              <div style={{ textAlign: 'right', fontSize: 13, fontFamily: t.mono, color: t.ink2 }}>
                <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><StatusDot color={t.live} size={5} pulse/> {r.suppliers}</span>
              </div>
              <div style={{ textAlign: 'right', fontSize: 13, fontFamily: t.mono, fontWeight: 600, color: t.live }}>{r.quality}%</div>
              <div style={{ textAlign: 'right' }}><Btn kind="accent" size="sm" color={t.draw} onClick={() => setBuy(r)}>{T('Buy')}</Btn></div>
            </div>
          );
        })}
      </div>
      {buy && <BuySheet row={buy} onClose={() => setBuy(null)}/>}
    </div>
  );
}

Object.assign(window, { ExSpot });
