"use client";

import { useState } from "react";
import Image from "next/image";
import { cn } from "@/lib/utils";

export function ProductGallery({
  images,
  name,
  zoomLabel,
}: {
  images: { id: string; url: string; alt: string }[];
  name: string;
  zoomLabel: string;
}) {
  const [active, setActive] = useState(0);
  const [zoomed, setZoomed] = useState(false);
  const [origin, setOrigin] = useState("50% 50%");
  const current = images[active];

  if (!current) {
    return <div className="aspect-[3/4] w-full bg-sand/20" />;
  }

  return (
    <div className="flex min-w-0 flex-col gap-4 md:flex-row-reverse md:gap-5">
      <div
        className="relative aspect-[3/4] min-w-0 flex-1 cursor-zoom-in overflow-hidden bg-sand/20"
        onMouseEnter={() => setZoomed(true)}
        onMouseLeave={() => setZoomed(false)}
        onMouseMove={(event) => {
          const rect = event.currentTarget.getBoundingClientRect();
          const x = ((event.clientX - rect.left) / rect.width) * 100;
          const y = ((event.clientY - rect.top) / rect.height) * 100;
          setOrigin(`${x}% ${y}%`);
        }}
        aria-label={zoomLabel}
      >
        <Image
          src={current.url}
          alt={current.alt || name}
          fill
          priority
          sizes="(max-width: 768px) 100vw, 55vw"
          className={cn(
            "object-cover transition-transform duration-500 ease-out",
            zoomed ? "scale-[1.65]" : "scale-100",
          )}
          style={{ transformOrigin: origin }}
        />
        <span className="pointer-events-none absolute bottom-4 right-4 bg-cream/80 px-2.5 py-1 text-[12px] uppercase tracking-[0.14em] text-charcoal/60 backdrop-blur">
          {zoomLabel}
        </span>
      </div>

      {images.length > 1 && (
        <div className="flex gap-3 md:w-20 md:flex-col">
          {images.map((image, index) => (
            <button
              key={image.id}
              type="button"
              onClick={() => setActive(index)}
              className={cn(
                "relative aspect-[3/4] w-16 shrink-0 overflow-hidden border bg-sand/20 transition-opacity md:w-full",
                index === active ? "border-charcoal opacity-100" : "border-transparent opacity-60 hover:opacity-100",
              )}
              aria-label={`${name} ${index + 1}`}
            >
              <Image src={image.url} alt={image.alt || name} fill sizes="80px" className="object-cover" />
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
