/* Maison Lior — Hero
 * Full-bleed cinematic hero with word-stagger headline, nav state, mute toggle,
 * scroll-parallax handoff and prefers-reduced-motion fallback.
 */

const { useEffect, useState, useRef, useMemo } = React;

/* ─────────────────────────  cinematic video backdrop  ─────────────────────────
 * Production: real <video> element with mobile/desktop sources + poster.
 * Falls back to a layered CSS/SVG twilight-kitchen scene if the video file is
 * missing, errors out, or the user prefers reduced motion. The same CSS scene
 * also covers the gap before the video can play. */

/* JS-controlled video. Two delivery modes — drop your real .mp4/.webm into
 * assets/video/ for the best result (autoplays, muted, loops, no chrome), OR
 * set DRIVE_FILE_ID to a Google Drive file id for a click-to-play modal embed.
 * Native mode is ON (empty id) — it autoplays the file at assets/video/hero.mp4. */
const DRIVE_FILE_ID = "";

/* ─────────────────────────  video lightbox modal  ─────────────────────────
 * Opens when the user clicks the ▶ play button. Renders the Drive video
 * inside a full-screen overlay so the iframe plays correctly. */
function VideoModal({ open, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    if (open) {
      document.addEventListener("keydown", onKey);
      document.body.style.overflow = "hidden";
    }
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      style={{
        position: "fixed", inset: 0, zIndex: 99999,
        background: "rgba(6,17,28,0.92)",
        display: "flex", alignItems: "center", justifyContent: "center",
        animation: "mlModalIn 0.3s ease",
      }}
      onClick={onClose}
    >
      <style>{`@keyframes mlModalIn{from{opacity:0;transform:scale(0.97)}to{opacity:1;transform:scale(1)}}`}</style>
      <div
        style={{
          position: "relative", width: "min(90vw, 1200px)",
          aspectRatio: "16/9", borderRadius: "4px", overflow: "hidden",
          boxShadow: "0 40px 120px rgba(0,0,0,0.7)",
        }}
        onClick={e => e.stopPropagation()}
      >
        <iframe
          src={`https://drive.google.com/file/d/${DRIVE_FILE_ID}/preview`}
          style={{ width: "100%", height: "100%", border: "none", display: "block" }}
          allow="autoplay; encrypted-media; picture-in-picture"
          allowFullScreen
          title="Martin Haidar — Reel 01"
        />
        <button
          onClick={onClose}
          aria-label="Close video"
          style={{
            position: "absolute", top: "12px", right: "12px",
            width: "36px", height: "36px", borderRadius: "50%",
            background: "rgba(13,27,42,0.8)", border: "1px solid rgba(224,225,221,0.2)",
            color: "#E0E1DD", cursor: "pointer", display: "flex",
            alignItems: "center", justifyContent: "center", fontSize: "18px",
            fontFamily: "sans-serif", lineHeight: 1,
          }}
        >×</button>
      </div>
      <p style={{
        position: "absolute", bottom: "24px", left: "50%", transform: "translateX(-50%)",
        color: "rgba(224,225,221,0.45)", fontSize: "11px", letterSpacing: "0.12em",
        fontFamily: "var(--mono, monospace)", whiteSpace: "nowrap",
      }}>ESC OR CLICK OUTSIDE TO CLOSE</p>
    </div>
  );
}

function VideoPlayer({ paused, muted, reduced, onReady, onError }){
  const ref = React.useRef(null);
  const [isMobile, setIsMobile] = React.useState(
    typeof window !== "undefined" && window.matchMedia("(max-width: 768px)").matches
  );

  React.useEffect(()=>{
    const mq = window.matchMedia("(max-width: 768px)");
    const set = ()=> setIsMobile(mq.matches);
    set();
    mq.addEventListener?.("change", set);
    return ()=> mq.removeEventListener?.("change", set);
  },[]);

  React.useEffect(()=>{
    const v = ref.current;
    if(!v || v.tagName !== "VIDEO") return;
    v.muted = muted;
  },[muted]);

  React.useEffect(()=>{
    const v = ref.current;
    if(!v || v.tagName !== "VIDEO") return;
    if(paused || reduced){ v.pause(); }
    else { v.play().catch(()=>{}); }
  },[paused, reduced]);

  /* Robust mobile autoplay. React's `muted` attribute does NOT reliably set the
   * DOM muted property, so iOS/Android refuse to autoplay. Force the properties
   * directly and kick off playback once there's data — and retry on the first
   * user interaction as a last resort if the browser still blocks it. */
  React.useEffect(()=>{
    const v = ref.current;
    if(!v || v.tagName !== "VIDEO") return;
    v.muted = true;
    v.defaultMuted = true;
    v.setAttribute("muted", "");
    v.playsInline = true;

    const tryPlay = ()=>{
      if(paused || reduced) return;
      const p = v.play();
      if(p && p.catch) p.catch(()=>{});
    };

    try{ v.load(); }catch(_){}
    tryPlay();
    v.addEventListener("loadeddata", tryPlay);
    v.addEventListener("canplay", tryPlay);

    // Fallback: if autoplay was blocked, start on the first interaction.
    const onInteract = ()=>{ tryPlay(); cleanupInteract(); };
    const cleanupInteract = ()=>{
      ["touchstart","pointerdown","click","scroll"].forEach(ev=>
        window.removeEventListener(ev, onInteract));
    };
    ["touchstart","pointerdown","click","scroll"].forEach(ev=>
      window.addEventListener(ev, onInteract, { once:true, passive:true }));

    return ()=>{
      v.removeEventListener("loadeddata", tryPlay);
      v.removeEventListener("canplay", tryPlay);
      cleanupInteract();
    };
  },[isMobile]);

  if (reduced) return null;

  /* Mode 1 — Drive iframe embed. Used when DRIVE_FILE_ID is set. */
  if (DRIVE_FILE_ID){
    return (
      <iframe
        ref={ref}
        className="ml-bd-iframe"
        src={`https://drive.google.com/file/d/${DRIVE_FILE_ID}/preview`}
        allow="autoplay; encrypted-media; picture-in-picture"
        loading="eager"
        tabIndex={-1}
        title="Hero background"
        aria-hidden="true"
        onLoad={onReady}
        onError={onError}
      />
    );
  }

  /* Mode 2 — local .mp4 with mobile/desktop sources. */
  const base = isMobile ? "assets/video/hero-mobile" : "assets/video/hero";
  const R = (typeof window !== "undefined" && window.__resources) || {};
  const posterSrc = R.heroPoster || "assets/video/hero-poster.jpg";
  const mp4Src = (isMobile ? R.heroVideoMobile : R.heroVideo) || `${base}.mp4`;
  return (
    <video
      ref={ref}
      className="ml-bd-video"
      autoPlay
      muted
      loop
      playsInline
      preload="auto"
      poster={posterSrc}
      aria-hidden="true"
      onCanPlay={onReady}
      onError={onError}
    >
      <source src={mp4Src}  type="video/mp4" />
    </video>
  );
}

function VideoBackdrop({ paused, muted, reduced }){
  const [videoOk, setVideoOk] = React.useState(true);
  return (
    <div className="ml-backdrop" data-paused={paused ? "true" : "false"} data-video={videoOk ? "ok":"fallback"} aria-hidden="true">
      {/* Fallback CSS scene — always rendered behind the video; visible whenever
          the video isn't (loading, errored, reduced motion). */}
      <div className="ml-bd-fallback">
        <div className="ml-bd-base"></div>
        <div className="ml-bd-spill"></div>
        <div className="ml-bd-stove"></div>
        <svg className="ml-bd-bokeh" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMid slice">
          <defs>
            <radialGradient id="b1"><stop offset="0%" stopColor="#C7D6EC" stopOpacity=".45"/><stop offset="60%" stopColor="#8AA4C7" stopOpacity=".05"/><stop offset="100%" stopColor="#8AA4C7" stopOpacity="0"/></radialGradient>
            <radialGradient id="b2"><stop offset="0%" stopColor="#E0E7F2" stopOpacity=".35"/><stop offset="100%" stopColor="#E0E7F2" stopOpacity="0"/></radialGradient>
            <radialGradient id="b3"><stop offset="0%" stopColor="#778DA9" stopOpacity=".40"/><stop offset="100%" stopColor="#778DA9" stopOpacity="0"/></radialGradient>
          </defs>
          <circle cx="220"  cy="180"  r="140" fill="url(#b1)"/>
          <circle cx="1620" cy="120"  r="180" fill="url(#b2)"/>
          <circle cx="1380" cy="260"  r="80"  fill="url(#b1)"/>
          <circle cx="430"  cy="780"  r="120" fill="url(#b3)"/>
          <circle cx="1750" cy="820"  r="220" fill="url(#b3)"/>
          <circle cx="940"  cy="160"  r="60"  fill="url(#b2)"/>
          <circle cx="80"   cy="540"  r="90"  fill="url(#b2)"/>
        </svg>
        <svg className="ml-bd-figure" viewBox="0 0 1920 1080" preserveAspectRatio="xMidYMax slice">
          <defs>
            <linearGradient id="figg" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#06111C" stopOpacity="0"/>
              <stop offset="55%" stopColor="#06111C" stopOpacity=".55"/>
              <stop offset="100%" stopColor="#06111C" stopOpacity=".88"/>
            </linearGradient>
          </defs>
          <rect x="0" y="780" width="1920" height="300" fill="url(#figg)"/>
          <path d="M 1120 780 C 1130 700 1175 660 1210 640 C 1240 620 1255 600 1265 575 C 1275 550 1295 540 1315 545 C 1340 552 1352 575 1352 600 C 1352 625 1365 645 1390 660 C 1430 685 1465 720 1480 780 Z" fill="#040A14" opacity=".82"/>
          <path d="M 1265 700 C 1230 715 1200 740 1180 770 L 1155 780 L 1300 780 Z" fill="#03070F" opacity=".86"/>
          <ellipse cx="1170" cy="775" rx="60" ry="6" fill="#D7DDE6" opacity=".32"/>
        </svg>
        <div className="ml-bd-drift"></div>
      </div>

      {/* Real video. Hides itself if 404 / decode error → CSS scene shows through. */}
      <VideoPlayer
        paused={paused}
        muted={muted}
        reduced={reduced}
        onReady={()=>setVideoOk(true)}
        onError={()=>setVideoOk(false)}
      />

      {/* Vignette + readability overlays sit ABOVE the video, not the fallback. */}
      <div className="ml-bd-vignette"></div>
      <div className="ml-bd-readability"></div>
    </div>
  );
}

/* ───────────────────────────────  nav  ─────────────────────────────── */
function Nav({ scrolled }){
  const links = [
    {label:"Services",  href:"#services"},
    {label:"Portfolio", href:"#portfolio"},
    {label:"Partners",  href:"#work"},
    {label:"Contact",   href:"#contact"},
  ];
  const [menuOpen, setMenuOpen] = React.useState(false);
  return (
    <nav className="ml-nav" data-scrolled={scrolled ? "true" : "false"} data-menu={menuOpen ? "open":"closed"}>
      <div className="ml-nav-inner">
        <a href="#" className="ml-brand" aria-label="The Baker Atelier — home">
          <span className="ml-brand-mark">BA</span>
          <span className="ml-brand-word">The&nbsp;Baker&nbsp;Atelier</span>
        </a>
        <div className="ml-nav-divider"></div>
        <ul className="ml-nav-links">
          {links.map((l,i)=>(
            <li key={l.label} style={{"--i": i}}>
              <a href={l.href} onClick={()=>setMenuOpen(false)} aria-label={l.label}>
                <span className="ml-nav-num">0{i+1}</span>
                <span className="ml-nav-label">{l.label}</span>
              </a>
            </li>
          ))}
          <li className="ml-nav-cta-li">
            <a href="#contact" className="ml-nav-cta" onClick={()=>setMenuOpen(false)} aria-label="Request a free consultation">Free Consultation</a>
          </li>
        </ul>
        <button
          className="ml-nav-burger"
          aria-label={menuOpen ? "Close menu" : "Open menu"}
          aria-expanded={menuOpen}
          onClick={()=>setMenuOpen(o=>!o)}
        >
          <span></span><span></span><span></span>
        </button>
      </div>
    </nav>
  );
}

/* ───────────────────────────  headline w/ word stagger  ─────────────────────────── */
function Headline({ words, italicIndex, reduced }){
  return (
    <h1 className="ml-headline" aria-label={words.map(w=>w.text).join(" ")}>
      {words.map((w,i)=>(
        <React.Fragment key={i}>
          <span className="ml-word-wrap">
            <span
              className={"ml-word" + (i===italicIndex ? " is-italic":"")}
              style={{ "--d": reduced ? "0ms" : `${300 + i*80}ms` }}
            >
              {w.text}{w.punct||""}
            </span>
          </span>
          {i < words.length-1 ? " " : null}
        </React.Fragment>
      ))}
    </h1>
  );
}

/* ───────────────────────────────  CTAs  ─────────────────────────────── */
function CTA({ variant="primary", children, delay=0, reduced, href="#" }){
  const external = /^https?:/.test(href);
  return (
    <a
      href={href}
      className={`ml-cta ml-cta--${variant}`}
      style={{"--d": reduced ? "0ms" : `${delay}ms`}}
      aria-label={typeof children === "string" ? children : undefined}
      {...(external ? { target:"_blank", rel:"noopener noreferrer" } : {})}
    >
      <span className="ml-cta-label">{children}</span>
      <span className="ml-cta-arrow" aria-hidden="true">
        <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.3" strokeLinecap="square"/></svg>
      </span>
      <span className="ml-cta-underline"></span>
    </a>
  );
}

/* ───────────────────────────────  scroll cue  ─────────────────────────────── */
function ScrollCue(){
  return (
    <div className="ml-scroll-cue" aria-hidden="true">
      <span className="ml-scroll-label">Scroll</span>
      <span className="ml-scroll-line"><span className="ml-scroll-line-fill"></span></span>
    </div>
  );
}

/* ───────────────────────────────  mute toggle  ─────────────────────────────── */
function MuteToggle({ muted, onClick, paused, onPause }){
  return (
    <div className="ml-mute-cluster">
      <button className="ml-mute" onClick={onPause} aria-label={paused?"Play background video":"Pause background video"}>
        {paused
          ? <svg width="10" height="12" viewBox="0 0 10 12"><path d="M1 1 L9 6 L1 11 Z" fill="currentColor"/></svg>
          : <svg width="10" height="12" viewBox="0 0 10 12"><rect x="1" y="1" width="2.5" height="10" fill="currentColor"/><rect x="6.5" y="1" width="2.5" height="10" fill="currentColor"/></svg>}
      </button>
      <button className="ml-mute" onClick={onClick} aria-label={muted?"Unmute background video":"Mute background video"}>
        {muted
          ? <svg width="18" height="14" viewBox="0 0 18 14" fill="none"><path d="M1 5 H4 L8 1 V13 L4 9 H1 Z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/><path d="M12 5l4 4M16 5l-4 4" stroke="currentColor" strokeWidth="1.2" strokeLinecap="square"/></svg>
          : <svg width="18" height="14" viewBox="0 0 18 14" fill="none"><path d="M1 5 H4 L8 1 V13 L4 9 H1 Z" stroke="currentColor" strokeWidth="1.2" strokeLinejoin="round"/><path d="M11 4c1.5 1 1.5 5 0 6" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/><path d="M14 2c3 2 3 8 0 10" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round"/></svg>}
      </button>
      <span className="ml-mute-rule" aria-hidden="true"></span>
      <span className="ml-mute-meta">REEL&nbsp;01 · MUTED</span>
    </div>
  );
}

/* ───────────────────────────────  HERO  ─────────────────────────────── */
function Hero({ tweaks }){
  const [scrolled, setScrolled] = useState(false);
  const [muted, setMuted] = useState(true);
  const [paused, setPaused] = useState(false);
  const [reduced, setReduced] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const heroRef = useRef(null);
  const [parallax, setParallax] = useState({s:1, o:1});

  useEffect(()=>{
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const set = ()=> setReduced(mq.matches);
    set(); mq.addEventListener?.("change", set);
    return ()=> mq.removeEventListener?.("change", set);
  },[]);

  useEffect(()=>{
    const onScroll = ()=>{
      const y = window.scrollY || 0;
      setScrolled(y > 80);
      // Parallax handoff: 0..600px -> scale 1..0.96, opacity 1..0.6
      const t = Math.min(1, Math.max(0, y / 600));
      setParallax({ s: 1 - 0.04*t, o: 1 - 0.4*t });
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return ()=> window.removeEventListener("scroll", onScroll);
  },[]);

  /* Build headline words from tweak copy. Format: "Craft, served with *intention*." */
  const headlineWords = useMemo(()=>{
    const raw = tweaks.headline;
    // tokens split on whitespace; italic word marked with *word*
    const tokens = raw.split(/\s+/);
    return tokens.map((tk,i)=>{
      const italic = /^\*.+\*[.,!?]?$/.test(tk);
      const clean = tk.replace(/\*/g,"");
      const m = clean.match(/^(.+?)([.,!?]?)$/);
      return { text: m[1], punct: m[2]||"", italic };
    });
  }, [tweaks.headline]);
  const italicIdx = headlineWords.findIndex(w=>w.italic);

  const align = tweaks.alignment; // 'center' | 'bottom-left'

  return (
    <section
      ref={heroRef}
      className={`ml-hero ml-hero--${align}`}
      data-reduced={reduced ? "true":"false"}
      style={{
        "--hero-scale": parallax.s,
        "--hero-opacity": parallax.o,
        "--coral": tweaks.accent,
      }}
    >
      <VideoModal open={modalOpen} onClose={() => setModalOpen(false)} />
      <VideoBackdrop paused={paused} muted={muted} reduced={reduced}/>
      <div className="ml-hero-fadein"></div>
      <Nav scrolled={scrolled}/>

      {/* ▶ Play reel button — centred over the backdrop */}
      {DRIVE_FILE_ID && (
        <button
          onClick={() => setModalOpen(true)}
          aria-label="Watch reel"
          style={{
            position: "absolute",
            top: "50%", left: "50%",
            transform: "translate(-50%, -50%)",
            zIndex: 20,
            width: "72px", height: "72px",
            borderRadius: "50%",
            background: "rgba(13,27,42,0.55)",
            border: "1.5px solid rgba(224,225,221,0.35)",
            color: "#E0E1DD",
            cursor: "pointer",
            display: "flex", alignItems: "center", justifyContent: "center",
            backdropFilter: "blur(6px)",
            transition: "background 0.2s, transform 0.2s, border-color 0.2s",
            boxShadow: "0 4px 32px rgba(0,0,0,0.4)",
          }}
          onMouseEnter={e => {
            e.currentTarget.style.background = "rgba(119,141,169,0.55)";
            e.currentTarget.style.borderColor = "rgba(224,225,221,0.7)";
            e.currentTarget.style.transform = "translate(-50%, -50%) scale(1.08)";
          }}
          onMouseLeave={e => {
            e.currentTarget.style.background = "rgba(13,27,42,0.55)";
            e.currentTarget.style.borderColor = "rgba(224,225,221,0.35)";
            e.currentTarget.style.transform = "translate(-50%, -50%) scale(1)";
          }}
        >
          <svg width="18" height="20" viewBox="0 0 18 20" fill="none">
            <path d="M2 1.5L16 10L2 18.5V1.5Z" fill="currentColor"/>
          </svg>
        </button>
      )}

      <div className="ml-hero-stage">
        <div className="ml-hero-copy">
          <p className="ml-eyebrow" style={{"--d": reduced ? "0ms" : "0ms"}}>
            <span className="ml-eyebrow-tick"></span>
            Pastry &amp; Bakery Consultant for the GCC
          </p>

          <Headline words={headlineWords} italicIndex={italicIdx} reduced={reduced}/>

          <p className="ml-subline" style={{"--d": reduced ? "0ms" : `${300 + headlineWords.length*80 + 200}ms`}}>
            {tweaks.subline}
          </p>

          <div className="ml-cta-row" style={{"--d": reduced ? "0ms" : `${300 + headlineWords.length*80 + 400}ms`}}>
            <CTA variant="gold"  delay={0}   reduced={reduced} href="#contact">Request a Free Consultation</CTA>
            <CTA variant="ghost" delay={120} reduced={reduced} href="#portfolio">View Our Work</CTA>
          </div>
        </div>
      </div>

      {/* Corner detail clusters */}
      <div className="ml-corner ml-corner--tl">
        <span className="ml-corner-label">N&nbsp;33.893°&nbsp;·&nbsp;E&nbsp;35.501°</span>
      </div>
      <div className="ml-corner ml-corner--tr">
        <span className="ml-corner-label">Pastry&nbsp;·&nbsp;Bakery&nbsp;·&nbsp;Classes</span>
      </div>
      <div className="ml-corner ml-corner--bl">
        <span className="ml-corner-label">Beirut · Dubai · Riyadh</span>
      </div>
      <div className="ml-corner ml-corner--br">
        <MuteToggle muted={muted} onClick={()=>setMuted(m=>!m)} paused={paused} onPause={()=>setPaused(p=>!p)}/>
      </div>

      <ScrollCue/>
    </section>
  );
}

window.Hero = Hero;
