// Cinematic 3D garage navigation — v4 (layered painted scene + parallax).
// gsap.matchMedia forks desktop/tablet/mobile timelines.
// Each layer has data-depth ∈ [0..1]; scroll progress translates each
// layer by depth*range so the scene "moves through" the camera.

const STOPS = ['hero', 'services', 'process', 'whyus', 'reviews', 'contact'];

const STOP_LABELS = {
  hero:     'MAIN BAY',
  services: 'TOOL WALL · SERVICES',
  process:  'DIAGNOSTIC · PROCESS',
  whyus:    'TRUST WALL · WHY US',
  reviews:  'LOUNGE · REVIEWS',
  contact:  'FRONT DESK · CONTACT',
};

const Nav = ({ onBook, currentStop, gotoStop, phone, phoneTel }) => (
  <nav className="cnav">
    <div className="inner">
      <a href="#top" className="brand" onClick={(e) => { e.preventDefault(); gotoStop('hero'); }}>
        <img src="./assets/logo-monogram.svg" alt="IAG" />
        <div className="wm">Infinite Auto Garage<small>FORT MYERS · BAY 03</small></div>
      </a>
      <div className="links">
        {STOPS.map((s) => (
          <button key={s} className={currentStop === s ? 'active' : ''} onClick={() => gotoStop(s)}>
            {{hero:'Bay', services:'Services', process:'Process', whyus:'Why us', reviews:'Reviews', contact:'Contact'}[s]}
          </button>
        ))}
      </div>
      <div className="cta">
        <a href={phoneTel} className="phone">{phone}</a>
        <a href="customer.html" className="my-garage-link" title="View, reschedule, or cancel">
          <svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true">
            <rect x="2" y="3" width="12" height="10" rx="1.5" stroke="currentColor" strokeWidth="1.4"/>
            <path d="M2 6.5h12" stroke="currentColor" strokeWidth="1.4"/>
            <path d="M5 2v2M11 2v2" stroke="currentColor" strokeWidth="1.4"/>
          </svg>
          <span>My Garage</span>
        </a>
        <button className="btn btn-primary btn-sm" onClick={onBook} style={{padding:'10px 16px', minHeight:0, fontSize:13}}>
          Book Service
        </button>
      </div>
    </div>
  </nav>
);

const StageIndicator = ({ currentStop, index, total }) => (
  <div className="stage-indicator">
    <span className="dot" />
    STAGE {String(index).padStart(2,'0')} / {String(total).padStart(2,'0')} · {STOP_LABELS[currentStop]}
  </div>
);

const StopsRail = ({ currentStop, gotoStop }) => (
  <div className="stops-rail">
    {STOPS.map((s) => (
      <button key={s} className={`stop ${currentStop === s ? 'active' : ''}`} onClick={() => gotoStop(s)}>
        <span className="tick" />
        {STOP_LABELS[s].split(' · ')[1] || STOP_LABELS[s]}
      </button>
    ))}
  </div>
);

const MobileCTA = ({ phoneTel, mapsUrl }) => (
  <div className="mobile-cta">
    <a href={phoneTel} className="btn btn-primary">
      <IconPhone size={16} /> Call Now
    </a>
    <a href={mapsUrl}
       target="_blank" rel="noopener"
       className="btn btn-amber">
      <IconPin size={16} /> Directions
    </a>
  </div>
);

function CinematicAppV2() {
  const [booking, setBooking] = React.useState(false);
  const [currentStop, setCurrentStop] = React.useState('hero');
  const [siteContent, setSiteContent] = React.useState(() =>
    typeof window.getSiteContent === 'function' ? window.getSiteContent() : null
  );
  React.useEffect(() => {
    const refresh = () => setSiteContent(window.getSiteContent());
    window.addEventListener('site-content-updated', refresh);
    return () => window.removeEventListener('site-content-updated', refresh);
  }, []);
  const navPhone   = siteContent?.hero?.phone   || '239-355-8787';
  const navAddress = siteContent?.hero?.address || '4036 Fowler St · Fort Myers, FL 33901';
  const phoneTel   = window.phoneToTel ? window.phoneToTel(navPhone) : `tel:${navPhone}`;
  const mapsUrl    = `https://maps.google.com/?q=${encodeURIComponent(navAddress)}`;
  const shellRef = React.useRef(null);
  const sceneRef = React.useRef(null);
  const stopsApiRef = React.useRef({ gotoStop: () => {} });

  React.useEffect(() => {
    if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') return;
    gsap.registerPlugin(ScrollTrigger);

    const mm = gsap.matchMedia();

    mm.add(
      {
        isDesktop: '(min-width: 1024px)',
        isTablet:  '(min-width: 768px) and (max-width: 1023px)',
        isMobile:  '(max-width: 767px)',
        reduceMotion: '(prefers-reduced-motion: reduce)',
      },
      (ctx) => {
        const { isDesktop, isTablet, isMobile, reduceMotion } = ctx.conditions;

        const scene = sceneRef.current;
        const world = scene.querySelector('[data-world]');
        const layers = Array.from(scene.querySelectorAll('[data-depth]'));
        const panels = Array.from(scene.querySelectorAll('.stage-panel'));
        const panelByStop = {};
        panels.forEach((p) => { panelByStop[p.dataset.stop] = p; });

        if (isMobile) {
          // Mobile: drop the 3D scene; show panels as vertical cards via CSS.
          gsap.set(panels, { clearProps: 'all' });
          setCurrentStop('hero');
          return;
        }

        const scrollLen = isDesktop ? 3200 : 2200;
        const depthScale = isDesktop ? 1.0 : 0.75;

        // Force panels invisible initially (except hero)
        gsap.set(panels, { opacity: 0, y: 30 });
        if (panelByStop.hero) gsap.set(panelByStop.hero, { opacity: 1, y: 0 });

        // Master timeline — pin scene, scroll progress drives panels + parallax
        const tl = gsap.timeline({
          defaults: { ease: 'none' },
          scrollTrigger: {
            trigger: scene,
            start: 'top top',
            end: `+=${scrollLen}`,
            scrub: 1,
            pin: true,
            anticipatePin: 1,
            invalidateOnRefresh: true,
            refreshPriority: 1,
            onUpdate: (self) => {
              const segLen = 1 / (STOPS.length - 1);
              const i = Math.min(
                STOPS.length - 1,
                Math.max(0, Math.round(self.progress / segLen))
              );
              const next = STOPS[i] || 'hero';
              setCurrentStop(prev => prev === next ? prev : next);
            },
          },
        });

        // Camera "dolly" effect:
        // - Scale the WHOLE world from 1 → 1.35 (gives "moving in" sensation)
        // - Translate world Y subtly upward
        // - PARALLAX: each layer's translateY is depth * scrollLen (deeper layers move more)
        tl.fromTo(world,
          { scale: 1.0, y: 0 },
          { scale: 1.35, y: -60, duration: 1, ease: 'none' },
          0
        );

        // Per-layer parallax — outer layers (low depth) move slowly, inner layers (cars, particles) move faster
        layers.forEach((layer) => {
          const depth = parseFloat(layer.dataset.depth) || 0;
          const range = depth * 180 * depthScale; // px shift over full scroll
          tl.fromTo(layer,
            { y: 0 },
            { y: -range, duration: 1, ease: 'none' },
            0
          );
        });

        // PANEL CROSS-FADES
        const segLen = 1 / (STOPS.length - 1);
        STOPS.forEach((stop, i) => {
          const panel = panelByStop[stop];
          if (!panel) return;

          const fadeInAt  = Math.max(0, (i - 0.5) * segLen);
          const fadeOutAt = Math.min(1, (i + 0.5) * segLen);
          const fadeDur   = segLen * 0.4;

          if (stop !== 'hero') {
            tl.fromTo(panel,
              { opacity: 0, y: 30 },
              { opacity: 1, y: 0, duration: fadeDur, ease: 'power3.out' },
              fadeInAt
            );
          }
          if (i < STOPS.length - 1) {
            tl.to(panel,
              { opacity: 0, y: -30, duration: fadeDur, ease: 'power3.in' },
              fadeOutAt - fadeDur
            );
          }
        });

        // Refresh after fonts load
        if (document.fonts && document.fonts.ready) {
          document.fonts.ready.then(() => ScrollTrigger.refresh());
        }

        // gotoStop helper
        stopsApiRef.current.gotoStop = (stop) => {
          const st = tl.scrollTrigger;
          if (!st) return;
          const i = STOPS.indexOf(stop);
          if (i < 0) return;
          const top = st.start + (i * segLen) * scrollLen;
          window.scrollTo({ top, behavior: 'smooth' });
        };
      }
    );

    return () => mm.revert();
  }, []);

  const gotoStop = (stop) => stopsApiRef.current.gotoStop(stop);
  const stopIndex = STOPS.indexOf(currentStop);

  return (
    <div className="shell" ref={shellRef}>
      <Nav onBook={() => setBooking(true)} currentStop={currentStop} gotoStop={gotoStop} phone={navPhone} phoneTel={phoneTel} />
      <StageIndicator currentStop={currentStop} index={Math.max(1, stopIndex + 1)} total={STOPS.length} />
      <StopsRail currentStop={currentStop} gotoStop={gotoStop} />

      <div className="scene" ref={sceneRef} id="top">
        <PersistentGarage />
        <StagePanels onBook={() => setBooking(true)} currentStop={currentStop} />
      </div>

      <Footer />

      <MobileCTA phoneTel={phoneTel} mapsUrl={mapsUrl} />
      <BookingModal open={booking} onClose={() => setBooking(false)} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<CinematicAppV2 />);
