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

// ============================================================
//  SVG primitives — 4-point burst star, squiggle line, blob
// ============================================================

// Classic 4-point sparkle star (with optional outline)
function Star4({ color = "currentColor", outline = "currentColor", outlined = false, className = "", style }) {
  const path = "M50 0 Q56 44 100 50 Q56 56 50 100 Q44 56 0 50 Q44 44 50 0 Z";
  return (
    <svg viewBox="0 0 100 100" className={className} style={style}>
      {outlined ? (
        <>
          <path d={path} fill={color} stroke={outline} strokeWidth="3" strokeLinejoin="round" />
        </>
      ) : (
        <path d={path} fill={color} />
      )}
    </svg>
  );
}

// Bigger pointier star used as the photo burst (8 spikes radial)
function StarBurst({ color = "currentColor", outline = "currentColor", className = "", style }) {
  // 8 elongated spikes radiating from center, like the cream stars in the reference
  const spikes = [];
  for (let i = 0; i < 8; i++) {
    const a = (i / 8) * Math.PI * 2;
    const lx = Math.cos(a) * 50;
    const ly = Math.sin(a) * 50;
    const wx = -Math.sin(a) * 9;
    const wy = Math.cos(a) * 9;
    spikes.push(`M${lx} ${ly} L${wx} ${wy} L${-lx * 0.0} ${-ly * 0.0} L${-wx} ${-wy} Z`);
  }
  return (
    <svg viewBox="-60 -60 120 120" className={className} style={style}>
      {Array.from({ length: 8 }).map((_, i) => {
        const a = (i / 8) * Math.PI * 2;
        const tx = Math.cos(a) * 56;
        const ty = Math.sin(a) * 56;
        const cx = Math.cos(a + Math.PI / 8) * 14;
        const cy = Math.sin(a + Math.PI / 8) * 14;
        const dx = Math.cos(a - Math.PI / 8) * 14;
        const dy = Math.sin(a - Math.PI / 8) * 14;
        return (
          <path
            key={i}
            d={`M${tx} ${ty} L${cx} ${cy} L${dx} ${dy} Z`}
            fill={color}
            stroke={outline}
            strokeWidth="3"
            strokeLinejoin="round"
          />
        );
      })}
      <circle cx="0" cy="0" r="14" fill={color} stroke={outline} strokeWidth="3" />
    </svg>
  );
}

// Wavy red squiggle (sinuous line)
function Squiggle({ color = "currentColor", className = "", style, thick = 6 }) {
  return (
    <svg viewBox="0 0 200 40" fill="none" className={className} style={style}>
      <path
        d="M5 20 C 25 0, 45 40, 65 20 S 105 0, 125 20 S 165 40, 195 20"
        stroke={color}
        strokeWidth={thick}
        strokeLinecap="round"
      />
    </svg>
  );
}

// Big organic cyan tongue/blob — tongue dripping from top
function BlobTop({ color = "currentColor", className = "", style }) {
  return (
    <svg viewBox="0 0 600 400" preserveAspectRatio="none" fill={color} className={className} style={style}>
      <path d="M-20 0
               L 620 0
               L 620 80
               Q 540 130 480 90
               Q 420 50 350 130
               Q 320 170 280 140
               Q 230 110 210 180
               Q 200 230 180 260
               Q 165 290 140 290
               Q 110 290 100 250
               Q 86 200 60 200
               Q 0 200 -20 240
               Z" />
    </svg>
  );
}

// Big organic cyan blob (bottom-right of hero, foot of frame)
function BlobCorner({ color = "currentColor", className = "", style }) {
  return (
    <svg viewBox="0 0 400 400" preserveAspectRatio="none" fill={color} className={className} style={style}>
      <path d="M400 60
               Q 360 30 320 60
               Q 280 90 240 70
               Q 200 50 200 110
               Q 200 170 240 200
               Q 290 230 260 280
               Q 230 330 280 360
               Q 340 390 400 400
               L 400 60 Z" />
    </svg>
  );
}

// Wavy squiggle pointing as a 'tilde' shape (~) — used in deco bottom
function TildeRow({ color = "currentColor", className = "", style }) {
  return (
    <svg viewBox="0 0 240 30" fill="none" className={className} style={style}>
      <path
        d="M10 18 Q40 -2 80 18 T 230 18"
        stroke={color}
        strokeWidth="6"
        strokeLinecap="round"
      />
    </svg>
  );
}

// Chunky 5-point star with thick ink outline + red motion rays (the
// left-edge "burst" star from the reference). Designed to bleed off
// the left edge of the page — rays radiate to the left.
function StarRays({ starColor = "var(--cream)", outline = "var(--ink)", rayColor = "var(--red)", className = "", style }) {
  return (
    <svg viewBox="-120 -120 240 240" fill="none" className={className} style={style}>
      {/* radiating rays — fan out to the LEFT side of the star */}
      <g stroke={rayColor} strokeWidth="14" strokeLinecap="round">
        <line x1="-30" y1="0" x2="-150" y2="0" />
        <line x1="-26" y1="-20" x2="-130" y2="-66" />
        <line x1="-26" y1="20" x2="-130" y2="66" />
        <line x1="-14" y1="-32" x2="-70" y2="-110" />
        <line x1="-14" y1="32" x2="-70" y2="110" />
      </g>
      {/* the star itself */}
      <path
        d="M0 -80
           L 22 -28
           L 78 -22
           L 36 14
           L 50 70
           L 0 38
           L -50 70
           L -36 14
           L -78 -22
           L -22 -28 Z"
        fill={starColor}
        stroke={outline}
        strokeWidth="9"
        strokeLinejoin="round"
      />
    </svg>
  );
}

// ============================================================
//  Diner signage — marquee bulb signs, route shields, ribbons
// ============================================================

// A sign panel ringed with marquee light-bulbs. tone: cream | teal | red.
function MarqueeSign({ label, tone = "cream", pill = false, vertical = false, className = "", style, children }) {
  const cls = `dsign tone-${tone}${pill ? " is-pill" : ""}${vertical ? " is-vert" : ""} ${className}`;
  return (
    <div className={cls} style={style}>
      <span className="dsign-bulbs" aria-hidden="true" />
      <span className="dsign-face">{children != null ? children : label}</span>
    </div>
  );
}

// US-route style shield badge. tone: cream | red | teal.
function RoadShield({ top = "ROUTE", big = "66", tone = "cream", className = "", style }) {
  return (
    <div className={`rshield tone-${tone} ${className}`} style={style}>
      <span className="rshield-top">{top}</span>
      <span className="rshield-big">{big}</span>
    </div>
  );
}

// Notched ribbon banner (NEXT EXIT style). tone: red | teal | amber.
function RibbonBanner({ label, tone = "red", className = "", style }) {
  return (
    <span className={`rbanner tone-${tone} ${className}`} style={style}>
      <span className="rbanner-face">{label}</span>
    </span>
  );
}

function useMagnetic(strength = 0.15, radius = 70) {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    if (window.matchMedia("(hover: none)").matches) return;
    let raf = 0, tx = 0, ty = 0, x = 0, y = 0;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      const dx = e.clientX - cx;
      const dy = e.clientY - cy;
      const d = Math.hypot(dx, dy);
      if (d < radius + Math.max(r.width, r.height) / 2) { tx = dx * strength; ty = dy * strength; }
      else { tx = 0; ty = 0; }
    };
    const onLeave = () => { tx = 0; ty = 0; };
    const tick = () => {
      x += (tx - x) * 0.18; y += (ty - y) * 0.18;
      el.style.transform = `translate(${x}px, ${y}px)`;
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    window.addEventListener("mousemove", onMove);
    el.addEventListener("mouseleave", onLeave);
    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("mousemove", onMove);
      el?.removeEventListener("mouseleave", onLeave);
    };
  }, [strength, radius]);
  return ref;
}

// ============================================================
//  Loader — logo zooms from giant down to brand size
// ============================================================
function Loader({ onDone }) {
  const wipeRef = useRef(null);
  const rootRef = useRef(null);
  const logoRef = useRef(null);
  const r1Ref = useRef(null);
  const r2Ref = useRef(null);
  const r3Ref = useRef(null);

  useEffect(() => {
    const gsap = window.gsap;
    gsap.set(logoRef.current, { scale: 9, opacity: 0 });
    gsap.set([r1Ref.current, r2Ref.current, r3Ref.current], { autoAlpha: 0, scale: 0.4 });

    gsap.to(logoRef.current, { opacity: 1, duration: 0.25, ease: "power2.out" });
    gsap.to(logoRef.current, { scale: 1, duration: 2.0, ease: "power3.inOut", onComplete: doExit });
    gsap.to([r3Ref.current, r2Ref.current, r1Ref.current], {
      autoAlpha: 1, scale: 1,
      duration: 0.55, stagger: 0.08, ease: "back.out(1.6)",
      delay: 1.6,
    });
  }, []);

  const doExit = () => {
    const gsap = window.gsap;
    const tl = gsap.timeline({ onComplete: () => onDone && onDone() });
    tl.to(rootRef.current.querySelector(".loader-mark"), { scale: 0.96, duration: 0.2, ease: "power2.in" })
      .to([r1Ref.current, r2Ref.current, r3Ref.current], { autoAlpha: 0, scale: 1.15, duration: 0.3, stagger: 0.04 }, "<")
      .to(wipeRef.current, { y: "0%", duration: 0.55, ease: "power3.inOut" }, "<0.05")
      .to(rootRef.current, { autoAlpha: 0, duration: 0.3, ease: "power2.out" }, ">-0.1");
  };

  return (
    <div ref={rootRef} className="loader">
      <div className="loader-mark">
        <div ref={r3Ref} className="ring r3" />
        <div ref={r2Ref} className="ring r2" />
        <div ref={r1Ref} className="ring" />
        <img ref={logoRef} className="logo" src="assets/wonderful-choice-logo.png" alt="Wonderful Choice" />
      </div>
      <div ref={wipeRef} className="loader-wipe" />
    </div>
  );
}

// ============================================================
//  Nav
// ============================================================
function Nav() {
  // Current page comes from <body data-page="…">. Home keeps Hero + Lineup + footer;
  // About / Process / Contact are their own pages. Lineup is an anchor on the home page.
  const page = (document.body && document.body.dataset.page) || "home";
  const onHome = page === "home";
  const homeHref = onHome ? "#top" : "index.html";
  const lineupHref = onHome ? "#lineup" : "index.html#lineup";
  const [open, setOpen] = useState(false);

  const links = [
    { key: "home",    label: "Home",    href: homeHref },
    { key: "about",   label: "About",   href: "about.html" },
    { key: "lineup",  label: "Lineup",  href: lineupHref },
    { key: "blog",    label: "Blog",    href: "blog.html" },
    { key: "contact", label: "Contact", href: "contact.html" },
  ];

  // Close on Esc, when resizing up to desktop, and lock body scroll while open.
  useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    const onResize = () => { if (window.innerWidth > 820) setOpen(false); };
    document.addEventListener("keydown", onKey);
    window.addEventListener("resize", onResize);
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      window.removeEventListener("resize", onResize);
      document.body.style.overflow = prev;
    };
  }, [open]);

  return (
    <>
    <header className="nav-wrap">
      <a href={homeHref} className="nav-logo" aria-label="Wonderful Choice — home">
        <img src="assets/wonderful-choice-logo.png" alt="Wonderful Choice" />
      </a>
      <nav className="nav-list" aria-label="Primary">
        {links.map((l) => (
          <a
            key={l.key}
            href={l.href}
            className={page === l.key ? "is-active" : ""}
            aria-current={page === l.key ? "page" : undefined}
          >
            {l.label}
          </a>
        ))}
      </nav>
      <button
        className="nav-menu-btn"
        aria-label={open ? "Close menu" : "Open menu"}
        aria-expanded={open}
        aria-controls="nav-mobile"
        onClick={() => setOpen((o) => !o)}
      >
        <svg viewBox="0 0 24 24" fill="none">
          {open
            ? <path d="M6 6l12 12M18 6L6 18" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />
            : <path d="M4 7h16M4 12h16M4 17h16" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" />}
        </svg>
      </button>
    </header>

    {/* Mobile menu sheet — a SIBLING of the header, never a child: the header
        carries a GSAP transform, and a transformed ancestor would turn this
        overlay's position:fixed into "fixed inside the nav bar" */}
    <div
        id="nav-mobile"
        className={`nav-mobile ${open ? "is-open" : ""}`}
        aria-hidden={!open}
        onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
      >
        <nav className="nav-mobile-list" aria-label="Mobile">
          {links.map((l) => (
            <a
              key={l.key}
              href={l.href}
              className={page === l.key ? "is-active" : ""}
              aria-current={page === l.key ? "page" : undefined}
              tabIndex={open ? 0 : -1}
              onClick={() => setOpen(false)}
            >
              {l.label}
            </a>
          ))}
        </nav>
        <div className="nav-mobile-foot t-label">Wonderful Choice</div>
      </div>
    </>
  );
}

// The Special Craft — decorative finishing techniques for paper cups.
// Shared by the home-menu showcase board and the cup product pages.
const WC_CRAFTS = [
  { name: "Gold Foil", note: "hot-stamped shine", photo: "assets/products/gold-foil-cups-1.jpg", alt: "Matte black cup with a gold hot-foil starburst", applies: "Paper hot cups, double-wall & kraft — pops on dark or matte stock" },
  { name: "Cold Foil", note: "mirror metallics", photo: "assets/products/metallic-foil-cups-1.jpg", alt: "Silver and champagne metallic foil cups", applies: "Any paper cup — full-wrap metallic, or metallic plus color" },
  { name: "Embossed Texture", note: "pressed patterns", photo: "assets/products/embossed-texture-cups-1.jpg", alt: "Green cup with crocodile-skin embossed texture", applies: "Single- and double-wall paper cups" },
  { name: "Blind Emboss", note: "ink-free relief", photo: "assets/products/relief-emboss-cups-1.jpg", alt: "Cream cup with a raised no-ink relief motif", applies: "Paper cups — best on uncoated cream or white board" },
  { name: "Spot UV", note: "gloss on matte", photo: "assets/products/spot-uv-cups-1.jpg", alt: "Matte charcoal cup with a glossy clear pattern", applies: "Paper cups with a matte laminate base" },
  { name: "Foam Ink", note: "puffed-up print", photo: "assets/products/foam-print-cups-1.jpg", alt: "Pastel blue cup with raised foam-ink dots", applies: "Paper hot & cold cups" },
  { name: "Flocking", note: "velvet touch", photo: "assets/products/flocked-cups-1.jpg", alt: "Red velvet-flocked cup with a cream scallop band", applies: "Paper cups" },
  { name: "Die-Cut Hollow", note: "window wall", photo: "assets/products/die-cut-cups-1.jpg", alt: "Cup with a scalloped cutout window revealing a patterned inner wall", applies: "Double-wall cups only — needs the inner wall to reveal" },
  { name: "Silk Screen", note: "thick-ink pop", photo: "assets/products/silk-screen-cups-1.jpg", alt: "Pink cup with a bold silk-screened starburst", applies: "Paper cups and clear plastic (PET / PP) cups" },
  { name: "Matte & Gloss", note: "lamination twins", photo: "assets/products/lamination-cups-1.jpg", alt: "Two blue cups, one matte-laminated and one gloss-laminated", applies: "Any paper cup" },
];

Object.assign(window, {
  Star4, StarBurst, StarRays, Squiggle, BlobTop, BlobCorner, TildeRow,
  MarqueeSign, RoadShield, RibbonBanner,
  useMagnetic, Loader, Nav,
  WC_CRAFTS,
});
