"use client";

import { useRef, useState } from "react";
import Image from "next/image";
import { ChevronLeft, ChevronRight, ZoomIn } from "lucide-react";

type ProductImage = { url: string; altText: string | null };

export default function ProductGallery({
  images,
  productName,
}: {
  images: ProductImage[];
  productName: string;
}) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isZooming, setIsZooming] = useState(false);
  const [zoomPos, setZoomPos] = useState({ x: 50, y: 50 });
  const containerRef = useRef<HTMLDivElement>(null);

  const active = images[activeIndex] ?? images[0];

  function goTo(index: number) {
    setActiveIndex(((index % images.length) + images.length) % images.length);
  }

  function handleMouseMove(e: React.MouseEvent<HTMLDivElement>) {
    const rect = containerRef.current?.getBoundingClientRect();
    if (!rect) return;
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setZoomPos({ x: Math.max(0, Math.min(100, x)), y: Math.max(0, Math.min(100, y)) });
  }

  return (
    <div className="flex flex-col gap-3">
      {/* Main image with hover zoom */}
      <div
        ref={containerRef}
        className="relative aspect-square bg-sand rounded-lg overflow-hidden border border-line cursor-zoom-in"
        onMouseEnter={() => setIsZooming(true)}
        onMouseLeave={() => setIsZooming(false)}
        onMouseMove={handleMouseMove}
      >
        {active && (
          <Image
            src={active.url}
            alt={active.altText ?? productName}
            fill
            className="object-cover"
            priority
            sizes="(max-width:1024px) 100vw, 33vw"
          />
        )}

        {/* Zoomed layer — same image, scaled up, positioned to follow the cursor */}
        {active && isZooming && (
          <div
            className="absolute inset-0 pointer-events-none hidden lg:block"
            style={{
              backgroundImage: `url(${active.url})`,
              backgroundSize: "200%",
              backgroundPosition: `${zoomPos.x}% ${zoomPos.y}%`,
              backgroundRepeat: "no-repeat",
            }}
          />
        )}

        {!isZooming && (
          <span className="absolute bottom-2 right-2 bg-ink/60 text-white text-xs px-2 py-1 rounded flex items-center gap-1 lg:flex hidden">
            <ZoomIn size={12} /> Hover to zoom
          </span>
        )}

        {/* Prev / next arrows */}  
        {images.length > 1 && (
          <>
            <button
              onClick={(e) => {
                e.stopPropagation();
                goTo(activeIndex - 1);
              }}
              className="absolute left-2 top-1/2 -translate-y-1/2 bg-white/90 hover:bg-white rounded-full p-1.5 shadow-sm transition-colors"
              aria-label="Previous image"
            >
              <ChevronLeft size={18} />
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                goTo(activeIndex + 1);
              }}
              className="absolute right-2 top-1/2 -translate-y-1/2 bg-white/90 hover:bg-white rounded-full p-1.5 shadow-sm transition-colors"
              aria-label="Next image"
            >
              <ChevronRight size={18} />
            </button>
            <span className="absolute top-2 right-2 bg-ink/60 text-white text-xs font-mono px-2 py-1 rounded">
              {activeIndex + 1} / {images.length}
            </span>
          </>
        )}
      </div>

      {/* Thumbnail strip — smooth scroll, active thumb auto-centered */}
      {images.length > 1 && (
        <div className="flex gap-2 overflow-x-auto scroll-smooth pb-1">
          {images.map((img, i) => (
            <button
              key={img.url}
              onClick={() => goTo(i)}
              className={`relative w-16 h-16 shrink-0 rounded-md overflow-hidden border-2 transition-colors ${
                i === activeIndex ? "border-harbor" : "border-line"
              }`}
            >
              <Image src={img.url} alt={img.altText ?? productName} fill className="object-cover" sizes="64px" />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}