// ============== CINEMATIC HERO ANIMATION + SCROLL FX ==============
// SVG-driven hero loop (truck → pipe flow → camera scope → blue light cure)
// Plus scroll-triggered reveal animations. Pure CSS/SVG — no video file needed.

const { useState: useStateCN, useEffect: useEffectCN, useRef: useRefCN } = React;

// ▶ Hero videos come from CB_DATA.heroVideos. Two sources, in priority order:
//   1) The LIVE list a marketer manages inside the Sheetz app (/hero-videos) — fetched by
//      live-hero-videos.js from /api/site/hero-videos and merged into CB_DATA.heroVideos
//      BEFORE this renders (and again via the 'cb:hero-videos' event if it lands late).
//   2) The static fallback list hardcoded in data.js (usually empty).
// If BOTH are empty we never request a file, so there's no 404 — the SVG animation plays.
function pickHeroVideo() {
  const list = ((window.CB_DATA && window.CB_DATA.heroVideos) || []).filter((v) => v && v.src);
  if (!list.length) return null;
  return list[Math.floor(Math.random() * list.length)]; // rotate when several are listed
}

function HeroCinema() {
  const [pick, setPick] = useStateCN(pickHeroVideo); // chosen at mount; null = no video (yet)
  const [stage, setStage] = useStateCN(0);  // 0..3 loop (SVG fallback)
  const [useVideo, setUseVideo] = useStateCN(!!pick);

  // If the LIVE list from the app arrives after mount (async fetch), re-pick once so a
  // marketer's clip shows without a page reload. Fail-soft: only upgrades empty→video;
  // if the fetch was empty/failed this never fires and the SVG hero keeps playing.
  useEffectCN(() => {
    function onLive() {
      if (pick) return; // already showing a clip; don't yank it mid-visit
      const next = pickHeroVideo();
      if (next && next.src) { setPick(next); setUseVideo(true); }
    }
    window.addEventListener('cb:hero-videos', onLive);
    return () => window.removeEventListener('cb:hero-videos', onLive);
  }, [pick]);

  useEffectCN(() => {
    if (useVideo) return;
    const id = setInterval(() => setStage(s => (s + 1) % 4), 4200);
    return () => clearInterval(id);
  }, [useVideo]);

  const stageNames = ['DISPATCH', 'JETTING', 'CAMERA SCOPE', 'BLUE LIGHT CURE'];

  // Real footage of the crew/vans rolling — the million-dollar hero. Falls back to the animation on any error
  // (e.g. a listed file is missing/misnamed), so a bad filename never leaves a black box.
  if (useVideo && pick) {
    return (
      <div className="cinema-wrap">
        <video key={pick.src} className="cinema-video" autoPlay muted loop playsInline preload="metadata"
          poster={pick.poster || undefined} onError={() => setUseVideo(false)}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover' }}>
          <source src={pick.src} type="video/mp4" />
        </video>
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(8,12,20,.38) 0%, rgba(8,12,20,.12) 42%, rgba(8,12,20,.70) 100%)' }} />
        <div className="cinema-readout">
          <div className="cinema-readout-tag">●  FROM THE FIELD</div>
          <div className="cinema-readout-stage">CLOG BUSTERZ · CAMERA FIRST</div>
        </div>
      </div>
    );
  }

  return (
    <div className="cinema-wrap">
      {/* SVG scene */}
      <svg className="cinema-svg" viewBox="0 0 1600 900" xmlns="http://www.w3.org/2000/svg" aria-label="Clog Busterz job in motion">
        <defs>
          <linearGradient id="cn-sky" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#0e1a2b"/>
            <stop offset="100%" stopColor="#1a2c44"/>
          </linearGradient>
          <linearGradient id="cn-ground" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#0a1422"/>
            <stop offset="100%" stopColor="#04080f"/>
          </linearGradient>
          <radialGradient id="cn-blueglow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="#4ab3ff" stopOpacity="0.9"/>
            <stop offset="60%" stopColor="#2473c4" stopOpacity="0.3"/>
            <stop offset="100%" stopColor="#2473c4" stopOpacity="0"/>
          </radialGradient>
          <filter id="cn-glow" x="-50%" y="-50%" width="200%" height="200%">
            <feGaussianBlur stdDeviation="6" result="b"/>
            <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>
          </filter>
          <pattern id="cn-grid" x="0" y="0" width="80" height="80" patternUnits="userSpaceOnUse">
            <path d="M80 0 L0 0 0 80" fill="none" stroke="rgba(74,179,255,0.06)" strokeWidth="1"/>
          </pattern>
        </defs>

        {/* sky + grid */}
        <rect width="1600" height="900" fill="url(#cn-sky)"/>
        <rect width="1600" height="900" fill="url(#cn-grid)"/>

        {/* horizon line */}
        <line x1="0" y1="540" x2="1600" y2="540" stroke="rgba(74,179,255,0.18)" strokeWidth="1" strokeDasharray="6 8"/>

        {/* ground */}
        <rect y="540" width="1600" height="360" fill="url(#cn-ground)"/>

        {/* underground pipe — always visible */}
        <g className={`cn-pipe cn-pipe-stage-${stage}`}>
          <rect x="0" y="700" width="1600" height="56" fill="#1a2638" stroke="#2c3a52" strokeWidth="2"/>
          <line x1="0" y1="700" x2="1600" y2="700" stroke="rgba(74,179,255,0.12)" strokeWidth="1"/>
          <line x1="0" y1="756" x2="1600" y2="756" stroke="rgba(0,0,0,0.5)" strokeWidth="1"/>

          {/* Stage 1: flowing water */}
          {stage === 1 && (
            <g className="cn-water-flow">
              {[...Array(8)].map((_, i) => (
                <rect key={i} x={-100 - i*180} y="720" width="80" height="16" fill="#4ab3ff" opacity="0.6" rx="8">
                  <animate attributeName="x" from={-100} to="1700" dur="2.4s" begin={`${i*0.3}s`} repeatCount="indefinite"/>
                </rect>
              ))}
            </g>
          )}

          {/* Stage 2: camera + LED */}
          {stage === 2 && (
            <g className="cn-camera">
              <circle cx="500" cy="728" r="22" fill="#1a2638" stroke="#4ab3ff" strokeWidth="2">
                <animate attributeName="cx" from="0" to="1600" dur="3.6s" repeatCount="indefinite"/>
              </circle>
              <circle cx="500" cy="728" r="14" fill="#4ab3ff" filter="url(#cn-glow)">
                <animate attributeName="cx" from="0" to="1600" dur="3.6s" repeatCount="indefinite"/>
                <animate attributeName="opacity" values="0.7;1;0.7" dur="0.6s" repeatCount="indefinite"/>
              </circle>
              {/* trailing cable */}
              <line x1="0" y1="728" x2="500" y2="728" stroke="#4ab3ff" strokeWidth="1.5" strokeDasharray="4 4" opacity="0.5">
                <animate attributeName="x2" from="0" to="1600" dur="3.6s" repeatCount="indefinite"/>
              </line>
            </g>
          )}

          {/* Stage 3: blue light CIPP cure */}
          {stage === 3 && (
            <g className="cn-cure">
              <rect x="0" y="708" width="1600" height="40" fill="url(#cn-blueglow)" opacity="0">
                <animate attributeName="opacity" values="0;0.85;0.85;0" keyTimes="0;0.25;0.85;1" dur="3.8s" repeatCount="indefinite"/>
              </rect>
              <circle cx="200" cy="728" r="40" fill="#4ab3ff" filter="url(#cn-glow)" opacity="0.9">
                <animate attributeName="cx" from="0" to="1600" dur="3.8s" repeatCount="indefinite"/>
              </circle>
              <circle cx="200" cy="728" r="14" fill="#fff" opacity="0.95">
                <animate attributeName="cx" from="0" to="1600" dur="3.8s" repeatCount="indefinite"/>
              </circle>
            </g>
          )}
        </g>

        {/* Stage 0: TRUCK rolling in */}
        {stage === 0 && (
          <g className="cn-truck">
            {/* body */}
            <g>
              <animateTransform attributeName="transform" type="translate" from="-600 0" to="1200 0" dur="4s" repeatCount="1" fill="freeze"/>
              {/* cab */}
              <rect x="80" y="440" width="160" height="120" fill="#2473c4" stroke="#0e1a2b" strokeWidth="3"/>
              <rect x="100" y="455" width="50" height="60" fill="#7cc1ff" opacity="0.5" stroke="#0e1a2b" strokeWidth="2"/>
              {/* box */}
              <rect x="230" y="400" width="320" height="160" fill="#0e1a2b" stroke="#2473c4" strokeWidth="3"/>
              {/* logo on box */}
              <text x="390" y="475" textAnchor="middle" fontFamily="Archivo Black, sans-serif" fontSize="36" fill="#4ab3ff" letterSpacing="2">CLOG BUSTERZ</text>
              <text x="390" y="510" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="14" fill="rgba(255,255,255,0.5)" letterSpacing="3">859-408-3382</text>
              <text x="390" y="535" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="10" fill="rgba(255,255,255,0.4)" letterSpacing="2">LIC #M7707 · RICHMOND KY</text>
              {/* wheels */}
              <circle cx="160" cy="580" r="32" fill="#0a0e14" stroke="#2c3a52" strokeWidth="3"/>
              <circle cx="160" cy="580" r="14" fill="#2c3a52"/>
              <circle cx="460" cy="580" r="32" fill="#0a0e14" stroke="#2c3a52" strokeWidth="3"/>
              <circle cx="460" cy="580" r="14" fill="#2c3a52"/>
              {/* headlights beam */}
              <path d="M 80 490 L -40 470 L -40 530 L 80 510 Z" fill="#fff8d4" opacity="0.35"/>
              {/* roof rack tools */}
              <rect x="240" y="385" width="90" height="6" fill="#9aa6b8"/>
              <rect x="350" y="385" width="120" height="6" fill="#9aa6b8"/>
            </g>
            {/* dust */}
            <g opacity="0.4">
              <circle cx="-50" cy="600" r="12" fill="#4a5a72">
                <animate attributeName="cx" from="-50" to="1100" dur="4s" repeatCount="1"/>
                <animate attributeName="r" values="6;18;6" dur="1.5s" repeatCount="indefinite"/>
              </circle>
              <circle cx="-20" cy="610" r="8" fill="#4a5a72">
                <animate attributeName="cx" from="-20" to="1150" dur="4s" repeatCount="1"/>
                <animate attributeName="r" values="4;14;4" dur="1.2s" repeatCount="indefinite"/>
              </circle>
            </g>
          </g>
        )}

        {/* stage label HUD */}
        <g className="cn-hud">
          <rect x="40" y="40" width="180" height="32" fill="rgba(74,179,255,0.12)" stroke="#4ab3ff" strokeWidth="1"/>
          <circle cx="58" cy="56" r="5" fill="#4ab3ff">
            <animate attributeName="opacity" values="1;0.3;1" dur="1.2s" repeatCount="indefinite"/>
          </circle>
          <text x="74" y="61" fontFamily="JetBrains Mono, monospace" fontSize="12" fill="#4ab3ff" letterSpacing="2">● {stageNames[stage]}</text>
        </g>

        {/* timestamp HUD */}
        <g>
          <rect x="1380" y="40" width="180" height="32" fill="rgba(255,255,255,0.04)" stroke="rgba(255,255,255,0.15)" strokeWidth="1"/>
          <text x="1470" y="61" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="12" fill="rgba(255,255,255,0.7)" letterSpacing="2">CB-CINEMA</text>
        </g>

        {/* Stage progress bar */}
        <g>
          {[0,1,2,3].map(i => (
            <rect key={i} x={40 + i*68} y={830} width="60" height="3" fill={i <= stage ? '#4ab3ff' : 'rgba(255,255,255,0.12)'}>
              {i === stage && <animate attributeName="opacity" values="1;0.4;1" dur="1s" repeatCount="indefinite"/>}
            </rect>
          ))}
        </g>
      </svg>

      {/* Overlay readout */}
      <div className="cinema-readout">
        <div className="cinema-readout-tag">●  FROM THE TRUCK</div>
        <div className="cinema-readout-stage">STAGE {stage + 1} / 4 · {stageNames[stage]}</div>
      </div>
    </div>
  );
}

// ============== SCROLL-TRIGGERED REVEAL ANIMATIONS ==============
function ScrollReveal() {
  useEffectCN(() => {
    const sels = [
      '.hero', '.services', '.diagnose-section', '.areas', '.why',
      '.reviews', '.bluelight', '.wh', '.fb-section', '.coupons',
      '.lot', '.faq', '.ai-section', '.vid-section', '.estimator',
      '.city-spot', '.pb-section', '.vip', '.blog-strip', '.sec-head'
    ].join(',');
    const els = document.querySelectorAll(sels);
    els.forEach(el => el.classList.add('reveal-init'));

    const io = new IntersectionObserver(entries => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('reveal-in');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.08, rootMargin: '0px 0px -8% 0px' });

    els.forEach(el => io.observe(el));

    // FAIL-VISIBLE SAFETY NET. reveal-init hides content until the observer fires — if the
    // observer misses (busy main thread, browser quirk, bfcache restore, fast scroll), whole
    // sections stayed BLANK forever (hit on launch night). This heartbeat force-reveals
    // anything in/near the viewport the observer missed. Content must never fail hidden.
    const revealNow = () => {
      const vh = window.innerHeight || 900;
      els.forEach(el => {
        if (el.classList.contains('reveal-in')) return;
        const r = el.getBoundingClientRect();
        if (r.top < vh * 0.96 && r.bottom > 0) { el.classList.add('reveal-in'); io.unobserve(el); }
      });
    };
    window.addEventListener('scroll', revealNow, { passive: true });
    window.addEventListener('resize', revealNow, { passive: true });
    const heartbeat = setInterval(revealNow, 1200);
    revealNow();

    return () => {
      io.disconnect();
      clearInterval(heartbeat);
      window.removeEventListener('scroll', revealNow);
      window.removeEventListener('resize', revealNow);
    };
  }, []);
  return null;
}

window.HeroCinema = HeroCinema;
window.ScrollReveal = ScrollReveal;
