/* ============================================
   VISUALIZERS — song-window stage + full screen
   Reads the app's existing analyser (window.__amsAudio). On iOS the app never builds
   a Web Audio graph (it would kill lock-screen playback), so visuals run in an
   ambient, time-driven mode there and say so.
   ============================================ */
const VIZ_KEY = 'ams-visualizer';
const VIZ_LIST = [
  { id: 'halo',     name: 'Halo',         note: 'The artwork in a ring that breathes with the bass' },
  { id: 'spectrum', name: 'Spectrum',     note: 'Frequency bars, lows on the left' },
  { id: 'scope',    name: 'Scope',        note: 'The waveform, drawn live' },
  { id: 'orbit',    name: 'Orbit',        note: 'Particles thrown out on every kick' },
  { id: 'aurora',   name: 'Maker aurora', note: 'Colour fields in the track’s maker colours' },
  { id: 'tunnel',   name: 'Tunnel',       note: 'Rings rushing toward you on the beat' },
  { id: 'milkdrop', name: 'MilkDrop',     note: '100 classic community presets · loads about 850 KB' },
];
const MILKDROP_SRC = [
  'https://cdn.jsdelivr.net/npm/butterchurn@2.6.7/lib/butterchurn.min.js',
  'https://cdn.jsdelivr.net/npm/butterchurn-presets@2.4.7/lib/butterchurnPresets.min.js',
];

// Maker colours on the always-dark stage
function vizColors(tag) {
  if (tag === 'human') return ['#67e8f9', '#e0fbff'];
  if (tag === 'ai')    return ['#a78bfa', '#f0e6ff'];
  return ['#a78bfa', '#67e8f9'];
}

// Load the MilkDrop engine + presets once, on demand
let _milkdropPromise = null;
function loadMilkdrop() {
  if (_milkdropPromise) return _milkdropPromise;
  _milkdropPromise = MILKDROP_SRC.reduce((p, src) => p.then(() => new Promise((res, rej) => {
    const s = document.createElement('script');
    s.src = src; s.async = true; s.crossOrigin = 'anonymous';
    s.onload = res; s.onerror = () => rej(new Error('Could not load ' + src));
    document.head.appendChild(s);
  })), Promise.resolve()).catch(e => { _milkdropPromise = null; throw e; });
  return _milkdropPromise;
}

// The UMD builds expose their API either directly or under .default, depending on version
const mdEngine  = () => window.butterchurn?.default || window.butterchurn;
const mdPresets = () => (window.butterchurnPresets?.default || window.butterchurnPresets).getPresets();

/* ---------- audio frame: live analyser or ambient fallback ---------- */
const _freq = new Uint8Array(128);
const _time = new Uint8Array(256);
function readAudio(t, live) {
  const an = live ? window.__amsAudio?.analyser?.() : null;
  if (an) {
    an.getByteFrequencyData(_freq);
    an.getByteTimeDomainData(_time);
    return { freq: _freq, time: _time, live: true };
  }
  // Ambient: a slow, believable pulse so the stage never looks dead
  for (let i = 0; i < 128; i++) {
    const fall = 1 - i / 140;
    _freq[i] = Math.max(0, 255 * fall * (0.35 + 0.25 * Math.sin(t * 1.7 + i * 0.21) + 0.15 * Math.sin(t * 3.1 + i * 0.07)));
  }
  for (let i = 0; i < 256; i++) _time[i] = 128 + 40 * Math.sin(t * 2 + i * 0.09) * Math.sin(t * 0.7 + i * 0.013);
  return { freq: _freq, time: _time, live: false };
}
const band = (f, a, b) => { let s = 0; for (let i = a; i < b; i++) s += f[i]; return s / ((b - a) * 255); };

/* ---------- renderers (2D canvas) ---------- */
function makeRenderer(id) {
  const st = { bass: 0, parts: [], rings: [], prevBass: 0, z: 0 };
  const fade = (c, w, h, a) => { c.fillStyle = `rgba(5,5,8,${a})`; c.fillRect(0, 0, w, h); };

  const R = {
    halo(c, w, h, t, au, env) {
      fade(c, w, h, 1);
      const m = Math.min(w, h), cx = w / 2, cy = h * env.cy;
      const r = m * 0.26 * (1 + st.bass * 0.07);
      const n = 96;
      for (let i = 0; i < n; i++) {
        const v = au.freq[Math.floor((i < n / 2 ? i : n - i) * 1.3) + 2] / 255;
        const a = (i / n) * Math.PI * 2 - Math.PI / 2;
        const len = m * (0.02 + 0.2 * v);
        c.strokeStyle = i % 2 ? env.c1 : env.c2;
        c.globalAlpha = 0.35 + 0.65 * v;
        c.lineWidth = Math.max(2, m * 0.008);
        c.lineCap = 'round';
        c.beginPath();
        c.moveTo(cx + Math.cos(a) * (r + m * 0.02), cy + Math.sin(a) * (r + m * 0.02));
        c.lineTo(cx + Math.cos(a) * (r + m * 0.02 + len), cy + Math.sin(a) * (r + m * 0.02 + len));
        c.stroke();
      }
      c.globalAlpha = 1;
      c.save(); c.beginPath(); c.arc(cx, cy, r, 0, Math.PI * 2); c.clip();
      if (env.img && env.img.complete && env.img.naturalWidth) c.drawImage(env.img, cx - r, cy - r, r * 2, r * 2);
      else { const g = c.createLinearGradient(cx - r, cy - r, cx + r, cy + r); g.addColorStop(0, env.c1); g.addColorStop(1, env.c2); c.fillStyle = g; c.fillRect(cx - r, cy - r, r * 2, r * 2); }
      c.restore();
      c.strokeStyle = env.c1; c.globalAlpha = 0.6; c.lineWidth = m * 0.004;
      c.beginPath(); c.arc(cx, cy, r + m * 0.01, 0, Math.PI * 2); c.stroke(); c.globalAlpha = 1;
    },
    spectrum(c, w, h, t, au, env) {
      fade(c, w, h, 1);
      const n = 48, gap = w * 0.004, bw = (w - gap * (n + 1)) / n;
      const g = c.createLinearGradient(0, h, 0, h * 0.15); g.addColorStop(0, env.c1); g.addColorStop(1, env.c2);
      for (let i = 0; i < n; i++) {
        const bin = Math.min(127, Math.floor(Math.pow(i / n, 1.6) * 110) + 1);
        const v = au.freq[bin] / 255, bh = Math.max(h * 0.01, v * h * 0.72), x = gap + i * (bw + gap);
        c.fillStyle = g; c.globalAlpha = 1;
        c.fillRect(x, h * 0.82 - bh, bw, bh);
        c.globalAlpha = 0.18; c.fillRect(x, h * 0.82 + h * 0.01, bw, bh * 0.25);
      }
      c.globalAlpha = 1;
    },
    scope(c, w, h, t, au, env) {
      fade(c, w, h, 0.22);
      const draw = (col, amp, lw, off) => {
        c.strokeStyle = col; c.lineWidth = lw; c.beginPath();
        for (let i = 0; i < 256; i++) {
          const x = (i / 255) * w, y = h / 2 + ((au.time[i] - 128) / 128) * h * amp + off;
          i ? c.lineTo(x, y) : c.moveTo(x, y);
        }
        c.stroke();
      };
      c.globalAlpha = 0.18;                          // soft glow: a wide faint stroke (shadowBlur cost too much)
      draw(env.c1, 0.42, Math.max(8, h * 0.024), 0);
      c.globalAlpha = 1;
      draw(env.c1, 0.42, Math.max(2, h * 0.006), 0);
      c.globalAlpha = 0.5;
      draw(env.c2, 0.30, Math.max(1, h * 0.003), h * 0.01);
      c.globalAlpha = 1;
    },
    orbit(c, w, h, t, au, env) {
      fade(c, w, h, 0.18);
      const cx = w / 2, cy = h * env.cy, m = Math.min(w, h);
      const kick = st.bass - st.prevBass > 0.06;
      const spawn = (kick ? 46 : 3) * (env.reduced ? 0.4 : 1);
      for (let i = 0; i < spawn; i++) st.parts.push({ a: Math.random() * Math.PI * 2, r: m * 0.05, v: m * (0.004 + Math.random() * 0.012) * (1 + st.bass * 2), life: 1, col: Math.random() < 0.5 ? env.c1 : env.c2 });
      st.parts = st.parts.filter(p => (p.life -= 0.012) > 0).slice(-700);
      for (const p of st.parts) {
        p.r += p.v; p.a += 0.004;
        c.globalAlpha = p.life; c.fillStyle = p.col;
        c.beginPath(); c.arc(cx + Math.cos(p.a) * p.r, cy + Math.sin(p.a) * p.r, m * 0.004 + p.life * m * 0.004, 0, Math.PI * 2); c.fill();
      }
      c.globalAlpha = 1;
      const g = c.createRadialGradient(cx, cy, 0, cx, cy, m * (0.08 + st.bass * 0.08));
      g.addColorStop(0, env.c1); g.addColorStop(1, 'rgba(5,5,8,0)'); c.fillStyle = g;
      c.beginPath(); c.arc(cx, cy, m * (0.08 + st.bass * 0.08), 0, Math.PI * 2); c.fill();
    },
    aurora(c, w, h, t, au, env) {
      fade(c, w, h, 0.35);
      const lo = band(au.freq, 1, 8), mid = band(au.freq, 8, 40), hi = band(au.freq, 40, 100);
      c.globalCompositeOperation = 'lighter';
      [[env.c1, lo, 0.7, 0], [env.c2, mid, 0.5, 2], [env.c1, hi, 0.9, 4]].forEach(([col, e, sp, ph]) => {
        const x = w * (0.5 + 0.32 * Math.sin(t * sp * 0.4 + ph)), y = h * (0.5 + 0.28 * Math.cos(t * sp * 0.33 + ph));
        const r = Math.max(w, h) * (0.18 + e * 0.45);
        const g = c.createRadialGradient(x, y, 0, x, y, r);
        g.addColorStop(0, col); g.addColorStop(1, 'rgba(0,0,0,0)');
        c.globalAlpha = 0.25 + e * 0.5; c.fillStyle = g; c.fillRect(0, 0, w, h);
      });
      c.globalCompositeOperation = 'source-over'; c.globalAlpha = 1;
    },
    tunnel(c, w, h, t, au, env) {
      fade(c, w, h, 0.35);
      const cx = w / 2, cy = h * env.cy, m = Math.max(w, h), N = 14;
      st.z = (st.z + 0.004 + st.bass * 0.02) % 1;          // travel speed rises with the bass
      for (let k = N - 1; k >= 0; k--) {
        const d = ((k / N) + st.z) % 1;                    // 0 = far away, 1 = passing the viewer
        const size = m * 0.04 + m * 1.3 * d * d;
        c.strokeStyle = k % 2 ? env.c1 : env.c2;
        c.globalAlpha = Math.min(1, d * 1.6) * (1 - d * 0.4);
        c.lineWidth = Math.max(1.5, size * 0.012);
        c.save(); c.translate(cx, cy); c.rotate(t * 0.12 + d * 1.2);
        c.beginPath();
        if (c.roundRect) c.roundRect(-size / 2, -size / 2, size, size, size * 0.2); else c.rect(-size / 2, -size / 2, size, size);
        c.stroke(); c.restore();
      }
      c.globalAlpha = 1;
    },
  };
  const fn = R[id] || R.halo;
  let first = true;   // wipe the previous visualizer's trails on switch
  return (c, w, h, t, au, env) => {
    if (first) { c.fillStyle = '#050508'; c.fillRect(0, 0, w, h); first = false; }
    st.prevBass = st.bass;
    const b = band(au.freq, 1, 6);
    st.bass += (b - st.bass) * (b > st.bass ? 0.5 : 0.12);
    fn(c, w, h, t, au, env);
  };
}

/* ---------- the stage component ---------- */
function VisualizerStage({ track: pageTrack, isCurrent: pageIsCurrent, nowTrack, isPlaying, onPlay, variant = 'inline', onClose }) {
  const [vizId, setVizIdState] = React.useState(() => { try { return localStorage.getItem(VIZ_KEY) || 'halo'; } catch { return 'halo'; } });
  const setVizId = (id) => { setVizIdState(id); try { localStorage.setItem(VIZ_KEY, id); } catch {} };
  const [full, setFull] = React.useState(variant === 'overlay');
  const [idle, setIdle] = React.useState(false);
  // Follow whatever is playing (skipping or the queue moving on must not strand the stage on the
  // page's song). Paused, the page's track and its "Play this track" come back; full screen keeps
  // the loaded song. (The app preloads a paused track on startup, so "loaded" alone isn't enough.)
  const follow = !!nowTrack && (isPlaying || full);
  const track = follow ? nowTrack : pageTrack;
  const isCurrent = follow || pageIsCurrent;
  const [md, setMd] = React.useState({ state: 'idle', names: [], name: '' });
  const wrapRef = React.useRef(null), c2dRef = React.useRef(null), cglRef = React.useRef(null);
  const mdRef = React.useRef({ viz: null, ctx: null });
  const isIOS = !!window.__amsAudio?.isIOS;
  // iPhone opt-in: analysis only while this is switched on and the screen is on (off by default)
  const [iosLive, setIosLive] = React.useState(false);
  const [iosNeedsTap, setIosNeedsTap] = React.useState(false);
  const live = isCurrent && isPlaying && (!isIOS || iosLive);
  const toggleIosLive = () => {
    const on = !iosLive;
    window.__amsVizIOSLive = on;
    if (on) { window.__amsAudio?.ensure?.(); window.__amsAudio?.ctx?.()?.resume?.().catch(() => {}); }   // inside the tap = the gesture iOS needs
    else window.__amsAudio?.release?.();
    setIosNeedsTap(false);
    setIosLive(on);
  };
  React.useEffect(() => () => { if (isIOS && window.__amsVizIOSLive) { window.__amsVizIOSLive = false; window.__amsAudio?.release?.(); } }, []); // eslint-disable-line
  const env = React.useMemo(() => {
    const [c1, c2] = vizColors(track?.tag);
    const img = new Image();
    if (track?.artworkUrl) img.src = track.artworkUrl;   // drawn only, never read back, so no CORS needed
    return { c1, c2, img, reduced: window.matchMedia?.('(prefers-reduced-motion: reduce)').matches };
  }, [track?.id, track?.artworkUrl, track?.tag]);

  // MilkDrop: load on first pick
  React.useEffect(() => {
    if (vizId !== 'milkdrop' || md.state !== 'idle') return;
    setMd(m => ({ ...m, state: 'loading' }));
    loadMilkdrop().then(() => {
      const names = Object.keys(mdPresets()).sort((a, b) => a.localeCompare(b));
      let saved = ''; try { saved = localStorage.getItem(VIZ_KEY + '-md') || ''; } catch {}
      setMd({ state: 'ready', names, name: names.includes(saved) ? saved : names[Math.floor(Math.random() * names.length)] });
    }).catch(() => setMd(m => ({ ...m, state: 'error' })));
  }, [vizId, md.state]);
  const pickPreset = (name) => { setMd(m => ({ ...m, name })); try { localStorage.setItem(VIZ_KEY + '-md', name); } catch {} };

  // Render loop
  React.useEffect(() => {
    const isMd = vizId === 'milkdrop';
    const cv = isMd ? cglRef.current : c2dRef.current;
    if (!cv) return;
    let raf = 0, visible = true, w = 0, h = 0;
    // Keep drawing cheap so it never competes with the audio: 1.5× pixels on desktop, 1× and
    // 30 fps on phones (full-screen Retina at 2×/60 fps was millions of pixels a frame)
    const coarse = !!window.matchMedia?.('(pointer: coarse)').matches;
    const dpr = Math.min(window.devicePixelRatio || 1, coarse ? 1 : 1.5);
    let last = 0;
    const fit = () => {
      const r = cv.getBoundingClientRect();
      w = Math.max(1, Math.round(r.width * dpr)); h = Math.max(1, Math.round(r.height * dpr));
      if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; mdRef.current.viz?.setRendererSize(w, h); }
    };
    fit();
    const ro = new ResizeObserver(fit); ro.observe(cv);
    const io = new IntersectionObserver(([e]) => { visible = e.isIntersecting; }); io.observe(cv);
    const draw2d = isMd ? null : makeRenderer(vizId);
    const c = isMd ? null : cv.getContext('2d');
    const t0 = performance.now();
    const frame = () => {
      raf = requestAnimationFrame(frame);
      if (!visible) return;
      const now = performance.now();
      if (coarse && now - last < 32) return;
      last = now;
      const t = (now - t0) / 1000;
      if (isMd) {
        const A = window.__amsAudio, ctx = A?.ctx?.(), src = A?.source?.();
        if (md.state !== 'ready' || !md.name) return;
        // (Re)create when the app rebuilds its audio graph (e.g. after returning from background)
        if (ctx && mdRef.current.ctx !== ctx) {
          mdRef.current.viz = mdEngine().createVisualizer(ctx, cv, { width: w, height: h, pixelRatio: 1 });
          if (src) mdRef.current.viz.connectAudio(src);
          mdRef.current.ctx = ctx; mdRef.current.preset = null;
        }
        const viz = mdRef.current.viz;
        if (!viz) return;
        if (mdRef.current.preset !== md.name) {
          viz.loadPreset(mdPresets()[md.name], mdRef.current.preset ? 2.0 : 0);
          mdRef.current.preset = md.name;
        }
        viz.render();
      } else {
        // iPhone live mode: after a lock/unlock the graph is gone — rebuild once a second; iOS may
        // keep the new context suspended until the listener taps, so say so instead of failing silently
        if (isIOS && iosLive && live && document.visibilityState === 'visible' && t - (frame.lastTry || 0) > 1) {
          frame.lastTry = t;
          const A = window.__amsAudio;
          if (!A.analyser()) A.ensure();
          const st8 = A.ctx()?.state, an = A.analyser();
          if (st8 && st8 !== 'running') A.ctx().resume().catch(() => {});   // 'suspended' or iOS 'interrupted'
          // A running graph can still hear nothing (Safari refused the analyser copy's play) — after
          // 3 silent seconds ask for a tap, which rebuilds everything inside the gesture
          let heard = false;
          if (an) { an.getByteFrequencyData(_freq); heard = _freq.some(v => v > 0); }
          frame.quiet = heard ? 0 : (frame.quiet || 0) + 1;
          setIosNeedsTap((!!st8 && st8 !== 'running') || frame.quiet >= 3);
        }
        env.cy = h / dpr < 420 ? 0.4 : 0.5;   // short stages: lift centred visuals clear of the title bar
        draw2d(c, w, h, t, readAudio(t, live), env);
      }
    };
    raf = requestAnimationFrame(frame);
    return () => { cancelAnimationFrame(raf); ro.disconnect(); io.disconnect(); };
  }, [vizId, live, env, md.state, md.name, iosLive]);

  // Full screen: real Fullscreen API where it exists, otherwise fill the window (iPhone Safari)
  const enterFull = () => {
    const el = wrapRef.current;
    if (el?.requestFullscreen && document.fullscreenEnabled) el.requestFullscreen().catch(() => setFull(true));
    else setFull(true);
  };
  const exitFull = () => {
    if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
    setFull(false);
    if (variant === 'overlay') onClose?.();
  };
  React.useEffect(() => {
    // Only react when *this* stage is the full-screen element (the overlay and the track page can both exist)
    const onFs = () => setFull(document.fullscreenElement === wrapRef.current || variant === 'overlay');
    const onKey = (e) => { if (e.key === 'Escape' && full && !document.fullscreenElement) exitFull(); };
    document.addEventListener('fullscreenchange', onFs);
    window.addEventListener('keydown', onKey);
    return () => { document.removeEventListener('fullscreenchange', onFs); window.removeEventListener('keydown', onKey); };
  }, [full, variant]);
  // Opened from the player bar: go properly full screen straight away (the click still counts as the gesture)
  React.useEffect(() => {
    if (variant !== 'overlay') return;
    const el = wrapRef.current;
    if (el?.requestFullscreen && document.fullscreenEnabled) el.requestFullscreen().catch(() => {});
  }, []); // eslint-disable-line

  // Hide controls after 3 s without movement while full screen
  React.useEffect(() => {
    if (!full) { setIdle(false); return; }
    let tm = setTimeout(() => setIdle(true), 3000);
    const wake = () => { setIdle(false); clearTimeout(tm); tm = setTimeout(() => setIdle(true), 3000); };
    const el = wrapRef.current;
    el?.addEventListener('pointermove', wake); el?.addEventListener('pointerdown', wake);
    return () => { clearTimeout(tm); el?.removeEventListener('pointermove', wake); el?.removeEventListener('pointerdown', wake); };
  }, [full]);

  const current = VIZ_LIST.find(v => v.id === vizId) || VIZ_LIST[0];
  const status = !isCurrent ? 'Press play to bring it to life'
    : !isPlaying ? 'Paused'
    : isIOS && !iosLive ? 'Ambient on iPhone · tap Live to react to the music'
    : isIOS && iosNeedsTap ? 'Tap Live again to reconnect'
    : isIOS ? 'Live (beta) · reacting to the music' : 'Live · reacting to the music';
  const mdBlocked = vizId === 'milkdrop' && !live;

  return (
    <section ref={wrapRef} className={`viz-stage${full ? ' viz-full' : ''}${idle ? ' viz-idle' : ''}`} aria-label="Visualizer">
      <canvas ref={c2dRef} className="viz-canvas" hidden={vizId === 'milkdrop'} />
      <canvas ref={cglRef} className="viz-canvas" hidden={vizId !== 'milkdrop'} />

      {mdBlocked && (
        <div className="viz-message">
          {isIOS && !iosLive ? 'On iPhone, MilkDrop needs Live mode. Tap Live (beta) below.'
                 : 'MilkDrop reacts to the audio itself.'}
          {!isIOS && !isCurrent && onPlay && <button className="btn btn-primary btn-sm" onClick={onPlay}><Icon name="play" size={12} /> Play this track</button>}
        </div>
      )}
      {vizId === 'milkdrop' && md.state === 'loading' && !mdBlocked && <div className="viz-message">Loading MilkDrop presets…</div>}
      {vizId === 'milkdrop' && md.state === 'error' && <div className="viz-message">MilkDrop couldn’t load. Check the connection and pick it again.</div>}

      <div className="viz-bar">
        <div className="viz-now">
          <div className="viz-title">{track?.title}</div>
          <div className="viz-sub">{track?.artist} · {status}</div>
        </div>
        <div className="viz-controls">
          {isIOS && (
            <button className={`viz-btn viz-live${iosLive ? ' on' : ''}`} onClick={() => { if (iosNeedsTap) { const A = window.__amsAudio; A?.release?.(); A?.ensure?.(); A?.ctx?.()?.resume?.().catch(() => {}); setIosNeedsTap(false); } else toggleIosLive(); }}
              title={iosLive ? 'Turn off live mode' : 'React to the music (beta). Stops automatically when the screen locks.'}
              aria-pressed={iosLive}>Live{iosLive ? '' : ' (beta)'}</button>
          )}
          {!isCurrent && onPlay && !mdBlocked && (
            <button className="viz-btn viz-play" onClick={onPlay} title="Play"><Icon name="play" size={14} /></button>
          )}
          <label className="viz-select-wrap" title={current.note}>
            <span className="sr-only">Visualizer</span>
            <select id="viz-select" className="viz-select" value={vizId} onChange={e => setVizId(e.target.value)}>
              {VIZ_LIST.map(v => <option key={v.id} value={v.id}>{v.name}</option>)}
            </select>
          </label>
          {vizId === 'milkdrop' && md.state === 'ready' && (
            <>
              <select id="viz-md-preset" className="viz-select viz-md" value={md.name} onChange={e => pickPreset(e.target.value)} title="MilkDrop preset (community-made; names credit the authors)">
                {md.names.map(n => <option key={n} value={n}>{n}</option>)}
              </select>
              <button className="viz-btn" title="Random preset" onClick={() => pickPreset(md.names[Math.floor(Math.random() * md.names.length)])}><Icon name="shuffle" size={14} /></button>
            </>
          )}
          <button className="viz-btn" onClick={full ? exitFull : enterFull} title={full ? 'Exit full screen (Esc)' : 'Full screen'}>
            {full ? <Icon name="x" size={14} /> : (
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>
            )}
          </button>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { VisualizerStage, VIZ_LIST });
