// PersistentGarage — host for the 3D cinematic background.
//
// The visual rendering is owned by Garage3D.jsx (loaded as an ESM Babel
// module). This component simply mounts a container and asks Garage3D
// to render its React Three Fiber canvas into it.
//
// The rest of CinematicAppV2's structure (.scene pinning, panels) is
// untouched — only the BACKGROUND is replaced.

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

const PersistentGarage = () => {
  const canvasHostRef = React.useRef(null);

  React.useEffect(() => {
    let cleanup = null;
    let tries = 0;
    let cancelled = false;

    const tryMount = () => {
      if (cancelled) return;
      if (window.__mountGarage3D && canvasHostRef.current) {
        try {
          cleanup = window.__mountGarage3D(canvasHostRef.current);
        } catch (err) {
          // Surface failures to the console but don't crash the page.
          // eslint-disable-next-line no-console
          console.error('[PersistentGarage] Garage3D mount failed:', err);
        }
        return;
      }
      if (tries++ < 200) {
        setTimeout(tryMount, 50); // wait for the ESM module to load
      } else {
        // eslint-disable-next-line no-console
        console.warn('[PersistentGarage] window.__mountGarage3D never appeared.');
      }
    };

    tryMount();

    return () => {
      cancelled = true;
      if (typeof cleanup === 'function') {
        try { cleanup(); } catch (e) {}
      }
    };
  }, []);

  return (
    <div className="world" data-world>
      {/* R3F canvas mounts here */}
      <div className="world-3d" ref={canvasHostRef} />
      {/* Cinematic overlay above the canvas — vignette + side darken so
          panel copy reads cleanly without dimming the car too much. */}
      <div className="world-3d-overlay" aria-hidden="true" />
    </div>
  );
};

window.PersistentGarage = PersistentGarage;
