const { useState: aUseState, useEffect: aUseEffect, useCallback: aUseCallback } = React;

function AutonomyPanel({ open, onClose }) {
  if (!open) return null;
  const [data, setData] = aUseState(null);
  const [loading, setLoading] = aUseState(true);
  const [err, setErr] = aUseState('');
  const [saving, setSaving] = aUseState(false);

  const load = aUseCallback(async () => {
    setLoading(true);
    try {
      const r = await fetch('/api/autonomy/status');
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      setData(await r.json());
      setErr('');
    } catch (e) {
      setErr(String(e.message || e));
    } finally {
      setLoading(false);
    }
  }, []);

  const setMode = aUseCallback(async (mode) => {
    if (saving) return;
    setSaving(true);
    try {
      const r = await fetch('/api/autonomy/mode', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mode }),
      });
      if (!r.ok) throw new Error(`HTTP ${r.status}`);
      await load();
    } catch (e) {
      setErr(String(e.message || e));
    } finally {
      setSaving(false);
    }
  }, [saving, load]);

  aUseEffect(() => { load(); }, [load]);

  const mode = data?.mode || 'copilot';
  const modes = data?.allowed_modes || ['manual', 'copilot', 'autonomous'];

  return (
    <div style={{ position:'fixed', inset:0, zIndex:105, background:'rgba(10,10,12,0.86)', backdropFilter:'blur(8px)', padding:'52px 16px' }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{ maxWidth:760, margin:'0 auto', background:'var(--bg)', border:'1px solid var(--line-2)', borderRadius:6, padding:22 }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:12 }}>
          <h2 style={{ margin:0, fontFamily:'Instrument Serif, serif', fontStyle:'italic' }}>Autonomy Control Center</h2>
          <button onClick={onClose}>close</button>
        </div>
        {err && <div style={{ color:'#d96a6a', marginBottom:8 }}>⚠ {err}</div>}
        <div style={{ marginBottom:12 }}>
          <div style={{ fontSize:11, color:'var(--text-dim)', marginBottom:8 }}>Mode</div>
          <div style={{ display:'flex', gap:8 }}>
            {modes.map(m => (
              <button key={m} onClick={() => setMode(m)} disabled={saving || mode===m}
                style={{ padding:'6px 10px', border:'1px solid var(--line)', background: mode===m ? 'rgba(95,179,124,0.2)' : 'transparent', color:'var(--text)' }}>
                {m}
              </button>
            ))}
          </div>
        </div>
        <div style={{ marginBottom:10, fontSize:11, color:'var(--text-dim)' }}>
          Queue: {data?.queues?.pending_trade_recs ?? '—'} pending recs · {data?.queues?.open_alerts ?? '—'} open alerts
        </div>
        <div style={{ marginBottom:10, fontSize:10, color:'var(--text-dim)' }}>
          Last mode change: {data?.mode_updated_at ? new Date(data.mode_updated_at).toLocaleString() : '—'}
        </div>
        <div style={{ borderTop:'1px solid var(--line)', paddingTop:10 }}>
          <div style={{ fontSize:11, color:'var(--text-dim)', marginBottom:8 }}>Schedulers / Jobs</div>
          {loading && <div style={{ fontSize:12 }}>Loading…</div>}
          {(data?.jobs || []).map(j => (
            <div key={j.id} style={{ display:'flex', justifyContent:'space-between', fontFamily:"'JetBrains Mono', monospace", fontSize:11, padding:'3px 0' }}>
              <span>{j.label}</span><span style={{ color:'#5fb37c' }}>{j.state}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.AutonomyPanel = AutonomyPanel;
