"use client";

import { useEffect, useState, useCallback, useRef } from "react";
import { useParams } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import { useCartStore } from "@/lib/cart-store";
import { useWishlistStore } from "@/lib/wishlist-store";
import { useRecentlyViewedStore } from "@/lib/recently-viewed-store";
import { useAuthStore } from "@/lib/auth-store";
import { formatPrice, resolveMediaUrl, categoryDisplayName } from "@/lib/utils";
import { useLanguage } from "@/lib/language-context";
import { useStorefrontConfig } from "@/lib/storefront-config-context";
import Spinner from "@/components/ui/Spinner";
import GateModal from "@/components/auth/GateModal";
import type { Product, ProductVariant, Color, Size } from "@/types";
import ProductCard from "@/components/product/ProductCard";
import ColorSwatch from "@/components/ui/ColorSwatch";
import BranchAvailability from "@/components/product/BranchAvailability";
import ReservationModal from "@/components/reservation/ReservationModal";

/** Pick SKU for color/size: prefer exact color+size, then color-only, then size-only. */
function findVariantByAttributes(
  variants: ProductVariant[],
  colorId: number | undefined,
  sizeId: number | undefined,
): ProductVariant | undefined {
  if (!variants.length) return undefined;
  if (colorId != null && sizeId != null) {
    const exact = variants.find(
      (v) => v.color?.id === colorId && v.size?.id === sizeId,
    );
    if (exact) return exact;
  }
  if (colorId != null) {
    const byColor = variants.find((v) => v.color?.id === colorId);
    if (byColor) return byColor;
  }
  if (sizeId != null) {
    return variants.find((v) => v.size?.id === sizeId);
  }
  return undefined;
}

export default function ProductDetailPage() {
  const { barcode } = useParams<{ barcode: string }>();
  const { locale, t } = useLanguage();
  const { website: websiteConfig } = useStorefrontConfig();
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedVariant, setSelectedVariant] = useState<
    Product | ProductVariant | null
  >(null);
  const [activeImage, setActiveImage] = useState(0);
  const [quantity, setQuantity] = useState(1);
  const [added, setAdded] = useState(false);
  const [zoomOpen, setZoomOpen] = useState(false);
  const [stickyVisible, setStickyVisible] = useState(false);
  const [relatedProducts, setRelatedProducts] = useState<Product[]>([]);
  const [reservationModal, setReservationModal] = useState<{
    open: boolean;
    branchId: number;
    branchName: string;
  }>({ open: false, branchId: 0, branchName: "" });
  const [showReserveGate, setShowReserveGate] = useState(false);
  const addToCartRef = useRef<HTMLButtonElement>(null);
  const { addItem } = useCartStore();
  const { toggle: toggleWishlist, isWishlisted } = useWishlistStore();
  const recentItems = useRecentlyViewedStore((s) => s.items).filter((i) => i.barcode !== barcode).slice(0, 8);
  const isLoggedIn = useAuthStore((s) => s.isLoggedIn());
  const customer = useAuthStore((s) => s.customer);

  useEffect(() => {
    fetch(`/api/storefront-proxy/products/${barcode}`)
      .then((r) => r.json())
      .then((d) => {
        const p = d.product;
        setProduct(p);
        const list: ProductVariant[] = p.variants ?? [];
        const match = list.find((v) => v.barcode === p.barcode);
        setSelectedVariant(match ?? p);
        if (p?.barcode) {
          useRecentlyViewedStore.getState().add({
            barcode: p.barcode,
            name: p.name ?? "",
            price: Number(p.price) ?? 0,
            image_url: p.image_url ?? p.images?.[0]?.url ?? null,
          });
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));

    fetch(`/api/storefront-proxy/products/${barcode}/related`)
      .then((r) => r.json())
      .then((d) => setRelatedProducts(d.products ?? []))
      .catch(() => {});
  }, [barcode]);

  // Sticky bar: show when the Add to Cart button scrolls out of view
  useEffect(() => {
    const btn = addToCartRef.current;
    if (!btn) return;
    const observer = new IntersectionObserver(
      ([entry]) => setStickyVisible(!entry.isIntersecting),
      { threshold: 0 },
    );
    observer.observe(btn);
    return () => observer.disconnect();
  }, [product]);

  // Close zoom on Escape
  useEffect(() => {
    if (!zoomOpen) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setZoomOpen(false);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [zoomOpen]);

  const handleAddToCart = useCallback(() => {
    if (!selectedVariant) return;
    const v = selectedVariant as any;
    addItem({
      item_id: v.id,
      barcode: v.barcode,
      name: v.name,
      variant_label:
        [v.color?.name, v.size?.name].filter(Boolean).join(" / ") || null,
      image_url: v.images?.[0]?.url ?? null,
      price: Number(v.price),
      quantity,
      available_qty: v.available_qty ?? 0,
      color:
        v.color != null
          ? { name: v.color.name, hex: v.color.hex ?? v.color.code }
          : null,
      size: v.size != null ? { name: v.size.name } : null,
    });
    setAdded(true);
    setTimeout(() => setAdded(false), 2500);
  }, [selectedVariant, quantity, addItem]);

  // Clamp quantity when selected variant or available stock changes (must run before early returns to satisfy rules of hooks)
  const availableQtyForClamp =
    product != null
      ? (selectedVariant as any)?.available_qty ??
        (product as any).available_qty ??
        0
      : 0;
  useEffect(() => {
    setQuantity((q) => {
      if (availableQtyForClamp <= 0) return 0;
      const clamped = Math.min(q, availableQtyForClamp);
      return clamped >= 1 ? clamped : 1;
    });
  }, [selectedVariant, availableQtyForClamp]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <Spinner size="lg" />
      </div>
    );
  }

  if (!product) {
    return (
      <div className="text-center py-24">
        <div className="w-16 h-16 rounded-full bg-gray-100 flex items-center justify-center mx-auto mb-5">
          <svg
            className="w-8 h-8 text-gray-400"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={1.5}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M9.75 9.75l4.5 4.5m0-4.5l-4.5 4.5M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
            />
          </svg>
        </div>
        <p className="text-base font-semibold text-gray-700 mb-1">
          {t.product.productNotFound}
        </p>
        <p className="text-sm text-gray-400 mb-6">
          {t.product.productNotFoundHint}
        </p>
        <Link
          href="/products"
          className="text-sm font-semibold hover:underline"
          style={{ color: "var(--color-primary)" }}
        >
          ← {t.product.backToProducts}
        </Link>
      </div>
    );
  }

  const variantImages = (selectedVariant as ProductVariant)?.images;
  const images =
    Array.isArray(variantImages) && variantImages.length > 0
      ? variantImages
      : product.images ?? [];
  const variants: ProductVariant[] = product.variants ?? [];
  const colors: Color[] = [
    ...new Map(
      variants.filter((v) => v.color).map((v) => [v.color!.id, v.color!]),
    ).values(),
  ];
  const sizes: Size[] = [
    ...new Map(
      variants.filter((v) => v.size).map((v) => [v.size!.id, v.size!]),
    ).values(),
  ];

  const sv = selectedVariant as any;
  const currentPrice = Number(sv?.price ?? product.price);
  const inStock = sv?.in_stock ?? product.in_stock;
  const availableQty = sv?.available_qty ?? product.available_qty ?? 0;
  const wishlisted = isWishlisted(product.barcode);
  const currentImageUrl = resolveMediaUrl(images[activeImage]?.url ?? null);

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Breadcrumb */}
      <nav className="text-xs text-gray-400 mb-8 flex items-center gap-1.5 flex-wrap">
        <Link href="/" className="hover:text-gray-600 transition-colors">
          {t.product.home}
        </Link>
        <svg
          className="w-3 h-3 text-gray-300"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
        </svg>
        <Link
          href="/products"
          className="hover:text-gray-600 transition-colors"
        >
          {t.product.products}
        </Link>
        <svg
          className="w-3 h-3 text-gray-300"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
        </svg>
        <span className="text-gray-600 truncate max-w-[200px]">
          {product.name}
        </span>
      </nav>

      {/* Quick select color/size outside main details */}
      {(colors.length > 0 || sizes.length > 0) && (
        <div className="flex flex-wrap items-center gap-4 mb-6 p-4 bg-gray-50 rounded-2xl border border-gray-100">
          {colors.length > 0 && (
            <div className="flex items-center gap-2">
              <span className="text-xs font-bold text-gray-500 uppercase tracking-wide">
                {t.product.color}:
              </span>
              <div className="flex gap-2 flex-wrap">
                {colors.map((color) => (
                  <button
                    key={color.id}
                    type="button"
                    onClick={() => {
                      const v = findVariantByAttributes(
                        variants,
                        color.id,
                        sv?.size?.id,
                      );
                      if (v) {
                        setSelectedVariant(v);
                        setActiveImage(0);
                      }
                    }}
                    title={color.name}
                    className={`rounded-full border-2 p-0.5 transition-all ${
                      sv?.color?.id === color.id
                        ? "border-gray-900 ring-2 ring-gray-900 ring-offset-1"
                        : "border-gray-200 hover:border-gray-400"
                    }`}
                  >
                    <ColorSwatch name={color.name} hex={color.hex ?? color.code} size="md" />
                  </button>
                ))}
              </div>
            </div>
          )}
          {sizes.length > 0 && (
            <div className="flex items-center gap-2">
              <span className="text-xs font-bold text-gray-500 uppercase tracking-wide">
                {t.product.size}:
              </span>
              <div className="flex gap-2 flex-wrap">
                {sizes.map((size) => {
                  const v = findVariantByAttributes(
                    variants,
                    sv?.color?.id,
                    size.id,
                  );
                  const available = v?.in_stock ?? false;
                  return (
                    <button
                      key={size.id}
                      type="button"
                      onClick={() => {
                        if (v && available) {
                          setSelectedVariant(v);
                          setActiveImage(0);
                        }
                      }}
                      disabled={!available}
                      className={`min-w-[2.5rem] py-1.5 px-2 rounded-lg text-sm font-semibold border-2 transition-all ${
                        sv?.size?.id === size.id
                          ? "border-gray-900 bg-gray-900 text-white"
                          : available
                          ? "border-gray-200 hover:border-gray-400 text-gray-700"
                          : "border-gray-100 text-gray-300 cursor-not-allowed bg-gray-50 line-through"
                      }`}
                    >
                      {size.name}
                    </button>
                  );
                })}
              </div>
            </div>
          )}
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-10 lg:gap-16">
        {/* ── Images ── */}
        <div>
          <div
            className="aspect-square bg-gray-50 rounded-2xl overflow-hidden relative mb-3 cursor-zoom-in group shadow-sm"
            onClick={() => currentImageUrl && setZoomOpen(true)}
          >
            {currentImageUrl ? (
              <>
                <Image
                  src={currentImageUrl}
                  alt={product.name}
                  fill
                  className="object-cover transition-transform duration-400 group-hover:scale-105"
                  sizes="(max-width: 1024px) 100vw, 50vw"
                  priority
                />
                <div className="absolute bottom-3 right-3 bg-black/35 text-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition-opacity backdrop-blur-sm">
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M21 21l-4.35-4.35M17 11A6 6 0 115 11a6 6 0 0112 0zm-2 0a4 4 0 10-8 0 4 4 0 008 0z"
                    />
                  </svg>
                </div>
              </>
            ) : (
              <div className="w-full h-full flex flex-col items-center justify-center gap-3 bg-gradient-to-br from-gray-100 to-gray-50 select-none">
                <svg
                  className="w-20 h-20 text-gray-300"
                  viewBox="0 0 64 64"
                  fill="none"
                  aria-hidden="true"
                >
                  <path
                    d="M32 10 C32 10 28 14 28 17 C28 19.2 29.8 21 32 21 C34.2 21 36 19.2 36 17 C36 14 32 10 32 10Z"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    fill="none"
                  />
                  <path
                    d="M32 21 L32 25 L10 40 C8 41.2 9 44 11.5 44 L52.5 44 C55 44 56 41.2 54 40 L32 25Z"
                    stroke="currentColor"
                    strokeWidth="1.5"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    fill="none"
                  />
                </svg>
                <span className="text-xs font-medium text-gray-300 uppercase tracking-widest">
                  {t.product.noImageAvailable}
                </span>
              </div>
            )}
          </div>

          {/* Thumbnails */}
          {images.length > 1 && (
            <div className="flex gap-2 overflow-x-auto pb-1 scrollbar-hide">
              {images.map((img: any, i: number) => (
                <button
                  key={i}
                  onClick={() => setActiveImage(i)}
                  className={`w-16 h-16 flex-shrink-0 rounded-xl overflow-hidden relative border-2 transition-all ${
                    activeImage === i
                      ? "border-gray-900 shadow-md"
                      : "border-transparent hover:border-gray-300"
                  }`}
                >
                  <Image
                    src={resolveMediaUrl(img.thumb || img.url) ?? img.url}
                    alt={`${product.name} ${i + 1}`}
                    fill
                    className="object-cover"
                    sizes="64px"
                  />
                </button>
              ))}
            </div>
          )}
        </div>

        {/* ── Details ── */}
        <div className="flex flex-col">
          {product.category && (
            <Link
              href={`/categories/${product.category.id}`}
              className="text-[11px] font-bold uppercase tracking-[0.15em] mb-2 hover:opacity-75 transition-opacity"
              style={{ color: "var(--color-primary)" }}
              dir={locale?.startsWith("ar") ? "rtl" : undefined}
            >
              {categoryDisplayName(product.category, locale)}
            </Link>
          )}

          <div className="flex items-start justify-between gap-3 mb-1">
            <h1 className="text-2xl md:text-3xl font-bold text-gray-900 leading-tight flex-1">
              {product.name}
            </h1>
            {/* Wishlist button */}
            <button
              onClick={() =>
                toggleWishlist({
                  barcode: product.barcode,
                  name: product.name,
                  price: currentPrice,
                  image_url: product.image_url ?? null,
                })
              }
              className={`flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full border transition-all mt-0.5 ${
                wishlisted
                  ? "border-red-200 bg-red-50"
                  : "border-gray-200 hover:border-red-200 hover:bg-red-50"
              }`}
              aria-label={
                wishlisted ? "Remove from wishlist" : "Add to wishlist"
              }
            >
              <svg
                className={`h-5 w-5 transition-colors ${
                  wishlisted
                    ? "fill-red-500 text-red-500"
                    : "fill-none text-gray-400"
                }`}
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.75}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
                />
              </svg>
            </button>
          </div>

          {product.brand && (
            <p className="text-sm text-gray-400 mb-4">{product.brand.name}</p>
          )}

          <div className="flex items-baseline gap-2 mb-7">
            <p
              className="text-3xl font-bold"
              style={{ color: "var(--color-primary)" }}
            >
              {formatPrice(currentPrice)}
            </p>
          </div>

          {/* Color selector — actual color swatch, name on hover */}
          {colors.length > 0 && (
            <div className="mb-6">
              <p className="text-xs font-bold text-gray-500 uppercase tracking-[0.12em] mb-3">
                {t.product.color}
              </p>
              <div className="flex gap-2 flex-wrap items-center">
                {colors.map((color) => (
                  <button
                    key={color.id}
                    type="button"
                    onClick={() => {
                      const v = findVariantByAttributes(
                        variants,
                        color.id,
                        sv?.size?.id,
                      );
                      if (v) {
                        setSelectedVariant(v);
                        setActiveImage(0);
                      }
                    }}
                    title={color.name}
                    className={`rounded-full border-2 p-0.5 transition-all ${
                      sv?.color?.id === color.id
                        ? "border-gray-900 ring-2 ring-gray-900 ring-offset-2"
                        : "border-gray-200 hover:border-gray-400"
                    }`}
                  >
                    <ColorSwatch
                      name={color.name}
                      hex={color.hex ?? color.code}
                      size="lg"
                    />
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Size selector */}
          {sizes.length > 0 && (
            <div className="mb-6">
              <p className="text-xs font-bold text-gray-500 uppercase tracking-[0.12em] mb-3">
                {t.product.size}
              </p>
              <div className="flex gap-2 flex-wrap">
                {sizes.map((size) => {
                  const v = findVariantByAttributes(
                    variants,
                    sv?.color?.id,
                    size.id,
                  );
                  const available = v?.in_stock ?? false;
                  return (
                    <button
                      key={size.id}
                      onClick={() => {
                        if (v && available) {
                          setSelectedVariant(v);
                          setActiveImage(0);
                        }
                      }}
                      disabled={!available}
                      className={`w-12 h-12 flex items-center justify-center rounded-xl text-sm border-2 font-semibold transition-all ${
                        sv?.size?.id === size.id
                          ? "border-gray-900 bg-gray-900 text-white"
                          : available
                          ? "border-gray-200 hover:border-gray-400 text-gray-700"
                          : "border-gray-100 text-gray-300 cursor-not-allowed line-through bg-gray-50"
                      }`}
                    >
                      {size.name}
                    </button>
                  );
                })}
              </div>
            </div>
          )}

          {/* Quantity & stock */}
          <div className="mb-7">
            <p className="text-xs font-bold text-gray-500 uppercase tracking-[0.12em] mb-3">
              {t.product.quantity}
            </p>
            <div className="flex flex-wrap items-center gap-3">
              <div className="flex items-center border border-gray-200 rounded-xl overflow-hidden">
                <button
                  onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                  disabled={quantity <= 1}
                  className="w-11 h-11 flex items-center justify-center text-gray-500 hover:bg-gray-50 transition-colors text-lg font-light disabled:opacity-30"
                >
                  −
                </button>
                <span className="text-base font-semibold w-10 text-center border-x border-gray-200">
                  {quantity}
                </span>
                <button
                  onClick={() =>
                    setQuantity((q) => Math.min(availableQty, q + 1))
                  }
                  disabled={quantity >= availableQty}
                  className="w-11 h-11 flex items-center justify-center text-gray-500 hover:bg-gray-50 transition-colors text-lg font-light disabled:opacity-30"
                >
                  +
                </button>
              </div>
              <span
                className={`text-sm font-medium ${
                  inStock
                    ? availableQty <= 5
                      ? "text-amber-600"
                      : "text-gray-600"
                    : "text-red-600"
                }`}
              >
                {inStock
                  ? t.product.inStockCount.replace(
                      "{{count}}",
                      String(availableQty),
                    )
                  : t.product.outOfStock}
              </span>
              {availableQty > 0 && availableQty <= 5 && (
                <span className="text-xs font-medium text-amber-600 bg-amber-50 px-2.5 py-1 rounded-lg">
                  {t.product.onlyLeft.replace(
                    "{{count}}",
                    String(availableQty),
                  )}
                </span>
              )}
            </div>
          </div>

          {/* Out of stock warning */}
          {!inStock && (
            <div className="mb-5 p-4 bg-gray-50 border border-gray-200 rounded-xl flex items-center gap-3">
              <svg
                className="w-5 h-5 text-gray-400 flex-shrink-0"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={1.75}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"
                />
              </svg>
              <p className="text-sm text-gray-600 font-medium">
                {t.product.outOfStockMessage}
              </p>
            </div>
          )}

          {/* Add to cart */}
          <button
            ref={addToCartRef}
            onClick={handleAddToCart}
            disabled={!inStock || quantity < 1}
            className="btn-primary w-full py-4 rounded-2xl text-sm font-bold shadow-md mb-3 flex items-center justify-center gap-2"
          >
            {added ? (
              <>
                <svg
                  className="w-5 h-5"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2.5}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M5 13l4 4L19 7"
                  />
                </svg>
                {t.product.addedToCart}
              </>
            ) : (
              <>
                <svg
                  className="w-5 h-5"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={1.75}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"
                  />
                </svg>
                {t.product.addToCart}
              </>
            )}
          </button>

          <Link
            href="/cart"
            className="block text-center text-sm font-medium text-gray-400 hover:text-gray-700 transition-colors mb-7"
          >
            {t.product.viewCart}
          </Link>

          {/* Trust badges */}
          <div className="grid grid-cols-3 gap-3 py-5 border-y border-gray-100 mb-7">
            {[
              {
                icon: "M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4",
                label: t.product.freeReturns,
              },
              {
                icon: "M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z",
                label: t.product.securePayment,
              },
              {
                icon: "M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z",
                label: t.product.support247,
              },
            ].map(({ icon, label }) => (
              <div
                key={label}
                className="flex flex-col items-center gap-1.5 text-center"
              >
                <div className="w-9 h-9 rounded-full bg-gray-50 flex items-center justify-center">
                  <svg
                    className="w-4.5 h-4.5 text-gray-500"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={1.5}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d={icon}
                    />
                  </svg>
                </div>
                <p className="text-[10px] font-semibold text-gray-500 leading-tight">
                  {label}
                </p>
              </div>
            ))}
          </div>

          {/* Description */}
          {product.description && (
            <div className="mb-7">
              <h3 className="text-xs font-bold text-gray-500 uppercase tracking-[0.12em] mb-3">
                {t.product.description}
              </h3>
              <p className="text-sm text-gray-600 leading-relaxed">
                {product.description}
              </p>
            </div>
          )}

          {/* Branch Availability */}
          {websiteConfig.enable_branch_availability &&
            product.branch_availability &&
            product.branch_availability.length > 0 && (
              <BranchAvailability
                branches={product.branch_availability}
                enableReservations={!!websiteConfig.enable_reservations}
                selectedVariant={
                  selectedVariant !== product
                    ? (selectedVariant as ProductVariant)
                    : null
                }
                onReserve={(branchId, branchName) =>
                  setReservationModal({ open: true, branchId, branchName })
                }
              />
            )}
        </div>
      </div>

      <GateModal
        open={showReserveGate}
        type="reserve"
        onClose={() => setShowReserveGate(false)}
      />

      {/* Reservation Modal */}
      {reservationModal.open &&
        product &&
        (() => {
          const branch = product.branch_availability?.find(
            (b: { branch_id: number }) =>
              b.branch_id === reservationModal.branchId,
          );
          const variantId =
            (selectedVariant as { id?: number })?.id ?? product.id;
          const variantStock = (
            branch as {
              variants?: { item_id: number; available_qty: number }[];
            }
          )?.variants?.find((v) => v.item_id === variantId);
          const maxQuantity = Math.max(1, variantStock?.available_qty ?? 99);
          return (
            <ReservationModal
              item={selectedVariant ?? product}
              branchId={reservationModal.branchId}
              branchName={reservationModal.branchName}
              maxQuantity={maxQuantity}
              reservationTtlHours={websiteConfig.reservation_ttl_hours ?? 2}
              onClose={() =>
                setReservationModal({
                  open: false,
                  branchId: 0,
                  branchName: "",
                })
              }
              initialName={customer?.name ?? ""}
              initialPhone={customer?.phone ?? ""}
            />
          );
        })()}

      {/* ── Image Zoom Lightbox ── */}
      {zoomOpen && currentImageUrl && (
        <div
          className="fixed inset-0 z-50 bg-black/92 flex items-center justify-center p-4"
          onClick={() => setZoomOpen(false)}
        >
          <button
            className="absolute top-4 right-4 text-white/70 hover:text-white p-2.5 rounded-full bg-white/10 hover:bg-white/20 transition-colors backdrop-blur-sm"
            onClick={() => setZoomOpen(false)}
            aria-label="Close"
          >
            <svg
              className="h-5 w-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M6 18L18 6M6 6l12 12"
              />
            </svg>
          </button>

          {/* Prev / Next */}
          {images.length > 1 && activeImage > 0 && (
            <button
              className="absolute left-4 top-1/2 -translate-y-1/2 text-white/70 hover:text-white p-2.5 rounded-full bg-white/10 hover:bg-white/20 transition-colors backdrop-blur-sm"
              onClick={(e) => {
                e.stopPropagation();
                setActiveImage((i) => i - 1);
              }}
            >
              <svg
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15 19l-7-7 7-7"
                />
              </svg>
            </button>
          )}
          {images.length > 1 && activeImage < images.length - 1 && (
            <button
              className="absolute right-4 top-1/2 -translate-y-1/2 text-white/70 hover:text-white p-2.5 rounded-full bg-white/10 hover:bg-white/20 transition-colors backdrop-blur-sm"
              onClick={(e) => {
                e.stopPropagation();
                setActiveImage((i) => i + 1);
              }}
            >
              <svg
                className="h-5 w-5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M9 5l7 7-7 7"
                />
              </svg>
            </button>
          )}

          <div
            className="relative max-w-4xl max-h-[90vh] w-full h-full"
            onClick={(e) => e.stopPropagation()}
          >
            <Image
              src={currentImageUrl}
              alt={product.name}
              fill
              className="object-contain"
              sizes="100vw"
              priority
            />
          </div>

          {/* Dot indicators */}
          {images.length > 1 && (
            <div className="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-1.5">
              {images.map((_: any, i: number) => (
                <button
                  key={i}
                  onClick={(e) => {
                    e.stopPropagation();
                    setActiveImage(i);
                  }}
                  className={`h-1.5 rounded-full transition-all ${
                    i === activeImage ? "w-5 bg-white" : "w-1.5 bg-white/40"
                  }`}
                />
              ))}
            </div>
          )}
        </div>
      )}

      {/* ── Recently viewed ── */}
      {recentItems.length > 0 && (
          <section className="mt-20 pt-12 border-t border-gray-100">
            <h2 className="text-xl font-bold text-gray-900 mb-6">{t.product.recentlyViewed}</h2>
            <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-hide md:grid md:grid-cols-4 lg:grid-cols-6 md:overflow-visible">
              {recentItems.map((i) => (
                <Link
                  key={i.barcode}
                  href={`/products/${i.barcode}`}
                  className="flex-shrink-0 w-[140px] sm:w-[160px] rounded-xl border border-gray-100 overflow-hidden bg-white hover:shadow-md transition-shadow"
                >
                  <div className="aspect-square bg-gray-50 relative">
                    {i.image_url ? (
                      <Image src={resolveMediaUrl(i.image_url) ?? i.image_url} alt={i.name} fill className="object-cover" sizes="160px" />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-gray-300">
                        <svg className="w-10 h-10" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14" />
                        </svg>
                      </div>
                    )}
                  </div>
                  <div className="p-2.5">
                    <p className="text-sm font-medium text-gray-900 truncate">{i.name}</p>
                    <p className="text-sm font-bold mt-0.5" style={{ color: "var(--color-primary)" }}>{formatPrice(i.price)}</p>
                  </div>
                </Link>
              ))}
            </div>
          </section>
      )}

      {/* ── Related Products ── */}
      {relatedProducts.length > 0 && (
        <section className="mt-20 pt-12 border-t border-gray-100">
          <div className="flex items-center gap-4 mb-8">
            <div>
              <h2 className="text-xl font-bold text-gray-900">
                {t.product.relatedProducts}
              </h2>
              <div className="divider-primary mt-2" />
            </div>
          </div>
          <div className="flex gap-4 overflow-x-auto pb-2 scrollbar-hide md:grid md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-6 md:overflow-visible md:pb-0">
            {relatedProducts.map((p) => (
              <div
                key={p.barcode}
                className="flex-shrink-0 w-[160px] sm:w-[180px] md:w-auto"
              >
                <ProductCard product={p} />
              </div>
            ))}
          </div>
        </section>
      )}

      {/* ── Sticky Add-to-Cart Bar ── */}
      {stickyVisible && inStock && (
        <div className="fixed bottom-0 left-0 right-0 z-40 bg-white/95 backdrop-blur-nav border-t border-gray-200 shadow-xl px-4 py-3 flex items-center gap-4">
          {resolveMediaUrl(product.image_url) && (
            <div className="w-11 h-11 rounded-xl overflow-hidden relative flex-shrink-0 border border-gray-100">
              <Image
                src={resolveMediaUrl(product.image_url)!}
                alt={product.name}
                fill
                className="object-cover"
                sizes="44px"
              />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p className="text-sm font-semibold text-gray-900 truncate">
              {product.name}
            </p>
            <p
              className="text-sm font-bold"
              style={{ color: "var(--color-primary)" }}
            >
              {formatPrice(currentPrice)}
            </p>
          </div>
          <button
            onClick={handleAddToCart}
            disabled={quantity < 1}
            className="btn-primary px-6 py-2.5 rounded-xl text-sm font-bold shadow flex-shrink-0"
          >
            {added ? `✓ ${t.product.addedToCart}` : t.product.addToCart}
          </button>
        </div>
      )}
    </div>
  );
}
