"use client";

import { useEffect, useState } from "react";
import { resolveMediaUrl } from "@/lib/api/client";

type MenuItemModelViewerProps = {
  modelUrl: string;
  posterUrl?: string | null;
  alt: string;
  className?: string;
};

// `@google/model-viewer` references browser globals (`self`) at module load, so a
// top-level `import` crashes server-side rendering (e.g. the /q guest menu).
// Load it lazily on the client only, once, the first time a viewer mounts.
let modelViewerLoad: Promise<unknown> | null = null;
function ensureModelViewerLoaded(): Promise<unknown> {
  if (typeof window === "undefined") return Promise.resolve();
  modelViewerLoad ??= import("@google/model-viewer");
  return modelViewerLoad;
}

export function MenuItemModelViewer({
  modelUrl,
  posterUrl,
  alt,
  className,
}: MenuItemModelViewerProps) {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    let active = true;
    void ensureModelViewerLoaded().then(() => {
      if (active) setReady(true);
    });
    return () => {
      active = false;
    };
  }, []);

  const src = resolveMediaUrl(modelUrl);
  const poster = posterUrl ? resolveMediaUrl(posterUrl) : undefined;
  if (!src) return null;

  // Until the custom element is registered, show the poster (or an empty box) so
  // layout is stable and nothing references the browser-only library on the server.
  if (!ready) {
    return (
      <div
        className={className}
        style={{
          width: "100%",
          height: "100%",
          minHeight: "min(72vh, 420px)",
          backgroundColor: "rgba(0,0,0,0.04)",
          backgroundImage: poster ? `url(${poster})` : undefined,
          backgroundSize: "contain",
          backgroundPosition: "center",
          backgroundRepeat: "no-repeat",
        }}
        aria-label={alt}
        role="img"
      />
    );
  }

  return (
    // @ts-expect-error model-viewer is a custom element from @google/model-viewer
    <model-viewer
      src={src}
      poster={poster}
      alt={alt}
      camera-controls
      touch-action="pan-y"
      auto-rotate
      rotation-per-second="28deg"
      interaction-prompt="none"
      shadow-intensity="1"
      exposure="1"
      environment-image="neutral"
      className={className}
      style={{ width: "100%", height: "100%", minHeight: "min(72vh, 420px)" }}
    />
  );
}
