// brand-background.jsx
// Canvas-driven brand background. Re-imagines the experimental site's Three.js
// neural net as a CALM, MONOCHROME constellation per the Prometio brand book:
// faint Platinum nodes + hairline links, Violet Blue ONLY near the cursor.
// Modes: 'constellation' | 'glow' | 'isotipo' | 'flat'

function BrandBackground({ mode, intensity, theme }) {
  const canvasRef = React.useRef(null);
  const wrapRef = React.useRef(null);

  React.useEffect(() => {
    const canvas = canvasRef.current;
    const wrap = wrapRef.current;
    if (!canvas || !wrap) return;
    const ctx = canvas.getContext('2d');
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    let W = 0, H = 0, dpr = Math.min(window.devicePixelRatio || 1, 2);
    const resize = () => {
      W = wrap.offsetWidth; H = wrap.offsetHeight;
      canvas.width = W * dpr; canvas.height = H * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener('resize', resize);

    const mouse = { x: -9999, y: -9999, active: false };
    const onMove = (e) => {
      const r = wrap.getBoundingClientRect();
      mouse.x = e.clientX - r.left; mouse.y = e.clientY - r.top; mouse.active = true;
    };
    const onLeave = () => { mouse.active = false; };
    window.addEventListener('mousemove', onMove);
    wrap.addEventListener('mouseleave', onLeave);

    // ---- Node field (used by constellation + isotipo modes) ----
    const isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
    const baseCount = isTouch ? 34 : 64;
    const COUNT = Math.round(baseCount * (intensity ?? 1));
    const nodes = [];
    const seed = () => {
      nodes.length = 0;
      for (let i = 0; i < COUNT; i++) {
        nodes.push({
          x: Math.random() * W, y: Math.random() * H,
          bx: 0, by: 0,
          vx: (Math.random() - 0.5) * 0.12,
          vy: (Math.random() - 0.5) * 0.12,
          r: 0.8 + Math.random() * 1.4,
        });
      }
    };
    seed();

    // Exclusion: keep nodes thin behind the centered text block
    const inExclusion = (x, y) => {
      const cx = W / 2, cy = H / 2;
      return Math.abs(x - cx) < Math.min(W * 0.32, 520) &&
             Math.abs(y - cy) < Math.min(H * 0.30, 230);
    };

    const NODE = theme === 'dark' ? '235,233,233' : '33,32,40';
    const LINK = 132;        // link distance
    const CURSOR_R = 190;    // cursor influence radius
    let raf, t = 0, running = true;

    const drawGlow = () => {
      // Calm violet/dusk glow field - drifts slowly, very low opacity
      ctx.clearRect(0, 0, W, H);
      const blob = (x, y, r, col, a) => {
        const g = ctx.createRadialGradient(x, y, 0, x, y, r);
        g.addColorStop(0, col.replace('A', a));
        g.addColorStop(0.55, col.replace('A', a * 0.28));
        g.addColorStop(1, 'rgba(0,0,0,0)');
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(x, y, r, 0, Math.PI * 2); ctx.fill();
      };
      const off = Math.sin(t * 0.004) * 60;
      blob(W * 0.24 + off, H * 0.72, Math.max(W, H) * 0.42, 'rgba(78,79,131,A)', 0.18);
      blob(W * 0.78 - off * 0.6, H * 0.26, Math.max(W, H) * 0.36, 'rgba(66,83,175,A)', 0.14);
      blob(W * 0.5, H * 0.5, Math.max(W, H) * 0.3, 'rgba(66,83,175,A)', 0.05);
    };

    const drawNodes = (faint) => {
      ctx.clearRect(0, 0, W, H);
      // update + draw links first
      for (const n of nodes) {
        n.x += n.vx; n.y += n.vy;
        if (n.x < 0 || n.x > W) n.vx *= -1;
        if (n.y < 0 || n.y > H) n.vy *= -1;
      }
      for (let i = 0; i < nodes.length; i++) {
        const a = nodes[i];
        for (let j = i + 1; j < nodes.length; j++) {
          const b = nodes[j];
          const dx = a.x - b.x, dy = a.y - b.y;
          const d = Math.hypot(dx, dy);
          if (d < LINK) {
            const op = (1 - d / LINK) * (faint ? 0.05 : 0.11);
            ctx.strokeStyle = `rgba(${NODE},${op})`;
            ctx.lineWidth = 1;
            ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
          }
        }
      }
      // nodes
      for (const n of nodes) {
        let col = `rgba(${NODE},${faint ? 0.20 : 0.36})`;
        let rr = n.r;
        if (mouse.active) {
          const dm = Math.hypot(n.x - mouse.x, n.y - mouse.y);
          if (dm < CURSOR_R) {
            const k = 1 - dm / CURSOR_R;
            const base = theme === 'dark' ? [235, 233, 233] : [33, 32, 40];
            // shift toward Violet Blue near the cursor
            col = `rgba(${Math.round(base[0] + (66 - base[0]) * k)},${Math.round(base[1] + (83 - base[1]) * k)},${Math.round(base[2] + (175 - base[2]) * k)},${0.4 + k * 0.5})`;
            rr = n.r + k * 1.6;
          }
        }
        ctx.fillStyle = col;
        ctx.beginPath(); ctx.arc(n.x, n.y, rr, 0, Math.PI * 2); ctx.fill();
      }
    };

    const frame = () => {
      if (!running) return;
      t += 1;
      if (mode === 'glow') drawGlow();
      else if (mode === 'flat') { ctx.clearRect(0, 0, W, H); running = false; return; }
      else drawNodes(mode === 'isotipo');
      raf = requestAnimationFrame(frame);
    };

    if (reduce) {
      // single static frame
      if (mode === 'glow') drawGlow();
      else if (mode !== 'flat') drawNodes(mode === 'isotipo');
      else ctx.clearRect(0, 0, W, H);
    } else {
      running = true;
      frame();
    }

    return () => {
      running = false;
      cancelAnimationFrame(raf);
      window.removeEventListener('resize', resize);
      window.removeEventListener('mousemove', onMove);
      wrap.removeEventListener('mouseleave', onLeave);
    };
  }, [mode, intensity, theme]);

  const ISO_PATH = "m130.53,221.5v-63.31s44.79,44.79,44.79,44.79l27.78-27.78-44.79-44.79h63.34s0-39.29,0-39.29h-63.34s44.79-44.79,44.79-44.79l-27.78-27.78-44.79,44.79V0h-.12s-39.17,0-39.17,0h-.12v63.34S46.33,18.55,46.33,18.55l-27.78,27.78,44.79,44.79H0s0,39.29,0,39.29h63.34s-44.79,44.79-44.79,44.79l27.78,27.78,44.79-44.79v63.31s39.41,0,39.41,0Zm-.03-110.73c0,5.2-2.07,10.19-5.75,13.87h0c-3.68,3.68-8.67,5.75-13.87,5.75h-.1c-5.2,0-10.19-2.07-13.87-5.75h0c-3.68-3.68-5.75-8.67-5.75-13.87h0c0-5.2,2.07-10.19,5.75-13.87,3.68-3.68,8.67-5.75,13.87-5.75h.11c5.2,0,10.19,2.07,13.87,5.75,3.68,3.68,5.75,8.67,5.75,13.87h0Z";

  return (
    <div ref={wrapRef} style={{
      position: 'absolute', inset: 0, overflow: 'hidden', background: 'transparent',
      WebkitMaskImage: 'linear-gradient(to bottom, #000 76%, transparent 99%)',
      maskImage: 'linear-gradient(to bottom, #000 76%, transparent 99%)',
    }}>
      {/* Large, subtle isotipo watermark - brand-approved decorative corner anchor */}
      {mode === 'isotipo' && (
        <svg viewBox="0 0 221.65 221.5" aria-hidden="true"
          style={{
            position: 'absolute', right: '-7%', bottom: '-14%',
            width: 'min(62vw, 760px)', height: 'auto', opacity: 0.05,
            pointerEvents: 'none',
          }}>
          <path d={ISO_PATH} fill={theme === 'dark' ? 'var(--platinum)' : 'var(--raisin)'} fillRule="evenodd" />
        </svg>
      )}
      <canvas ref={canvasRef} style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} />
      {/* Vignette + bottom fade keep the composition calm and centered */}
      <div aria-hidden="true" style={{
        position: 'absolute', inset: 0, pointerEvents: 'none',
        background: 'radial-gradient(125% 95% at 50% 42%, transparent 62%, var(--vignette) 100%)',
      }} />
    </div>
  );
}

window.BrandBackground = BrandBackground;
