// ============================================================================
// MobileHero — clean, static mobile-only heroes. Zero heavy animation.
// Rendered inside .mobile-only wrappers (visible <=768px).
// Matches the desktop brand but uses a single looping video as ambient backdrop.
// ============================================================================

(function () {

  // --- Poster video backdrop — same assets as desktop, but sized for phone
  // Strategy: ALWAYS render the <video>. Poster is layered BEHIND it so it
  // shows through until the first frame is painted, and remains visible if
  // playback never starts (Low Power Mode, etc.) — we don't unmount the video,
  // because doing so meant a single transient play() rejection permanently
  // killed playback on mobile. Instead we keep retrying: on canplay, on
  // visibility change, and on the first user tap anywhere on the page.
  function HeroVideoBackdrop({ src, poster, overlay = 0.35 }) {
    const ref = React.useRef(null);
    const [playing, setPlaying] = React.useState(false);

    React.useEffect(() => {
      const v = ref.current;
      if (!v) return;
      v.muted = true;
      v.defaultMuted = true;
      v.playsInline = true;
      v.setAttribute('playsinline', '');
      v.setAttribute('webkit-playsinline', '');

      let cancelled = false;
      const tryPlay = () => {
        if (cancelled || !v) return;
        const p = v.play();
        if (p && typeof p.then === 'function') {
          p.then(() => { if (!cancelled) setPlaying(true); })
           .catch(() => { /* will retry on next trigger */ });
        } else {
          setPlaying(true);
        }
      };

      // Retry hooks
      const onCanPlay = () => tryPlay();
      const onPlaying = () => setPlaying(true);
      const onVis = () => { if (!document.hidden) tryPlay(); };
      const onTouch = () => tryPlay();

      v.addEventListener('canplay', onCanPlay);
      v.addEventListener('playing', onPlaying);
      document.addEventListener('visibilitychange', onVis);
      document.addEventListener('touchstart', onTouch, { once: true, passive: true });
      document.addEventListener('click', onTouch, { once: true });

      // Kick it off
      tryPlay();
      // Also retry once shortly after mount (iOS Safari sometimes needs a beat)
      const t = setTimeout(tryPlay, 400);

      return () => {
        cancelled = true;
        clearTimeout(t);
        v.removeEventListener('canplay', onCanPlay);
        v.removeEventListener('playing', onPlaying);
        document.removeEventListener('visibilitychange', onVis);
        document.removeEventListener('touchstart', onTouch);
        document.removeEventListener('click', onTouch);
      };
    }, [src]);

    return (
      <div style={{ position: 'absolute', inset: 0, overflow: 'hidden',
        borderRadius: 'inherit',
        background: 'linear-gradient(180deg, #0B1220 0%, #101a2e 100%)' }}>
        {/* Poster sits BEHIND the video — visible until first frame paints,
            and remains visible if autoplay never starts. */}
        {poster && (
          <img src={poster} alt="" aria-hidden="true"
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
              objectFit: 'cover', zIndex: 1 }}/>
        )}
        <video ref={ref}
          src={src}
          autoPlay muted loop playsInline
          preload="metadata"
          poster={poster}
          style={{ position: 'absolute', inset: 0, width: '100%', height: '100%',
            objectFit: 'cover', zIndex: 2, pointerEvents: 'none',
            opacity: playing ? 1 : 0, transition: 'opacity 300ms ease' }}
        />
        {/* Legibility gradient */}
        <div aria-hidden style={{ position: 'absolute', inset: 0, zIndex: 3,
          background: `linear-gradient(180deg, rgba(11,18,32,${overlay}) 0%, rgba(11,18,32,${overlay * 0.6}) 45%, rgba(11,18,32,${overlay * 1.15}) 100%)` }}/>
      </div>
    );
  }

  // --- Homepage mobile hero --------------------------------------------------
  function HomeMobileHero() {
    const ORB = 'uploads/optimized/im-orb.mp4';
    const POSTER = 'assets/hero-mobile-poster.png';
    return (
      <section className="mb-hero mb-hero--home">
        {/* Dark-to-light video band on top */}
        <div className="mb-hero__media">
          <HeroVideoBackdrop src={ORB} poster={POSTER} overlay={0.45}/>
          <div className="mb-hero__pill">
            <span className="mb-hero__pill-dot"/>
            <span>Live · 40+ carriers</span>
          </div>
        </div>

        {/* White copy block */}
        <div className="mb-hero__body">
          <div className="mb-hero__rating">
            {[0,1,2,3,4].map(i => (
              <svg key={i} width="12" height="12" viewBox="0 0 24 24" fill="#FF801E">
                <path d="M12 2l2.9 6.9 7.5.6-5.7 4.9 1.7 7.3L12 17.8 5.6 21.7l1.7-7.3L1.6 9.5l7.5-.6L12 2z"/>
              </svg>
            ))}
            <span>4.9 · 2,000+ shippers</span>
          </div>
          <h1 className="mb-hero__title">
            Logistics,<br/>
            <span className="mb-hero__title-grad">reimagined.</span>
          </h1>
          <p className="mb-hero__lead">
            Quote, book, and track freight globally — one platform for air, ocean,
            ground and courier.
          </p>
          <div className="mb-hero__cta-row">
            <a href="#quote" className="mb-cta-primary"
              onClick={(e) => { e.preventDefault();
                window.__abgsCTA && window.__abgsCTA.openQuote('mobile-hero-quote'); }}>
              Get instant quote
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M13 6l6 6-6 6"/>
              </svg>
            </a>
            <a href="#platform" className="mb-cta-ghost">Explore platform</a>
          </div>
          <div className="mb-hero__trust">
            <span><span className="dot"/>NVOCC licensed</span>
            <span><span className="dot"/>C-TPAT</span>
            <span><span className="dot"/>SOC 2 Type II</span>
          </div>
        </div>
      </section>
    );
  }

  // --- Ocean Freight mobile hero --------------------------------------------
  function OceanMobileHero() {
    const VIDEO = '../uploads/Whisk_yjy4ajnwydzzudmx0cokltytgjmhrtl5kdm30cm-25181c3c.mp4';
    const POSTER = '../assets/hero-poster-ocean-freight.png';
    return (
      <section className="mb-hero mb-hero--service">
        <div className="mb-hero__media">
          <HeroVideoBackdrop src={VIDEO} poster={POSTER} overlay={0.5}/>
          <div className="mb-hero__chip">LOGISTICS & TRANSPORT · OCEAN FREIGHT</div>
          {/* Static telemetry stack — NO animation, just info */}
          <div className="mb-hero__telemetry">
            <div className="mb-hero__telemetry-row">
              <span className="mb-hero__telemetry-live">
                <span className="mb-hero__telemetry-dot"/>UNDERWAY
              </span>
              <span className="mb-hero__telemetry-id">MSCU-7712</span>
            </div>
            <div className="mb-hero__telemetry-route">
              <span>SHA</span>
              <span className="mb-hero__telemetry-dash"/>
              <span>LGB</span>
            </div>
            <div className="mb-hero__telemetry-meta">
              <span>18.1 kn · ETA 14 Nov · 42% complete</span>
            </div>
          </div>
        </div>

        <div className="mb-hero__body">
          <h1 className="mb-hero__title">
            Ocean freight,<br/>
            <span className="mb-hero__title-grad">on every lane.</span>
          </h1>
          <p className="mb-hero__lead">
            FCL, LCL, reefer and breakbulk — live rates from 40+ carriers,
            customs-ready, tracked end to end.
          </p>
          <div className="mb-hero__cta-row">
            <a href="#quote" className="mb-cta-primary"
              onClick={(e) => { e.preventDefault();
                window.__abgsCTA && window.__abgsCTA.openQuote('mobile-hero-quote', { audience: 'business' }); }}>
              Get live rates
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M13 6l6 6-6 6"/>
              </svg>
            </a>
            <a href="#lanes" className="mb-cta-ghost">See live lanes</a>
          </div>
          {/* mini stat strip */}
          <div className="mb-hero__stats">
            <div><strong>98.4%</strong><span>On-time</span></div>
            <div><strong>40+</strong><span>Carriers</span></div>
            <div><strong>186</strong><span>Ports</span></div>
          </div>
        </div>
      </section>
    );
  }

  // --- Per-slug hero video map for service pages ----------------------------
  const SERVICE_HERO_VIDEOS = {
    'air-freight':   '../uploads/optimized/air-freight.mp4',
    'trucking':      '../uploads/optimized/trucking.mp4',
    'ocean-freight': '../uploads/Whisk_yjy4ajnwydzzudmx0cokltytgjmhrtl5kdm30cm-25181c3c.mp4',
    'international-moves': '../uploads/optimized/im-orb.mp4',
    'break-bulk':    '../uploads/BreakBulk_crane_loading_202604221145.mp4',
    'less-than-container': '../uploads/optimized/lcl.mp4',
    'replenishment': '../uploads/optimized/replenishment.mp4',
    'cargo-insurance': '../uploads/optimized/cargo-insurance.mp4',
    'buyers-consolidation': '../uploads/buyers-consolidation-hero-5d6f6ac2.mp4',
  };
  const DEFAULT_HERO_VIDEO = '../uploads/Earth_floating_studio_202604212142.mp4';

  // Parallel poster map — first-frame stills for iOS Low-Power-Mode fallback
  const SERVICE_HERO_POSTERS = {
    'air-freight':   '../assets/hero-poster-air-freight.png',
    'trucking':      '../assets/hero-poster-trucking.png',
    'ocean-freight': '../assets/hero-poster-ocean-freight.png',
    'international-moves': '../assets/hero-poster-international-moves.png',
    'break-bulk':    '../assets/hero-poster-break-bulk.png',
    'less-than-container': '../assets/hero-poster-less-than-container.png',
    'replenishment': '../assets/hero-poster-replenishment.png',
    'cargo-insurance': '../assets/hero-poster-cargo-insurance.png',
    'buyers-consolidation': '../assets/hero-poster-buyers-consolidation.png',
  };
  const DEFAULT_HERO_POSTER = '../assets/hero-poster-default.png';

  // --- Generic Service mobile hero — data-driven from content.hero ----------
  // Props: slug, division (for chip label), hero (= content.hero), icon
  function ServiceMobileHero({ slug, division, hero, icon }) {
    if (!hero) return null;
    const video = SERVICE_HERO_VIDEOS[slug] || DEFAULT_HERO_VIDEO;
    const poster = SERVICE_HERO_POSTERS[slug] || DEFAULT_HERO_POSTER;
    const chipText = division
      ? `${division.label.toUpperCase()}`
      : (hero.kicker || '').toUpperCase();

    // Use first 3 stats if provided
    const stats = (hero.stats || []).slice(0, 3);

    return (
      <section className="mb-hero mb-hero--service">
        <div className="mb-hero__media">
          <HeroVideoBackdrop src={video} poster={poster} overlay={0.5}/>
          {chipText && <div className="mb-hero__chip">{chipText}</div>}
        </div>

        <div className="mb-hero__body">
          <h1 className="mb-hero__title">
            {hero.title}{hero.titleAccent ? <br/> : null}
            {hero.titleAccent && (
              <span className="mb-hero__title-grad">{hero.titleAccent}</span>
            )}
          </h1>
          <p className="mb-hero__lead">{hero.lead}</p>
          <div className="mb-hero__cta-row">
            <a href="#quote" className="mb-cta-primary"
              onClick={(e) => { e.preventDefault();
                window.__abgsCTA && window.__abgsCTA.openQuote('mobile-hero-quote'); }}>
              Get instant quote
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M5 12h14M13 6l6 6-6 6"/>
              </svg>
            </a>
            <a href="#talk" className="mb-cta-ghost"
              onClick={(e) => { e.preventDefault();
                window.__abgsCTA && window.__abgsCTA.openContact('mobile-hero-talk',
                  { intent: 'specialist', topic: hero && hero.kicker ? hero.kicker : null }); }}>
              Talk to specialist
            </a>
          </div>
          {stats.length > 0 && (
            <div className="mb-hero__stats">
              {stats.map((s, i) => (
                <div key={i}><strong>{s.value}</strong><span>{s.label}</span></div>
              ))}
            </div>
          )}
        </div>
      </section>
    );
  }

  window.HomeMobileHero    = HomeMobileHero;
  window.OceanMobileHero   = OceanMobileHero;
  window.ServiceMobileHero = ServiceMobileHero;
})();
