/* Shared Spotify Connect device picker.
 * Loaded as a Babel script in both the instructor screen and the planner.
 * Relies on globals: React, PC (design tokens), window.TaktSpotify.
 *
 * Renders a device <select> + refresh, or the "open Spotify first" message
 * when no devices are reachable. Returns null when not logged in. */
function SpotifyDevicePicker({ style, onChange }) {
  const [devices, setDevices] = React.useState([]);
  const [active,  setActive]  = React.useState(() => window.TaktSpotify?.getActiveDevice() || '');
  const [loading, setLoading] = React.useState(false);
  const [loggedIn, setLoggedIn] = React.useState(() => !!window.TaktSpotify?.isLoggedIn());

  const refresh = React.useCallback(async () => {
    if (!window.TaktSpotify?.isLoggedIn()) { setLoggedIn(false); return; }
    setLoggedIn(true);
    setLoading(true);
    const r = await window.TaktSpotify.getDevices();
    setLoading(false);
    setDevices(r.ok ? r.items : []);
    setActive(window.TaktSpotify.getActiveDevice() || '');
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  // Re-check login after the OAuth redirect lands.
  React.useEffect(() => {
    const id = setInterval(() => {
      const li = !!window.TaktSpotify?.isLoggedIn();
      setLoggedIn(prev => { if (li && !prev) refresh(); return li; });
    }, 1500);
    return () => clearInterval(id);
  }, [refresh]);

  if (!loggedIn) return null;

  const choose = (id) => {
    window.TaktSpotify.setActiveDevice(id);
    setActive(id);
    if (onChange) onChange(id);
  };

  const wrap = { display: 'flex', alignItems: 'center', gap: 7, ...style };

  const refreshBtn = (
    <button onClick={refresh} title="Oppdater enheter" disabled={loading}
      style={{ width: 28, height: 28, borderRadius: 5, border: `1px solid ${PC.line2}`, background: PC.paper,
        color: PC.muted, fontSize: 13, cursor: loading ? 'default' : 'pointer', flexShrink: 0,
        display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      {loading ? '…' : '↻'}
    </button>
  );

  if (devices.length === 0) {
    return (
      <div style={wrap}>
        <span style={{ fontFamily: "'Archivo',sans-serif", fontSize: 11, fontWeight: 600, color: PC.z3,
          letterSpacing: '0.04em', whiteSpace: 'nowrap' }}>
          {loading ? 'Søker etter enheter…' : 'Åpne Spotify og start en sang først'}
        </span>
        {refreshBtn}
      </div>
    );
  }

  return (
    <div style={wrap}>
      <select value={active} onChange={e => choose(e.target.value)}
        style={{ padding: '6px 28px 6px 10px', borderRadius: 5, border: `1px solid ${active ? PC.z2 : PC.line2}`,
          background: PC.paper, fontFamily: "'Archivo',sans-serif", fontSize: 12, fontWeight: 600,
          color: PC.ink, outline: 'none', maxWidth: 200, cursor: 'pointer' }}>
        {!active && <option value="">Velg enhet…</option>}
        {devices.map(d => (
          <option key={d.id} value={d.id}>{d.name}{d.type ? ` · ${d.type}` : ''}</option>
        ))}
      </select>
      {refreshBtn}
    </div>
  );
}

window.SpotifyDevicePicker = SpotifyDevicePicker;
