// Neurasea Exchange — pro Terminal view
// Exports to window: ExTerminal

function PriceChart({ data, color, w = 560, h = 230 }) {
  const t = useTheme();
  const max = Math.max(...data) * 1.02, min = Math.min(...data) * 0.98;
  const rng = max - min || 1;
  const pts = data.map((d, i) => [(i / (data.length - 1)) * w, h - ((d - min) / rng) * h]);
  const line = pts.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');
  const area = `${line} L${w} ${h} L0 ${h} Z`;
  const id = React.useMemo(() => 'pc' + Math.random().toString(36).slice(2, 6), []);
  const grid = [0.2, 0.4, 0.6, 0.8];
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" style={{ display: 'block' }} preserveAspectRatio="none">
      <defs><linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={color} stopOpacity="0.20"/><stop offset="100%" stopColor={color} stopOpacity="0"/>
      </linearGradient></defs>
      {grid.map((g, i) => <line key={i} x1="0" x2={w} y1={h * g} y2={h * g} stroke={t.line2} strokeWidth="1"/>)}
      <path d={area} fill={`url(#${id})`}/>
      <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round"/>
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="3.5" fill={color}/>
    </svg>
  );
}

function Watchlist({ sel, onSel }) {
  const t = useTheme();
  const T = useT();
  const c = exColors(t);
  return (
    <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: 14, overflow: 'hidden' }}>
      <div style={{ padding: '12px 16px', fontSize: 12, fontWeight: 650, fontFamily: t.mono, color: t.ink2, textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: `1px solid ${t.line2}` }}>{T('Watchlist')}</div>
      {EX_DATA.spot.map(r => {
        const on = r.id === sel;
        return (
          <button key={r.id} onClick={() => onSel(r.id)} style={{
            width: '100%', display: 'flex', alignItems: 'center', gap: 10, padding: '11px 16px', cursor: 'pointer',
            background: on ? t.panel3 : 'transparent', border: 'none', borderLeft: `2px solid ${on ? t.draw : 'transparent'}`,
            fontFamily: t.sans, textAlign: 'left',
          }}>
            <Avatar label={r.model[0]} bg={r.bg} fg={r.fg} size={26} radius={7}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: t.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.model}</div>
              <div style={{ fontSize: 10.5, fontFamily: t.mono, color: t.ink3 }}>{r.suppliers} {T('online')}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 12.5, fontFamily: t.mono, fontWeight: 650, color: t.ink }}>{r.price.toFixed(2)}</div>
              <div style={{ fontSize: 10.5, fontFamily: t.mono, color: r.chg >= 0 ? c.up : c.down }}>{r.chg >= 0 ? '+' : ''}{r.chg.toFixed(1)}%</div>
            </div>
          </button>
        );
      })}
    </div>
  );
}

function OrderBook() {
  const t = useTheme();
  const T = useT();
  const c = exColors(t);
  const b = EX_DATA.book;
  const maxSz = Math.max(...[...b.asks, ...b.bids].map(x => x.sz));
  const Row = ({ o, side }) => {
    const col = side === 'ask' ? c.down : c.up;
    const bg = side === 'ask' ? c.downSoft : t.liveSoft;
    return (
      <div style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr 0.7fr', gap: 8, padding: '4px 14px', fontSize: 11.5, fontFamily: t.mono }}>
        <div style={{ position: 'absolute', top: 0, bottom: 0, right: 0, width: `${o.sz / maxSz * 100}%`, background: bg }}/>
        <span style={{ position: 'relative', color: col, fontWeight: 600 }}>{o.px.toFixed(2)}</span>
        <span style={{ position: 'relative', textAlign: 'right', color: t.ink2 }}>{o.sz.toFixed(1)}</span>
        <span style={{ position: 'relative', textAlign: 'right', color: t.ink3 }}>{o.n}</span>
      </div>
    );
  };
  return (
    <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: 14, overflow: 'hidden' }}>
      <div style={{ padding: '12px 16px', fontSize: 12, fontWeight: 650, fontFamily: t.mono, color: t.ink2, textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: `1px solid ${t.line2}` }}>{T('Order book')}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 0.7fr', gap: 8, padding: '7px 14px', fontSize: 10, fontFamily: t.mono, color: t.ink3, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
        <span>{T('PRICE')}</span><span style={{ textAlign: 'right' }}>{T('SIZE')}</span><span style={{ textAlign: 'right' }}>n</span>
      </div>
      {b.asks.slice().reverse().map((o, i) => <Row key={i} o={o} side="ask"/>)}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 14px', borderTop: `1px solid ${t.line2}`, borderBottom: `1px solid ${t.line2}`, background: t.panel2 }}>
        <span style={{ fontSize: 15, fontWeight: 700, fontFamily: t.mono, color: t.ink }}>{b.last.toFixed(2)}</span>
        <span style={{ fontSize: 11, fontFamily: t.mono, color: t.ink3 }}>{T('Spread')} 0.03</span>
      </div>
      {b.bids.map((o, i) => <Row key={i} o={o} side="bid"/>)}
    </div>
  );
}

function TradeTape() {
  const t = useTheme();
  const T = useT();
  const c = exColors(t);
  return (
    <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: 14, overflow: 'hidden' }}>
      <div style={{ padding: '12px 16px', fontSize: 12, fontWeight: 650, fontFamily: t.mono, color: t.ink2, textTransform: 'uppercase', letterSpacing: '0.05em', borderBottom: `1px solid ${t.line2}` }}>{T('Recent trades')}</div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 0.7fr 0.9fr', gap: 8, padding: '7px 16px', fontSize: 10, fontFamily: t.mono, color: t.ink3, textTransform: 'uppercase', letterSpacing: '0.04em' }}>
        <span>{T('PRICE')}</span><span style={{ textAlign: 'right' }}>{T('SIZE')}</span><span style={{ textAlign: 'right' }}>{T('TIME')}</span>
      </div>
      {EX_DATA.tape.map((tr, i) => (
        <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 0.7fr 0.9fr', gap: 8, padding: '5px 16px', fontSize: 11.5, fontFamily: t.mono }}>
          <span style={{ color: tr.side === 'buy' ? c.up : c.down, fontWeight: 600 }}>{tr.px.toFixed(2)}</span>
          <span style={{ textAlign: 'right', color: t.ink2 }}>{tr.sz.toFixed(1)}</span>
          <span style={{ textAlign: 'right', color: t.ink3 }}>{tr.t}</span>
        </div>
      ))}
    </div>
  );
}

function OrderEntry({ row }) {
  const t = useTheme();
  const T = useT();
  const [mode, setMode] = React.useState('spot');
  const [otype, setOtype] = React.useState('Market');
  const [amt, setAmt] = React.useState(2);
  const cost = (amt * row.price).toFixed(1);
  return (
    <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: 14, padding: 18 }}>
      <Segmented size="sm" options={[{ value: 'spot', label: T('Spot') }, { value: 'fut', label: T('Futures') }]} value={mode} onChange={setMode}/>
      <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 12 }}>
        {mode === 'spot' && (
          <div>
            <div style={{ fontSize: 11, color: t.ink3, fontFamily: t.mono, marginBottom: 6 }}>{T('Order type')}</div>
            <Segmented size="sm" options={[{ value: 'Market', label: T('Market') }, { value: 'Limit', label: T('Limit') }]} value={otype} onChange={setOtype}/>
          </div>
        )}
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, color: t.ink3, fontFamily: t.mono, marginBottom: 6 }}>
            <span>{T('Amount')}</span><span>{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.draw }}/>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '12px 0', borderTop: `1px solid ${t.line2}`, borderBottom: `1px solid ${t.line2}` }}>
          {[[mode === 'spot' ? T('Avg. price') : T('lock price'), `${(mode === 'spot' ? row.price : row.price * 0.82).toFixed(2)} kWh/Mtok`], [T('Est. cost'), `${mode === 'spot' ? cost : (amt * row.price * 0.82).toFixed(1)} kWh`], [T('Quality floor'), `≥ ${row.quality}%`]].map(([k, v], i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, fontFamily: t.mono }}>
              <span style={{ color: t.ink3 }}>{k}</span><span style={{ fontWeight: 650, color: t.ink }}>{v}</span>
            </div>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11, fontFamily: t.mono, color: t.live }}>
          <Icon name="shield" size={13} color={t.live}/> {T('Quality floor')} {T('guaranteed')}
        </div>
        <Btn kind="accent" full color={t.draw} icon={mode === 'spot' ? 'bolt' : 'battery'}>{mode === 'spot' ? T('Place order') : T('Lock in contract')}</Btn>
      </div>
    </div>
  );
}

function ExTerminal() {
  const t = useTheme();
  const T = useT();
  const c = exColors(t);
  const [sel, setSel] = React.useState('opus');
  const row = EX_DATA.spot.find(r => r.id === sel);
  const series = exSeries(row.model.length * 5, 60, row.price, row.price * 0.14);

  return (
    <div style={{ padding: '24px 28px 40px', maxWidth: 1320, margin: '0 auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '230px 1fr 280px', gap: 16, alignItems: 'start' }}>
        {/* left: watchlist */}
        <Watchlist sel={sel} onSel={setSel}/>

        {/* center: chart + order entry */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ background: t.panel, border: `1px solid ${t.line}`, borderRadius: 14, padding: 20 }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <Avatar label={row.model[0]} bg={row.bg} fg={row.fg} size={38} radius={10}/>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                    <span style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.02em', color: t.ink }}>{row.model}</span>
                    <TierBadge tier={row.tier}/>
                  </div>
                  <div style={{ fontSize: 11.5, fontFamily: t.mono, color: t.ink3, marginTop: 2 }}>{row.vendor} · {row.suppliers} {T('SUPPLIERS').toLowerCase()}</div>
                </div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ fontSize: 26, fontWeight: 720, fontFamily: t.mono, letterSpacing: '-0.02em', color: t.ink }}>{row.price.toFixed(2)}</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'flex-end' }}>
                  <ChangeTag v={row.chg}/>
                  <span style={{ fontSize: 11, fontFamily: t.mono, color: t.ink3 }}>· {row.latency}ms · {row.quality}%</span>
                </div>
              </div>
            </div>
            <PriceChart data={series} color={row.chg >= 0 ? c.up : c.down}/>
          </div>
          <OrderEntry row={row}/>
        </div>

        {/* right: order book + tape */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <OrderBook/>
          <TradeTape/>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ExTerminal });
