// brushstrokes-final-2.jsx — generative brushstroke backdrops (static, resize-safe)
// HeroBrush is now drawn ONCE (no requestAnimationFrame loop) for smooth scrolling.
// All canvases redraw crisply (debounced) on resize so they stay sharp at any size.

const { useEffect, useRef } = React;

/* Utility: deterministic pseudo-random */
function mulberry32(a) {
  return function() {
    a |= 0; a = a + 0x6D2B79F5 | 0;
    let t = Math.imul(a ^ a >>> 15, 1 | a);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}

/* Draw a tapered brush stroke along a bezier path with texture */
function drawBrush(ctx, pts, { color, width = 60, alpha = 0.8, layers = 6, texture = true, rng }) {
  if (pts.length < 2) return;
  ctx.save();
  ctx.globalCompositeOperation = "multiply";

  // Bezier smooth
  const smooth = [];
  for (let i = 0; i < pts.length - 1; i++) {
    const a = pts[i], b = pts[i + 1];
    const steps = 40;
    for (let t = 0; t <= 1; t += 1 / steps) {
      const ease = t;
      smooth.push({
        x: a.x + (b.x - a.x) * ease,
        y: a.y + (b.y - a.y) * ease,
      });
    }
  }

  for (let l = 0; l < layers; l++) {
    const offset = (rng() - 0.5) * width * 0.4;
    const w = width * (0.4 + rng() * 0.7);
    const a = alpha * (0.15 + rng() * 0.5);
    ctx.strokeStyle = color;
    ctx.globalAlpha = a;
    ctx.lineWidth = w;
    ctx.lineCap = "round";
    ctx.lineJoin = "round";
    ctx.beginPath();
    smooth.forEach((p, i) => {
      const wobble = Math.sin(i * 0.05 + l) * 2;
      const x = p.x + offset + wobble;
      const y = p.y + offset * 0.3;
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    });
    ctx.stroke();

    // Bristle texture — tiny dots along path
    if (texture && l < 3) {
      ctx.globalAlpha = a * 0.6;
      for (let i = 0; i < smooth.length; i += 2) {
        const p = smooth[i];
        for (let b = 0; b < 6; b++) {
          const r = (rng() - 0.5) * w * 1.1;
          const angle = rng() * Math.PI * 2;
          ctx.beginPath();
          ctx.arc(p.x + Math.cos(angle) * Math.abs(r) + offset, p.y + Math.sin(angle) * Math.abs(r) * 0.6 + offset * 0.3, rng() * 1.6, 0, Math.PI * 2);
          ctx.fill();
        }
      }
    }
  }
  ctx.restore();
}

/* Debounce helper using rAF so we only repaint once per frame on resize */
function rafDebounce(fn) {
  let raf = 0;
  const wrapped = () => { cancelAnimationFrame(raf); raf = requestAnimationFrame(fn); };
  wrapped.cancel = () => cancelAnimationFrame(raf);
  return wrapped;
}

/* Hero — large strokes drawn ONCE (static, fully painted). No animation loop. */
function HeroBrush({ accent = "#c7452a" }) {
  const ref = useRef(null);

  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");

    const W = () => canvas.offsetWidth;
    const H = () => canvas.offsetHeight;

    function size() {
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = Math.max(1, Math.round(canvas.offsetWidth * dpr));
      canvas.height = Math.max(1, Math.round(canvas.offsetHeight * dpr));
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    }

    function buildStrokes() {
      const w = W(), h = H();
      return [
        {
          color: accent,
          width: Math.max(80, w * 0.09),
          alpha: 0.26,
          pts: [
            { x: -w * 0.08, y: h * 0.15 },
            { x: w * 0.35, y: h * 0.08 },
            { x: w * 0.72, y: h * 0.22 },
            { x: w * 1.08, y: h * 0.08 },
          ],
          rng: mulberry32(11),
        },
        {
          color: "#1a3d2e",
          width: Math.max(60, w * 0.06),
          alpha: 0.15,
          pts: [
            { x: w * 1.1, y: h * 0.78 },
            { x: w * 0.65, y: h * 0.9 },
            { x: w * 0.28, y: h * 0.72 },
            { x: -w * 0.08, y: h * 0.86 },
          ],
          rng: mulberry32(23),
        },
        {
          color: "#d4a574",
          width: Math.max(110, w * 0.14),
          alpha: 0.14,
          pts: [
            { x: w * 0.75, y: -h * 0.05 },
            { x: w * 0.85, y: h * 0.4 },
            { x: w * 0.72, y: h * 0.75 },
            { x: w * 0.92, y: h * 1.1 },
          ],
          rng: mulberry32(41),
        },
        {
          color: accent,
          width: Math.max(30, w * 0.03),
          alpha: 0.3,
          pts: [
            { x: w * 0.02, y: h * 0.62 },
            { x: w * 0.12, y: h * 0.5 },
            { x: w * 0.18, y: h * 0.6 },
          ],
          rng: mulberry32(67),
        },
      ];
    }

    function paint() {
      size();
      ctx.clearRect(0, 0, W(), H());
      const strokes = buildStrokes();
      strokes.forEach((s) => {
        drawBrush(ctx, s.pts, {
          color: s.color, width: s.width, alpha: s.alpha, layers: 4, rng: s.rng,
        });
      });
    }

    paint();

    const onResize = rafDebounce(paint);
    window.addEventListener("resize", onResize);
    window.addEventListener("orientationchange", onResize);

    return () => {
      onResize.cancel();
      window.removeEventListener("resize", onResize);
      window.removeEventListener("orientationchange", onResize);
    };
  }, [accent]);

  return <canvas ref={ref} className="hero-canvas" />;
}

/* Card visuals — each company gets a signature brushstroke composition */
function CardBrush({ variant = 0, accent = "#c7452a" }) {
  const ref = useRef(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");

    function paint() {
      if (!canvas.offsetWidth || !canvas.offsetHeight) return;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = Math.max(1, Math.round(canvas.offsetWidth * dpr));
      canvas.height = Math.max(1, Math.round(canvas.offsetHeight * dpr));
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

      const w = canvas.offsetWidth, h = canvas.offsetHeight;

      // Soft paper base
      ctx.fillStyle = "#ebe6db";
      ctx.fillRect(0, 0, w, h);

      const configs = [
        // 0: GetRIA — horizontal architectural strokes, vermillion + green
        [
          { color: accent, width: h * 0.18, alpha: 0.55, pts: [{x:-w*0.1,y:h*0.3},{x:w*0.5,y:h*0.4},{x:w*1.1,y:h*0.3}], rng: mulberry32(101) },
          { color: "#1a3d2e", width: h * 0.06, alpha: 0.45, pts: [{x:w*0.1,y:h*0.65},{x:w*0.55,y:h*0.75},{x:w*0.95,y:h*0.6}], rng: mulberry32(103) },
          { color: "#d4a574", width: h * 0.1, alpha: 0.3, pts: [{x:w*0.7,y:-h*0.1},{x:w*0.8,y:h*0.5},{x:w*0.75,y:h*1.1}], rng: mulberry32(105) },
        ],
        // 1: SymphonyFlow — curved flowing waves, teal-green dominant
        [
          { color: "#1a3d2e", width: h * 0.14, alpha: 0.5, pts: [{x:-w*0.1,y:h*0.5},{x:w*0.3,y:h*0.3},{x:w*0.6,y:h*0.7},{x:w*1.1,y:h*0.45}], rng: mulberry32(201) },
          { color: "#4a7c64", width: h * 0.08, alpha: 0.4, pts: [{x:-w*0.1,y:h*0.75},{x:w*0.35,y:h*0.55},{x:w*0.7,y:h*0.85},{x:w*1.1,y:h*0.6}], rng: mulberry32(203) },
          { color: accent, width: h * 0.05, alpha: 0.4, pts: [{x:w*0.2,y:h*0.2},{x:w*0.5,y:h*0.15},{x:w*0.8,y:h*0.25}], rng: mulberry32(205) },
        ],
        // 2: VisionSure — concentric arcs (eye-like), ochre + vermillion
        [
          { color: "#d4a574", width: h * 0.2, alpha: 0.45, pts: [{x:-w*0.1,y:h*0.5},{x:w*0.5,y:h*0.35},{x:w*1.1,y:h*0.5}], rng: mulberry32(301) },
          { color: "#1a3d2e", width: h * 0.08, alpha: 0.35, pts: [{x:w*0.1,y:h*0.85},{x:w*0.5,y:h*0.95},{x:w*0.9,y:h*0.8}], rng: mulberry32(303) },
          { color: accent, width: h * 0.18, alpha: 0.55, pts: [{x:w*0.35,y:h*0.6},{x:w*0.5,y:h*0.55},{x:w*0.65,y:h*0.6}], rng: mulberry32(305) },
        ],
      ];

      const strokes = configs[variant % configs.length];
      strokes.forEach((s) => {
        drawBrush(ctx, s.pts, { color: s.color, width: s.width, alpha: s.alpha, layers: 6, rng: s.rng });
      });
    }

    paint();
    const onResize = rafDebounce(paint);
    window.addEventListener("resize", onResize);
    window.addEventListener("orientationchange", onResize);
    return () => {
      onResize.cancel();
      window.removeEventListener("resize", onResize);
      window.removeEventListener("orientationchange", onResize);
    };
  }, [variant, accent]);

  return <canvas ref={ref} style={{ width: "100%", height: "100%", display: "block" }} />;
}

/* Leadership portraits — abstract brushstroke silhouettes (placeholders) */
function PortraitBrush({ seed = 1, accent = "#c7452a" }) {
  const ref = useRef(null);
  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");

    function paint() {
      if (!canvas.offsetWidth || !canvas.offsetHeight) return;
      const dpr = Math.min(window.devicePixelRatio || 1, 2);
      canvas.width = Math.max(1, Math.round(canvas.offsetWidth * dpr));
      canvas.height = Math.max(1, Math.round(canvas.offsetHeight * dpr));
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      const w = canvas.offsetWidth, h = canvas.offsetHeight;

      // warm background wash
      const bgHues = [
        ["#e8dfc9","#d4c19a"],
        ["#d9d3c4","#c4bca6"],
        ["#ead7c0","#d9b38a"],
      ];
      const pair = bgHues[seed % bgHues.length];
      const grad = ctx.createLinearGradient(0, 0, w, h);
      grad.addColorStop(0, pair[0]); grad.addColorStop(1, pair[1]);
      ctx.fillStyle = grad; ctx.fillRect(0, 0, w, h);

      // Painterly warm field + faint accent brushstroke; the real photo
      // (overlaid via .lcard-img) sits on top, so no dark silhouette is drawn.
      drawBrush(ctx, [
        { x: -w * 0.1, y: h * 0.28 },
        { x: w * 0.3, y: h * 0.22 },
        { x: w * 0.55, y: h * 0.3 },
      ], { color: accent, width: h * 0.05, alpha: 0.32, layers: 5, rng: mulberry32(seed * 3 + 5) });
      drawBrush(ctx, [
        { x: w * 1.1, y: h * 0.7 },
        { x: w * 0.6, y: h * 0.82 },
        { x: w * 0.1, y: h * 0.72 },
      ], { color: "#1a3d2e", width: h * 0.06, alpha: 0.16, layers: 4, rng: mulberry32(seed * 7 + 3) });
    }

    paint();
    const onResize = rafDebounce(paint);
    window.addEventListener("resize", onResize);
    window.addEventListener("orientationchange", onResize);
    return () => {
      onResize.cancel();
      window.removeEventListener("resize", onResize);
      window.removeEventListener("orientationchange", onResize);
    };
  }, [seed, accent]);

  return <canvas ref={ref} style={{ width: "100%", height: "100%", display: "block" }} />;
}

Object.assign(window, { HeroBrush, CardBrush, PortraitBrush });
