/* Apple Music-agent: enhetsvelger og administrasjonsdialog.
 * Loaded as a Babel script i begge skjermer, etter shared/auth-ui.jsx og shared/source-ui.jsx. Relies on globals:
 * React, PC (design tokens), window.TaktAgent, AuthScreen/useAuthUser (auth-ui.jsx).
 *
 *   <AppleAgentPicker />      enhetsvelger (erstatter SpotifyDevicePicker når aktiv avspiller er Apple Music)
 *   <AppleAgentDialogHost />  monteres én gang per skjerm; åpner dialogen ved hendelsen `takt:apple-agent-dialog`
 *                              (kilden sender den fra login(), dvs. når brukeren klikker statusfeltet / «koble til»-knappen)
 *
 * Dialogen dekker de tre tilstandene «ikke innlogget», «ingen agent paret» og «velg/administrer Mac-er», pluss selve
 * paringen: agenten viser en kode i terminalen, brukeren taster den her (POST /api/agent/pair/claim). */

function useTaktAgent() {
  const [, bump] = React.useReducer(n => n + 1, 0);
  React.useEffect(() => {
    window.TaktAgent.start();
    return window.TaktAgent.onChange(bump);
  }, []);
  return window.TaktAgent;
}

function openAppleAgentDialog() {
  window.dispatchEvent(new CustomEvent('takt:apple-agent-dialog'));
}

const agentFont = "'Archivo',sans-serif";

function AppleAgentPicker({ style }) {
  const A = useTaktAgent();
  const wrap = { display: 'flex', alignItems: 'center', gap: 7, ...style };
  const hint = { fontFamily: agentFont, fontSize: 11, fontWeight: 600, color: PC.z3, letterSpacing: '0.04em', whiteSpace: 'nowrap' };
  const linkBtn = {
    padding: '5px 10px', borderRadius: 5, border: `1px solid ${PC.accent}`, background: 'transparent', color: PC.accent,
    fontFamily: agentFont, fontWeight: 700, fontSize: 11, cursor: 'pointer', whiteSpace: 'nowrap',
  };
  const gear = (
    <button onClick={openAppleAgentDialog} title="Administrer Apple Music-agenter"
      style={{ width: 28, height: 28, borderRadius: 5, border: `1px solid ${PC.line2}`, background: PC.paper, color: PC.muted, fontSize: 14, cursor: 'pointer', flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>⚙</button>
  );

  if (!A.userId()) {
    return (
      <div style={wrap}>
        <span style={hint}>{A.authResolved() ? 'Logg inn i Takt for Apple Music' : 'Kobler til…'}</span>
        {A.authResolved() && <button onClick={openAppleAgentDialog} style={linkBtn}>Logg inn…</button>}
      </div>
    );
  }
  const devices = A.devices();
  if (!devices.length) {
    return (
      <div style={wrap}>
        <span style={hint}>{A.connState() === 'connected' ? 'Ingen Mac er paret' : 'Kobler til…'}</span>
        {A.connState() === 'connected' && <button onClick={openAppleAgentDialog} style={linkBtn}>Par agent…</button>}
      </div>
    );
  }
  const sel = A.selected();
  return (
    <div style={wrap}>
      <select value={sel ? sel.deviceId : ''} onChange={e => A.selectDevice(e.target.value)}
        style={{ padding: '6px 28px 6px 10px', borderRadius: 5, border: `1px solid ${sel && sel.online ? PC.z2 : PC.line2}`, background: PC.paper,
          fontFamily: agentFont, fontSize: 12, fontWeight: 600, color: PC.ink, outline: 'none', maxWidth: 200, cursor: 'pointer' }}>
        {!sel && <option value="">Velg Mac…</option>}
        {devices.map(d => <option key={d.deviceId} value={d.deviceId}>{d.deviceName}{d.online ? '' : ' (frakoblet)'}</option>)}
      </select>
      {gear}
    </div>
  );
}

function formatPairCode(raw) {
  const c = String(raw).toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8);
  return c.length > 4 ? c.slice(0, 4) + '-' + c.slice(4) : c;
}

function claimErrorText(r) {
  if (r.status === 404 || r.error === 'unknown-code') return 'Koden finnes ikke, er allerede brukt, eller har utløpt (den gjelder i 10 minutter). Start paringen på nytt i terminalen.';
  if (r.status === 409 || r.error === 'too-many-devices') return 'Du har nådd grensen på 10 enheter. Koble fra en eldre først.';
  if (r.status === 429 || r.error === 'rate-limited') return 'For mange forsøk. Vent et minutt og prøv igjen.';
  if (r.status === 401 || r.error === 'unauthorized') return 'Innloggingen din har utløpt. Last siden på nytt.';
  if (r.error === 'network') return 'Ingen kontakt med Takt-serveren. Sjekk nettforbindelsen.';
  return `Noe gikk galt (${r.status || r.error || 'ukjent feil'}). Prøv igjen.`;
}

function AppleAgentDialog({ onClose }) {
  const A = useTaktAgent();
  const user = useAuthUser();
  const [code, setCode] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState(null);              // { kind: 'ok' | 'error', text }
  const [confirmId, setConfirmId] = React.useState(null);  // enhet som er i ferd med å kobles fra

  const submit = async e => {
    e.preventDefault();
    if (code.replace('-', '').length !== 8) { setMsg({ kind: 'error', text: 'Koden har 8 tegn, f.eks. ABCD-2345.' }); return; }
    setBusy(true); setMsg(null);
    const r = await A.claim(code);
    setBusy(false);
    if (r.ok) { setCode(''); setMsg({ kind: 'ok', text: `Koblet til «${(r.json && r.json.deviceName) || 'Mac'}». Agenten henter tilgangen i løpet av noen sekunder.` }); }
    else setMsg({ kind: 'error', text: claimErrorText(r) });
  };

  const remove = async id => {
    setBusy(true);
    const r = await A.removeDevice(id);
    setBusy(false); setConfirmId(null);
    if (!r.ok && r.status !== 404) setMsg({ kind: 'error', text: 'Kunne ikke koble fra enheten. Prøv igjen.' });
  };

  const conn = A.connState();
  const connText = conn === 'connected' ? 'Koblet til Takt-serveren'
    : conn === 'connecting' ? 'Kobler til Takt-serveren…'
    : conn === 'error' ? `Ingen kontakt med Takt-serveren${A.lastError() ? ` (${A.lastError()})` : ''}` : '';
  const devices = A.devices();
  const sel = A.selected();

  const label = { fontFamily: agentFont, fontWeight: 700, fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: PC.muted, marginBottom: 8 };
  const text = { fontFamily: agentFont, fontSize: 13, color: PC.ink2, lineHeight: 1.6 };
  const mono = { fontFamily: "'Space Mono',monospace", fontSize: 11, background: PC.bg, border: `1px solid ${PC.line}`, borderRadius: 3, padding: '1px 5px', color: PC.ink };
  const smallBtn = (color, extra) => ({ padding: '5px 10px', borderRadius: 4, border: `1px solid ${color}`, background: 'transparent', color, fontFamily: agentFont, fontWeight: 700, fontSize: 11, cursor: 'pointer', ...extra });

  return (
    <div onClick={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 400, backdropFilter: 'blur(3px)', padding: 16 }}>
      <div style={{ background: PC.paper, border: `1px solid ${PC.line2}`, borderRadius: 8, width: 'min(520px, 100%)', maxHeight: '90vh', overflowY: 'auto', padding: 26, boxSizing: 'border-box' }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontFamily: agentFont, fontWeight: 800, fontSize: 18, color: PC.ink, flex: 1 }}>Apple Music-agent</div>
          <button onClick={onClose} aria-label="Lukk" style={{ background: 'transparent', border: 'none', fontSize: 18, color: PC.muted, cursor: 'pointer', lineHeight: 1 }}>✕</button>
        </div>

        {!user ? (
          <>
            <div style={{ ...text, marginBottom: 16 }}>
              Apple Music styres fra en liten agent på Macen din, og agenten kobles til kontoen din i Takt. Logg inn først.
            </div>
            <AuthScreen compact onSuccess={() => {}} />
          </>
        ) : (
          <>
            <div style={{ ...text, marginBottom: 14 }}>
              Agenten kjører på Macen med Musikk-appen og lar Takt starte og styre musikken. Den kobler seg selv ut til Takt — du åpner ingenting i brannmuren.
            </div>
            {connText && (
              <div style={{ fontFamily: agentFont, fontSize: 11, fontWeight: 600, color: conn === 'connected' ? PC.z2 : conn === 'error' ? PC.z5 : PC.muted, marginBottom: 14 }}>{connText}</div>
            )}

            <div style={label}>Dine Mac-er</div>
            {devices.length === 0 ? (
              <div style={{ ...text, color: PC.muted, marginBottom: 16 }}>Ingen Mac er paret ennå.</div>
            ) : (
              <div style={{ border: `1px solid ${PC.line}`, borderRadius: 6, marginBottom: 16 }}>
                {devices.map((d, i) => (
                  <div key={d.deviceId} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px', borderTop: i ? `1px solid ${PC.line}` : 'none' }}>
                    <span title={d.online ? 'Tilkoblet' : 'Frakoblet'} style={{ width: 9, height: 9, borderRadius: '50%', flexShrink: 0, background: d.online ? PC.z2 : 'transparent', border: `2px solid ${d.online ? PC.z2 : PC.dim}`, boxSizing: 'border-box' }} />
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ fontFamily: agentFont, fontSize: 13, fontWeight: 700, color: PC.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.deviceName}</div>
                      <div style={{ fontFamily: agentFont, fontSize: 11, color: PC.muted }}>
                        {d.online ? (d.musicRunning === false ? 'Tilkoblet · Musikk er ikke åpen (starter ved avspilling)' : 'Tilkoblet') : 'Frakoblet — start agenten på Macen'}
                        {d.status && d.status.problem === 'automation-denied' ? ' · mangler tilgang til Musikk' : ''}
                      </div>
                    </div>
                    {confirmId === d.deviceId ? (
                      <div style={{ display: 'flex', gap: 6 }}>
                        <button disabled={busy} onClick={() => remove(d.deviceId)} style={smallBtn(PC.z5)}>Koble fra</button>
                        <button disabled={busy} onClick={() => setConfirmId(null)} style={smallBtn(PC.muted)}>Avbryt</button>
                      </div>
                    ) : (
                      <div style={{ display: 'flex', gap: 6 }}>
                        {sel && sel.deviceId === d.deviceId
                          ? <span style={{ fontFamily: agentFont, fontSize: 11, fontWeight: 700, color: PC.z2, alignSelf: 'center' }}>I bruk</span>
                          : <button onClick={() => A.selectDevice(d.deviceId)} style={smallBtn(PC.accent)}>Bruk denne</button>}
                        <button onClick={() => setConfirmId(d.deviceId)} title="Tilbakekall tilgangen til denne Macen" style={smallBtn(PC.muted)}>Koble fra</button>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}

            <div style={label}>Koble til en ny Mac</div>
            <ol style={{ ...text, margin: '0 0 12px', paddingLeft: 20 }}>
              <li>På Macen: åpne Terminal, gå til <span style={mono}>agent</span>-mappen i Takt-prosjektet og kjør <span style={mono}>npm install</span>, deretter <span style={mono}>npm run install-agent</span>.</li>
              <li>Agenten viser en kode som <span style={mono}>ABCD-2345</span> i terminalen og som varsling.</li>
              <li>Skriv koden her (den gjelder i 10 minutter):</li>
            </ol>
            <form onSubmit={submit} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
              <input value={code} onChange={e => setCode(formatPairCode(e.target.value))} placeholder="ABCD-2345" autoComplete="off" spellCheck={false} maxLength={9}
                style={{ flex: 1, padding: '9px 11px', background: PC.bg, border: `1px solid ${PC.line}`, borderRadius: 4, fontFamily: "'Space Mono',monospace", fontSize: 16, letterSpacing: '0.12em', color: PC.ink, outline: 'none', boxSizing: 'border-box', minWidth: 0 }} />
              <button type="submit" disabled={busy || code.replace('-', '').length !== 8}
                style={{ padding: '9px 16px', borderRadius: 4, border: 'none', background: PC.accent, color: '#fff', fontFamily: agentFont, fontWeight: 700, fontSize: 13, cursor: busy ? 'default' : 'pointer', opacity: busy || code.replace('-', '').length !== 8 ? 0.5 : 1 }}>
                {busy ? 'Kobler…' : 'Koble til'}
              </button>
            </form>
            {msg && (
              <div style={{ margin: '8px 0 0', padding: '9px 11px', borderRadius: 4, fontFamily: agentFont, fontSize: 12, fontWeight: 600, lineHeight: 1.5,
                background: msg.kind === 'ok' ? `${PC.z2}14` : `${PC.z5}12`, border: `1px solid ${msg.kind === 'ok' ? PC.z2 : PC.z5}40`, color: msg.kind === 'ok' ? PC.z2 : PC.z5 }}>{msg.text}</div>
            )}
            <div style={{ ...text, fontSize: 11, color: PC.muted, marginTop: 14 }}>
              Første gang spør macOS om <span style={mono}>node</span> får styre <span style={mono}>Musikk</span> — velg OK. Krever Apple Music i Musikk-appen.
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function AppleAgentDialogHost() {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const h = () => setOpen(true);
    window.addEventListener('takt:apple-agent-dialog', h);
    return () => window.removeEventListener('takt:apple-agent-dialog', h);
  }, []);
  return open ? <AppleAgentDialog onClose={() => setOpen(false)} /> : null;
}

Object.assign(window, { AppleAgentPicker, AppleAgentDialogHost, openAppleAgentDialog });
