/* global React */
const { useEffect, useState, useRef } = React;

// Logo mark — background removed via canvas flood-fill (works on any nav background)
function LogoMark({ size = 80 }) {
  const canvasRef = useRef(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const img = new Image();
    img.onload = () => {
      const w = img.naturalWidth, h = img.naturalHeight;
      canvas.width = w;
      canvas.height = h;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);
      try {
        const data = ctx.getImageData(0, 0, w, h);
        const d = data.data;
        // Sample background color from top-left corner
        const bgR = d[0], bgG = d[1], bgB = d[2];
        const threshold = 38; // tolerance per channel
        // BFS flood-fill from all 4 corners → remove background
        const visited = new Uint8Array(w * h);
        const queue = [];
        [[0, 0], [w - 1, 0], [0, h - 1], [w - 1, h - 1]].forEach(([cx, cy]) => {
          const idx = cy * w + cx;
          if (!visited[idx]) { visited[idx] = 1; queue.push(idx); }
        });
        while (queue.length > 0) {
          const i = queue.pop();
          const px = i * 4;
          if (
            Math.abs(d[px] - bgR) > threshold ||
            Math.abs(d[px + 1] - bgG) > threshold ||
            Math.abs(d[px + 2] - bgB) > threshold
          ) continue;
          d[px + 3] = 0; // transparent
          const x = i % w, y = (i / w) | 0;
          if (x > 0     && !visited[i - 1])     { visited[i - 1] = 1;     queue.push(i - 1); }
          if (x < w - 1 && !visited[i + 1])     { visited[i + 1] = 1;     queue.push(i + 1); }
          if (y > 0     && !visited[i - w])     { visited[i - w] = 1;     queue.push(i - w); }
          if (y < h - 1 && !visited[i + w])     { visited[i + w] = 1;     queue.push(i + w); }
        }
        // Passe secondaire : supprime les résidus JPEG near-white (anti-aliasing de bord)
        for (let i = 0; i < d.length; i += 4) {
          if (d[i + 3] === 0) continue;
          const mn = Math.min(d[i], d[i + 1], d[i + 2]);
          if (mn > 210) {
            // fade to transparent proportionnellement à la blancheur
            d[i + 3] = Math.round(d[i + 3] * (255 - mn) / 45);
          }
        }
        ctx.putImageData(data, 0, 0);
      } catch (_) {
        // Fallback si canvas tainté (ne devrait pas arriver en same-origin)
        canvas.style.display = "none";
        const fb = new Image();
        fb.src = "assets/summersky-logo-v2.jpeg";
        Object.assign(fb.style, { height: size + "px", width: "auto", mixBlendMode: "multiply" });
        canvas.parentNode && canvas.parentNode.insertBefore(fb, canvas);
      }
    };
    img.src = "assets/summersky-logo-v2.jpeg";
  }, [size]);

  return (
    <canvas
      ref={canvasRef}
      aria-label="Summer Sky"
      style={{ display: "block", height: size, width: "auto", maxWidth: "none" }}
    />
  );
}

// Eyebrow text with line
function Eyebrow({ children }) {
  return <span className="eyebrow">{children}</span>;
}

// Image placeholder with monospace label
function PlaceholderImg({ label, style, className = "" }) {
  return (
    <div className={`placeholder-img ${className}`} style={style}>
      {label}
    </div>
  );
}

// Countdown to event
function Countdown() {
  const target = new Date("2026-06-20T12:00:00").getTime();
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const t = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(t);
  }, []);
  const diff = Math.max(0, target - now);
  const days = Math.floor(diff / 86400000);
  const hours = Math.floor((diff / 3600000) % 24);
  const mins = Math.floor((diff / 60000) % 60);
  const secs = Math.floor((diff / 1000) % 60);
  const cells = [
    { n: days, l: "Jours" },
    { n: hours, l: "Heures" },
    { n: mins, l: "Minutes" },
    { n: secs, l: "Secondes" },
  ];
  return (
    <div className="countdown">
      {cells.map((c) => (
        <div key={c.l} className="cd-cell">
          <div className="cd-num">{String(c.n).padStart(2, "0")}</div>
          <div className="cd-label">{c.l}</div>
        </div>
      ))}
    </div>
  );
}

// Marquee
function Marquee({ items }) {
  const content = (
    <>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          <span>{it}</span>
          <span className="dot" />
        </React.Fragment>
      ))}
    </>
  );
  return (
    <div className="marquee-outer">
      <div className="marquee">
        <div className="marquee-track">
          {content}
          {content}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LogoMark, Eyebrow, PlaceholderImg, Countdown, Marquee });
