"use client";

import { useRef, useState } from "react";
import Image from "next/image";

const SWIPE_THRESHOLD_PX = 40;

/**
 * Main image + thumbnail strip, swappable on click. `image` is always
 * slide zero, `gallery` (Products.gallery, optional/empty for most
 * products) fills in the rest. Renders as a single plain image with no
 * thumbnail row at all when `gallery` is empty — the common case, and
 * exactly today's pre-gallery appearance, no behavior change for any
 * product that hasn't opted in. Plain divs/buttons, no carousel package —
 * same "no charting/UI-library dependency for a simple case" reasoning as
 * OrderQueueWidget.tsx's own OrderSparkline.
 */
export function ProductGallery({
  image,
  gallery,
  alt,
  badge,
}: {
  image: string;
  gallery: string[];
  alt: string;
  /** Optional overlay (e.g. a discount/Ausverkauft/Neu pill) absolutely
   * positioned over the main image — top-3.5/left-3.5, same corner every
   * other badge on the site anchors to. Not part of this component's own
   * data; the caller decides what, if anything, to show. */
  badge?: React.ReactNode;
}) {
  const slides = [image, ...gallery];
  const [current, setCurrent] = useState(0);
  const touchStartX = useRef<number | null>(null);

  if (slides.length <= 1) {
    return (
      <div className="relative w-full aspect-[4/3.1] overflow-hidden rounded-md border border-border bg-bg-base">
        <Image src={image} alt={alt} fill sizes="(min-width: 860px) 55vw, 100vw" className="object-cover" />
        {badge && <div className="absolute top-3.5 left-3.5">{badge}</div>}
      </div>
    );
  }

  function next() {
    setCurrent((c) => (c + 1) % slides.length);
  }
  function prev() {
    setCurrent((c) => (c - 1 + slides.length) % slides.length);
  }

  function handleTouchStart(e: React.TouchEvent) {
    touchStartX.current = e.touches[0].clientX;
  }
  function handleTouchEnd(e: React.TouchEvent) {
    if (touchStartX.current === null) return;
    const delta = e.changedTouches[0].clientX - touchStartX.current;
    touchStartX.current = null;
    if (delta <= -SWIPE_THRESHOLD_PX) next();
    else if (delta >= SWIPE_THRESHOLD_PX) prev();
  }

  return (
    <div className="flex flex-col gap-3.5 w-full">
      <div
        className="relative w-full aspect-[4/3.1] overflow-hidden rounded-md border border-border bg-bg-base touch-pan-y"
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
      >
        <Image src={slides[current]} alt={alt} fill sizes="(min-width: 860px) 55vw, 100vw" className="object-cover" />
        {badge && <div className="absolute top-3.5 left-3.5">{badge}</div>}
        <button
          type="button"
          onClick={prev}
          aria-label="Vorheriges Bild"
          className="absolute left-3.5 top-1/2 -translate-y-1/2 flex h-9 w-9 items-center justify-center rounded-full bg-bg-base/90 text-text-primary shadow-md hover:bg-bg-base transition-colors"
        >
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" aria-hidden="true">
            <path d="M15 19l-7-7 7-7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        <button
          type="button"
          onClick={next}
          aria-label="Nächstes Bild"
          className="absolute right-3.5 top-1/2 -translate-y-1/2 flex h-9 w-9 items-center justify-center rounded-full bg-bg-base/90 text-text-primary shadow-md hover:bg-bg-base transition-colors"
        >
          <svg viewBox="0 0 24 24" width="18" height="18" fill="none" aria-hidden="true">
            <path d="M9 5l7 7-7 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </button>
        <span className="absolute bottom-3.5 right-3.5 rounded-full bg-text-primary/60 px-2.5 py-1 text-label font-semibold text-white tabular-nums">
          {current + 1} / {slides.length}
        </span>
      </div>
      <div className="flex gap-2.5">
        {slides.map((src, i) => (
          <button
            key={src + i}
            type="button"
            onClick={() => setCurrent(i)}
            aria-label={`Bild ${i + 1} anzeigen`}
            aria-current={i === current}
            className={`relative h-[4.75rem] w-[4.75rem] shrink-0 overflow-hidden rounded-sm border-2 transition-opacity ${
              i === current ? "border-brand opacity-100" : "border-transparent opacity-70 hover:opacity-100"
            }`}
          >
            <Image src={src} alt="" fill sizes="76px" className="object-cover" />
          </button>
        ))}
      </div>
    </div>
  );
}
