// DevPanel.jsx — right rail. Controlled by settings prop from App.
function DevPanel({ settings, onChangeSettings, usage }) {
  const [tab, setTab] = React.useState('params');
  const temp   = (settings && typeof settings.default_temp === 'number') ? settings.default_temp : 0.2;
  const topP   = (settings && typeof settings.default_top_p === 'number') ? settings.default_top_p : 0.95;
  const maxTok = (settings && typeof settings.default_max_tokens === 'number') ? settings.default_max_tokens : 512;
  const serverUrl = (window.API && window.API.serverUrl) || 'http://127.0.0.1:8000';
  const llmUrl    = (window.API && window.API.llmUrl)    || 'http://100.106.148.2:8091';

  // Live model identity from /v1/models. The Rust proxy ignores client-side
  // `model` and always serves whatever the M3 sidecar has loaded — so picking
  // from a static dropdown would be misleading. Show what's actually live and
  // let the LLM team rotate it via CPN_VERSION on the sidecar.
  const [liveModel, setLiveModel] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    window.API.liveModel().then(id => { if (!cancelled) setLiveModel(id); });
    return () => { cancelled = true; };
  }, []);
  const model = liveModel || (settings && settings.default_model) || 'GBR-LM';

  const set = (k, v) => onChangeSettings && onChangeSettings({ [k]: v });

  return (
    <aside className="ch-side">
      <div className="ch-side-head">
        <h3>플레이그라운드</h3>
        <div className="seg">
          <button className={tab==='params'?'on':''} onClick={() => setTab('params')}>파라미터</button>
          <button className={tab==='api'?'on':''} onClick={() => setTab('api')}>API</button>
        </div>
      </div>

      {tab === 'params' && <>
        <div className="ch-side-section">
          <h4>인증 서버 <span style={{color:'var(--fg-5)',fontWeight:400,letterSpacing:0,fontSize:9.5,textTransform:'none'}}>· canon_lm_server</span></h4>
          <input
            className="ch-select" type="text" defaultValue={serverUrl}
            spellCheck="false" autoCapitalize="off"
            onBlur={e => {
              const next = e.target.value.trim();
              if (next && next !== serverUrl) {
                window.API.setServerUrl(next);
                location.reload();
              }
            }}
          />
        </div>

        <div className="ch-side-section">
          <h4>LLM 서버 <span style={{color:'var(--fg-5)',fontWeight:400,letterSpacing:0,fontSize:9.5,textTransform:'none'}}>· zigu_engine_rs (M3)</span></h4>
          <input
            className="ch-select" type="text" defaultValue={llmUrl}
            spellCheck="false" autoCapitalize="off"
            onBlur={e => {
              const next = e.target.value.trim();
              if (next && next !== llmUrl) {
                window.API.setLlmUrl(next);
                location.reload();
              }
            }}
          />
        </div>

        <div className="ch-side-section">
          <h4>모델 <span style={{color:'var(--fg-5)',fontWeight:400,letterSpacing:0,fontSize:9.5,textTransform:'none'}}>· /v1/models 자동감지</span></h4>
          <div className="ch-keychip">
            <span className="label" style={{fontFamily:'var(--font-mono)'}}>{liveModel || '— 엔진 응답 대기 중 —'}</span>
          </div>
          <div style={{marginTop:6,fontSize:11,color:'var(--fg-5)'}}>
            변경: M3 의 <code>CPN_VERSION</code> 환경변수 (예: <code>v22.lm</code>) 로 사이드카 재기동.
          </div>
        </div>

        <div className="ch-side-section">
          <h4>샘플링</h4>
          <div className="ch-field">
            <div className="ch-field-top"><span className="name">Temperature</span><span className="val">{temp.toFixed(2)}</span></div>
            <input type="range" className="ch-slider" min="0" max="2" step="0.01" value={temp} onChange={e => set('default_temp', +e.target.value)}/>
          </div>
          <div className="ch-field">
            <div className="ch-field-top"><span className="name">Top-p</span><span className="val">{topP.toFixed(2)}</span></div>
            <input type="range" className="ch-slider" min="0" max="1" step="0.01" value={topP} onChange={e => set('default_top_p', +e.target.value)}/>
          </div>
          <div className="ch-field">
            <div className="ch-field-top"><span className="name">Max tokens</span><span className="val">{maxTok}</span></div>
            <input type="range" className="ch-slider" min="128" max="4096" step="128" value={maxTok} onChange={e => set('default_max_tokens', +e.target.value)}/>
          </div>
        </div>

        <div className="ch-side-section">
          <h4>사용량 · 현재 대화</h4>
          <div className="ch-usage">
            <div className="item">
              <div className="lbl">턴 수</div>
              <div className="v">{(usage && usage.turns) || 0}</div>
              <div className="sub">유저 + 응답</div>
            </div>
            <div className="item">
              <div className="lbl">문자</div>
              <div className="v">{(usage && usage.chars) || 0}</div>
              <div className="sub">마지막 응답</div>
            </div>
            <div className="item">
              <div className="lbl">소요</div>
              <div className="v">{usage && usage.elapsed ? usage.elapsed.toFixed(2) : '0.00'}</div>
              <div className="sub">마지막 턴 (s)</div>
            </div>
            <div className="item">
              <div className="lbl">tok/s</div>
              <div className="v">{usage && usage.cps ? Math.round(usage.cps) : 0}</div>
              <div className="sub">처리량</div>
            </div>
          </div>
        </div>
      </>}

      {tab === 'api' && <>
        <div className="ch-side-section">
          <h4>Chat endpoint <span style={{color:'var(--fg-5)',fontWeight:400,letterSpacing:0,fontSize:9.5,textTransform:'none'}}>· Rust M3</span></h4>
          <div className="ch-keychip">
            <span className="label">{llmUrl}/v1/chat/completions</span>
          </div>
        </div>
        <div className="ch-side-section">
          <h4>Equivalent cURL</h4>
          <div className="ch-curl">
<span className="c"># POST /v1/chat/completions (no auth on Rust engine)</span>{'\n'}
curl {llmUrl}/<span className="k">v1/chat/completions</span> \{'\n'}
&nbsp;&nbsp;-H <span className="s">"Content-Type: application/json"</span> \{'\n'}
&nbsp;&nbsp;-d <span className="s">'{'{'}</span>{'\n'}
&nbsp;&nbsp;&nbsp;&nbsp;<span className="k">"model"</span>: <span className="s">"{model}"</span>,{'\n'}
&nbsp;&nbsp;&nbsp;&nbsp;<span className="k">"messages"</span>: [...],{'\n'}
&nbsp;&nbsp;&nbsp;&nbsp;<span className="k">"stream"</span>: <span className="s">true</span>,{'\n'}
&nbsp;&nbsp;&nbsp;&nbsp;<span className="k">"temperature"</span>: {temp.toFixed(2)},{'\n'}
&nbsp;&nbsp;&nbsp;&nbsp;<span className="k">"top_p"</span>: {topP.toFixed(2)},{'\n'}
&nbsp;&nbsp;&nbsp;&nbsp;<span className="k">"max_tokens"</span>: {maxTok}{'\n'}
&nbsp;&nbsp;<span className="s">{'}'}'</span>
          </div>
        </div>
        <div className="ch-side-section">
          <h4>Backend</h4>
          <div className="ch-usage">
            <div className="item"><div className="lbl">Engine</div><div className="v" style={{fontSize:'13px'}}>zigu_engine_rs</div><div className="sub">Rust · axum · tch</div></div>
            <div className="item"><div className="lbl">Host</div><div className="v" style={{fontSize:'11px'}}>M3</div><div className="sub">via Tailscale</div></div>
          </div>
        </div>
      </>}
    </aside>
  );
}
window.DevPanel = DevPanel;
