// WiseTokens — Playground
function Playground() {
  const [model, setModel] = React.useState('deepseek-v3.1');
  const [system, setSystem] = React.useState('You are a helpful assistant.');
  const [input, setInput] = React.useState('Write a haiku about token arbitrage.');
  const [temp, setTemp] = React.useState(0.7);
  const [maxTok, setMaxTok] = React.useState(512);
  const [stream, setStream] = React.useState(true);
  const [messages, setMessages] = React.useState([
    { role: 'assistant', content: 'Ready. Send a message to test this model.', meta: { tokens: 0, cost: 0, latency: 0 } },
  ]);
  const [running, setRunning] = React.useState(false);

  const m = WT.MODELS.find(x => x.id === model);
  const samples = {
    chat: 'Explain LLM routing in 2 sentences, for a product manager.',
    code: 'Write a TypeScript function to debounce async calls.',
    reasoning: 'If a train leaves Beijing at 9 AM going 300km/h and another leaves Shanghai at 10 AM going 250km/h, when do they meet? Cities are 1318km apart.',
    roleplay: 'You are a helpful polyglot tutor. Translate "hello, how are you?" into Hindi, Portuguese, and Bahasa Indonesia.',
  };

  const responseSamples = [
    'Tokens flow downstream\nArbitrage across the strait—\nSavings in silence.',
    'WiseTokens routes every request through the cheapest model that still meets your quality target. You pay per-token, we handle failover and streaming. Your code stays OpenAI-compatible.',
    'Given both trains travel toward each other: relative speed = 550 km/h. At 10 AM, Beijing train has covered 300km, so 1018km remain. Time to meet = 1018/550 ≈ 1.85 hours. They meet around 11:51 AM.',
  ];

  const run = () => {
    if (running) return;
    setRunning(true);
    const userMsg = { role: 'user', content: input };
    const reply = responseSamples[Math.floor(Math.random() * responseSamples.length)];
    const inTok = Math.floor((system.length + input.length) / 3.5);
    const outTok = Math.floor(reply.length / 3.5);
    const cost = (inTok/1e6)*m.in + (outTok/1e6)*m.out;

    setMessages(prev => [...prev, userMsg, { role: 'assistant', content: '', streaming: true, meta: { tokens: 0, cost: 0, latency: 0 } }]);
    setInput('');

    if (stream) {
      let i = 0;
      const start = Date.now();
      const tick = () => {
        i += Math.max(2, Math.floor(Math.random()*4));
        const partial = reply.slice(0, i);
        setMessages(prev => {
          const next = [...prev];
          next[next.length - 1] = { role: 'assistant', content: partial, streaming: i < reply.length, meta: { tokens: Math.floor(partial.length/3.5), cost: (inTok/1e6)*m.in + (partial.length/3.5/1e6)*m.out, latency: Date.now() - start, inTok, model } };
          return next;
        });
        if (i < reply.length) {
          setTimeout(tick, 22 + Math.random()*35);
        } else {
          setRunning(false);
        }
      };
      setTimeout(tick, m.latency * 0.5);
    } else {
      setTimeout(() => {
        setMessages(prev => {
          const next = [...prev];
          next[next.length - 1] = { role: 'assistant', content: reply, streaming: false, meta: { tokens: outTok, cost, latency: m.latency, inTok, model } };
          return next;
        });
        setRunning(false);
      }, m.latency);
    }
  };

  return (
    <div className="page" style={{ paddingBottom: 24, maxWidth: 1600 }}>
      <div className="page-h">
        <div>
          <h1>Playground</h1>
          <div className="sub">Test any model with live streaming. Every run is billed to your balance at live pricing.</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 18, height: 'calc(100vh - 200px)', minHeight: 560 }}>
        {/* Chat pane */}
        <div className="card" style={{ padding: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12 }}>
            <span className="prov">
              <span className="prov-dot" style={{ background: WT.PROVIDER_COLORS[m.provider], width: 10, height: 10, borderRadius: 3 }}/>
              <span style={{ fontFamily: 'var(--font-sans)', fontWeight: 500 }}>{m.name}</span>
            </span>
            <span className="dim" style={{ fontSize: 11, fontFamily: 'var(--font-mono)' }}>{m.id}</span>
            <div style={{ flex: 1 }}/>
            <span className="badge">${m.in.toFixed(2)} in · ${m.out.toFixed(2)} out / 1M</span>
            <button className="btn sm" onClick={() => setMessages([messages[0]])}>Clear</button>
          </div>
          <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px', display: 'flex', flexDirection: 'column', gap: 18 }}>
            {messages.map((msg, i) => (
              <div key={i} style={{ display: 'flex', gap: 14 }}>
                <div style={{ width: 28, height: 28, borderRadius: 6, background: msg.role === 'user' ? 'var(--accent)' : 'var(--bg-sunken)', color: msg.role === 'user' ? 'var(--accent-ink)' : 'var(--ink-2)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 600, flexShrink: 0 }}>
                  {msg.role === 'user' ? 'U' : 'W'}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 11, color: 'var(--ink-3)', marginBottom: 4 }}>{msg.role === 'user' ? 'You' : m.name}</div>
                  <div style={{ fontSize: 13.5, whiteSpace: 'pre-wrap', lineHeight: 1.6 }}>
                    {msg.content}
                    {msg.streaming && <span style={{ display: 'inline-block', width: 6, height: 14, background: 'var(--ink)', marginLeft: 2, verticalAlign: 'middle', animation: 'blink 1s infinite' }}/>}
                  </div>
                  {msg.meta && msg.meta.tokens > 0 && !msg.streaming && (
                    <div style={{ display: 'flex', gap: 14, marginTop: 8, fontSize: 11, color: 'var(--ink-3)', fontFamily: 'var(--font-mono)' }}>
                      <span>{WT.fmt.num(msg.meta.inTok)} in / {WT.fmt.num(msg.meta.tokens)} out</span>
                      <span>${msg.meta.cost.toFixed(5)}</span>
                      <span>{WT.fmt.ms(msg.meta.latency)}</span>
                    </div>
                  )}
                </div>
              </div>
            ))}
          </div>
          <div style={{ padding: 14, borderTop: '1px solid var(--line)', display: 'flex', gap: 10 }}>
            <textarea className="textarea" rows={2} style={{ flex: 1, fontFamily: 'var(--font-sans)', fontSize: 13 }} value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) run(); }} placeholder="Type a message… ⌘+Enter to send"/>
            <button className="btn primary" onClick={run} disabled={running || !input.trim()} style={{ alignSelf: 'stretch', padding: '0 18px' }}>
              {running ? 'Running…' : (<><Icon name="send" size={13}/> Send</>)}
            </button>
          </div>
        </div>

        {/* Controls */}
        <div className="card" style={{ padding: 20, overflowY: 'auto' }}>
          <div className="card-h" style={{ marginBottom: 14 }}><h3>Parameters</h3></div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div className="field">
              <label>Model</label>
              <select className="select" value={model} onChange={e => setModel(e.target.value)}>
                {WT.MODELS.filter(x => x.origin === 'CN').map(x => (
                  <option key={x.id} value={x.id}>{x.name} — ${x.in.toFixed(2)}/${x.out.toFixed(2)}</option>
                ))}
              </select>
            </div>
            <div className="field">
              <label>Sample prompts</label>
              <div className="seg">
                {Object.keys(samples).map(k => (
                  <button key={k} onClick={() => setInput(samples[k])}>{k}</button>
                ))}
              </div>
            </div>
            <div className="field">
              <label>System message</label>
              <textarea className="textarea" rows={3} value={system} onChange={e => setSystem(e.target.value)}/>
            </div>
            <div className="field">
              <label>Temperature — <span className="mono">{temp.toFixed(2)}</span></label>
              <input type="range" min="0" max="2" step="0.05" value={temp} onChange={e => setTemp(+e.target.value)}/>
            </div>
            <div className="field">
              <label>Max tokens — <span className="mono">{maxTok}</span></label>
              <input type="range" min="64" max="8192" step="64" value={maxTok} onChange={e => setMaxTok(+e.target.value)}/>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 12 }}>Stream response</span>
              <div className={'switch' + (stream ? ' on' : '')} onClick={() => setStream(!stream)}/>
            </div>
          </div>
          <div style={{ marginTop: 20, padding: 12, background: 'var(--bg-sunken)', border: '1px solid var(--line)', borderRadius: 6, fontSize: 11.5 }}>
            <div className="dim" style={{ marginBottom: 4, textTransform: 'uppercase', fontSize: 10, letterSpacing: '0.08em' }}>Estimated cost this run</div>
            <div className="mono tabular" style={{ fontSize: 16, fontWeight: 500 }}>${((input.length/3.5/1e6)*m.in + (maxTok/1e6)*m.out).toFixed(5)}</div>
          </div>
        </div>
      </div>
      <style>{`@keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }`}</style>
    </div>
  );
}
Object.assign(window, { Playground });
