import { paletteOf } from './palettes.js';

export function startBackground(canvas, getPal) {
  let pal = paletteOf(getPal());
  let t = 0;
  const motes = Array.from({ length: 48 }, () => ({
    x: Math.random(),
    y: Math.random(),
    r: 0.6 + Math.random() * 1.8,
    s: 0.04 + Math.random() * 0.12,
    a: 0.08 + Math.random() * 0.18,
  }));

  function resize() {
    const dpr = Math.min(devicePixelRatio || 1, 2);
    canvas.width = innerWidth * dpr;
    canvas.height = innerHeight * dpr;
    canvas.style.width = innerWidth + 'px';
    canvas.style.height = innerHeight + 'px';
  }
  resize();
  addEventListener('resize', resize);

  function frame(now) {
    pal = paletteOf(getPal());
    t = now * 0.001;
    const dpr = Math.min(devicePixelRatio || 1, 2);
    const ctx = canvas.getContext('2d');
    const w = innerWidth;
    const h = innerHeight;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    ctx.fillStyle = pal.bg;
    ctx.fillRect(0, 0, w, h);

    const g = ctx.createRadialGradient(w * 0.2, h * 0.1, 10, w * 0.3, h * 0.2, w * 0.7);
    g.addColorStop(0, hexA(pal.accent, 0.12));
    g.addColorStop(1, 'transparent');
    ctx.fillStyle = g;
    ctx.fillRect(0, 0, w, h);
    const g2 = ctx.createRadialGradient(w * 0.85, h * 0.85, 10, w * 0.8, h * 0.8, w * 0.55);
    g2.addColorStop(0, hexA(pal.flooz, 0.1));
    g2.addColorStop(1, 'transparent');
    ctx.fillStyle = g2;
    ctx.fillRect(0, 0, w, h);

    ctx.save();
    ctx.globalAlpha = 0.16;
    ctx.strokeStyle = pal.accent;
    ctx.lineWidth = 8;
    ctx.lineCap = 'round';
    const drift = (t * 18) % 120;
    ctx.beginPath();
    ctx.moveTo(-20, h * 0.35 + Math.sin(t * 0.4) * 20);
    ctx.lineTo(w * 0.25, h * 0.35);
    ctx.quadraticCurveTo(w * 0.4, h * 0.35, w * 0.4, h * 0.55);
    ctx.lineTo(w * 0.4, h + 20);
    ctx.stroke();
    ctx.beginPath();
    ctx.strokeStyle = pal.flooz;
    ctx.moveTo(w + 20, h * 0.2);
    ctx.lineTo(w * 0.62, h * 0.2);
    ctx.quadraticCurveTo(w * 0.5, h * 0.2, w * 0.5, h * 0.45);
    ctx.lineTo(w * 0.5, h * 0.7);
    ctx.quadraticCurveTo(w * 0.5, h * 0.82, w * 0.7, h * 0.82);
    ctx.lineTo(w + 20, h * 0.82);
    ctx.stroke();
    ctx.restore();

    ctx.fillStyle = pal.floozCore || '#fff';
    for (const m of motes) {
      m.y -= m.s * 0.0025;
      if (m.y < -0.02) {
        m.y = 1.02;
        m.x = Math.random();
      }
      ctx.globalAlpha = m.a * (0.6 + Math.sin(t + m.x * 8) * 0.4);
      ctx.beginPath();
      ctx.arc(m.x * w, m.y * h + Math.sin(t + m.x * 12) * 6, m.r, 0, Math.PI * 2);
      ctx.fill();
    }
    ctx.globalAlpha = 1;
    void drift;
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
}

function hexA(hex, a) {
  const n = parseInt(String(hex).replace('#', ''), 16);
  const r = (n >> 16) & 255;
  const g = (n >> 8) & 255;
  const b = n & 255;
  return `rgba(${r},${g},${b},${a})`;
}
