import React, { useState, useEffect, useRef } from "react";
import Head from "next/head";
import Link from "next/link";
import Script from "next/script";
import toast from "react-hot-toast";
import { useSession } from "next-auth/react";
import { useCart } from "../context/CartContext";
import { useCheckout } from "../context/CheckoutContext";
import BundleImageGrid from "../components/BundleImageGrid";
import PickupPointSuggestions from "../components/PickupPointSuggestions";

declare global {
  interface Window {
    Packeta?: {
      Widget?: {
        pick: (
          apiKey: string,
          callback: (point: any) => void,
          options: any,
        ) => void;
      };
    };
  }
}

const Cart: React.FC = () => {
  const { data: session } = useSession();
  const { items, removeItem, updateQuantity, getTotalPrice, clearCart, refreshCart } =
    useCart();
  const {
    selectedShipping,
    setSelectedShipping,
    contactInfo,
    setContactInfo,
    shippingOptions,
    pickupPoints,
    selectedPickupPoint,
    setSelectedPickupPoint,
    packetaErrorMessages,
    getPacketaConfig,
  } = useCheckout();
  const [isClient, setIsClient] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [stockError, setStockError] = useState<{ message: string; variantId?: number } | null>(null);
  const [packetaLoaded, setPacketaLoaded] = useState(false);
  const [isBalikovnaModalOpen, setIsBalikovnaModalOpen] = useState(false);
  const [isGlsModalOpen, setIsGlsModalOpen] = useState(false);
  const [isDpdModalOpen, setIsDpdModalOpen] = useState(false);
  const [voucherCode, setVoucherCode] = useState("");
  const [voucherDiscount, setVoucherDiscount] = useState(0);
  const [voucherError, setVoucherError] = useState("");
  const [discountType, setDiscountType] = useState<"fixed" | "percent">(
    "fixed",
  );
  const [availableCoupons, setAvailableCoupons] = useState<any[]>([]);
  const [loadingCoupons, setLoadingCoupons] = useState(false);
  const [isGiftWrapped, setIsGiftWrapped] = useState(false);
  const GIFT_WRAP_PRICE = 99;
  const isSubmittingRef = useRef(false);
  const stockErrorCloseRef = useRef<HTMLButtonElement>(null);
  const shippingRef = useRef<HTMLDivElement>(null);
  const contactRef = useRef<HTMLDivElement>(null);
  const packetaApiKey = process.env.NEXT_PUBLIC_PACKETA_API_KEY;

  const hasOnlyVouchers = () =>
    items.every((item) => item.productType === "voucher");
  const hasPerfume = () => items.some((item) => item.productType !== "voucher");

  useEffect(() => {
    setIsClient(true);
  }, []);

  useEffect(() => {
    if (!stockError) return;

    const previousOverflow = document.body.style.overflow;
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setStockError(null);
    };

    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", handleKeyDown);
    stockErrorCloseRef.current?.focus();

    return () => {
      document.body.style.overflow = previousOverflow;
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [stockError]);

  // Load available coupons for logged-in user
  useEffect(() => {
    if (!isClient || !session?.user?.email) {
      setAvailableCoupons([]);
      return;
    }

    const loadAvailableCoupons = async () => {
      setLoadingCoupons(true);
      try {
        const response = await fetch("/api/user/available-coupons");
        if (response.ok) {
          const data = await response.json();
          setAvailableCoupons(data.coupons || []);
        } else {
          setAvailableCoupons([]);
        }
      } catch (error) {
        setAvailableCoupons([]);
      } finally {
        setLoadingCoupons(false);
      }
    };

    loadAvailableCoupons();
  }, [isClient, session?.user?.email]);

  useEffect(() => {
    if (items.length > 0 && hasOnlyVouchers()) {
      setSelectedShipping(null);
      setSelectedPickupPoint(null);
      setVoucherCode("");
      setVoucherDiscount(0);
      setVoucherError("");
      setIsGiftWrapped(false);
    }
  }, [items, setSelectedShipping, setSelectedPickupPoint]);

  useEffect(() => {
    if (!isClient || !packetaLoaded || !selectedShipping) return;

    const shippingOpt = shippingOptions.find(
      (opt) => opt.id === selectedShipping,
    );
    if (
      shippingOpt?.requiresLocation &&
      shippingOpt?.carrier === "packeta" &&
      !selectedPickupPoint &&
      !(contactInfo.street?.trim() && contactInfo.city?.trim() && contactInfo.zip?.trim())
    ) {
      const timer = setTimeout(() => {
        if (window.Packeta?.Widget?.pick && packetaApiKey) {
          const config = getPacketaConfig(shippingOpt?.type);
          window.Packeta.Widget.pick(
            packetaApiKey,
            (point: any) => {
              if (point) {
                const selectedPoint = {
                  id: point.id,
                  place: point.place || "Unknown",
                  name: point.name || "Unknown",
                  city: point.city || "Unknown",
                  street: point.street || "Unknown",
                  zip: point.zip || "",
                  country: point.country || "CZ",
                  pickupPointType: point.pickupPointType,
                  directions: point.directions || "",
                };
                setSelectedPickupPoint(selectedPoint);
              }
            },
            config,
          );
        }
      }, 300);
      return () => clearTimeout(timer);
    }
  }, [
    selectedShipping,
    packetaLoaded,
    shippingOptions,
    isClient,
    packetaApiKey,
    setSelectedPickupPoint,
    getPacketaConfig,
    pickupPoints,
    selectedPickupPoint,
    contactInfo.street,
    contactInfo.city,
    contactInfo.zip,
  ]);

  const hasSearchAddress = Boolean(
    contactInfo.street?.trim() &&
      contactInfo.city?.trim() &&
      contactInfo.zip?.trim(),
  );

  // Auto-open Balíkovna modal when Balíkovna shipping is selected
  useEffect(() => {
    if (!isClient || !selectedShipping || hasSearchAddress) return;

    const shippingOpt = shippingOptions.find(
      (opt) => opt.id === selectedShipping,
    );
    if (
      shippingOpt?.requiresLocation &&
      shippingOpt?.carrier === "czech_post" &&
      !selectedPickupPoint
    ) {
      setIsBalikovnaModalOpen(true);
    }
  }, [selectedShipping, shippingOptions, isClient, selectedPickupPoint, hasSearchAddress]);

  // Auto-open GLS modal when GLS pickup is selected
  useEffect(() => {
    if (!isClient || !selectedShipping || hasSearchAddress) return;

    const shippingOpt = shippingOptions.find(
      (opt) => opt.id === selectedShipping,
    );
    if (
      shippingOpt?.requiresLocation &&
      shippingOpt?.carrier === "gls" &&
      !selectedPickupPoint
    ) {
      setIsGlsModalOpen(true);
    }
  }, [selectedShipping, shippingOptions, isClient, selectedPickupPoint, hasSearchAddress]);

  // Auto-open DPD modal when DPD pickup is selected
  useEffect(() => {
    if (!isClient || !selectedShipping || hasSearchAddress) return;

    const shippingOpt = shippingOptions.find(
      (opt) => opt.id === selectedShipping,
    );
    if (
      shippingOpt?.requiresLocation &&
      shippingOpt?.carrier === "dpd" &&
      !selectedPickupPoint
    ) {
      setIsDpdModalOpen(true);
    }
  }, [selectedShipping, shippingOptions, isClient, selectedPickupPoint, hasSearchAddress]);

  // Listen for Balíkovna selection event
  useEffect(() => {
    if (!isClient) return;

    const handleBalikovnaSelection = (event: MessageEvent) => {
      try {
        if (
          event.data &&
          event.data.message === "pickerResult" &&
          event.data.point
        ) {
          const point = event.data.point;

          const selectedPoint = {
            id: point.id?.toString() || "",
            name: point.name || "Balíkovna",
            city: point.municipality_name || "",
            street: point.address || "",
            zip: point.zip || "",
            country: "CZ",
            pickupPointType: "Balíkovna",
            place: point.name || "Balíkovna",
            code: point.id?.toString() || "",
            rawDetail: point,
          };
          setSelectedPickupPoint(selectedPoint);
          setIsBalikovnaModalOpen(false);
        }
      } catch (err) {
        // Error in handleBalikovnaSelection
      }
    };

    window.addEventListener("message", handleBalikovnaSelection);

    return () => {
      window.removeEventListener("message", handleBalikovnaSelection);
    };
  }, [isClient, setSelectedPickupPoint]);

  // Listen for GLS pickup point selection
  useEffect(() => {
    if (!isClient) return;

    const handleGlsSelection = (event: MessageEvent) => {
      try {
        const origin = String(event.origin || "");
        if (
          origin &&
          !origin.includes("gls-czech") &&
          !origin.includes("ps-maps.gls")
        ) {
          return;
        }

        let data: any = event.data;
        if (typeof data === "string") {
          try {
            data = JSON.parse(data);
          } catch {
            return;
          }
        }

        const detail =
          data?.parcelshop?.detail ||
          data?.detail ||
          (data?.pclshopid ? data : null);

        const id = detail?.pclshopid || detail?.id;
        if (!id) return;

        setSelectedPickupPoint({
          id: String(id),
          name: detail.name || "GLS výdejní místo",
          city: detail.city || "",
          street: detail.address || detail.street || "",
          zip: detail.zipcode || detail.zip || "",
          country: detail.ctrcode || "CZ",
          pickupPointType: detail.isparcellocker === "1" || detail.isparcellocker === 1
            ? "GLS Parcel Box"
            : "GLS Parcel Shop",
          place: detail.name || "GLS",
          code: String(id),
          rawDetail: detail,
        });
        setIsGlsModalOpen(false);
      } catch (err) {
        // Error in handleGlsSelection
      }
    };

    window.addEventListener("message", handleGlsSelection);
    return () => {
      window.removeEventListener("message", handleGlsSelection);
    };
  }, [isClient, setSelectedPickupPoint]);

  // Listen for DPD pickup point selection
  useEffect(() => {
    if (!isClient) return;

    const handleDpdSelection = (event: MessageEvent) => {
      try {
        const widget = event.data?.dpdWidget;
        if (!widget) return;

        if (widget.message === "widgetClose") {
          setIsDpdModalOpen(false);
          return;
        }

        const result = String(widget.pickupPointResult || "");
        const parts = result
          .split(/[|,]/)
          .map((part: string) => part.trim())
          .filter(Boolean);

        const id =
          widget.id ||
          widget.parcelShopId ||
          widget.pickupPointId ||
          parts[0];
        if (!id) return;

        const name =
          widget.name ||
          widget.company ||
          widget.parcelShopName ||
          parts[1] ||
          "DPD Pickup";
        const street =
          widget.street ||
          widget.address ||
          widget.streetAddress ||
          parts[2] ||
          "";
        const city = widget.city || parts[parts.length - 1] || "";
        const zip =
          widget.zip ||
          widget.zipCode ||
          widget.postcode ||
          widget.postalCode ||
          "";

        setSelectedPickupPoint({
          id: String(id),
          name,
          city,
          street,
          zip,
          country: widget.country || "CZ",
          pickupPointType: widget.type || "DPD Pickup",
          place: name,
          code: String(id),
          rawDetail: widget,
        });
        setIsDpdModalOpen(false);
      } catch (err) {
        // Error in handleDpdSelection
      }
    };

    window.addEventListener("message", handleDpdSelection);
    return () => {
      window.removeEventListener("message", handleDpdSelection);
    };
  }, [isClient, setSelectedPickupPoint]);

  if (!isClient) {
    return (
      <>
        <Head>
          <title>Košík | Vystříkejto.cz</title>
          <meta name="robots" content="noindex,nofollow,noarchive" />
        </Head>
        <div className="min-h-screen bg-luxury-dark" />
      </>
    );
  }

  const totalPrice = getTotalPrice();
  const selectedShippingOption = shippingOptions.find(
    (opt) => opt.id === selectedShipping,
  );
  const shippingPrice =
    totalPrice >= 999 ? 0 : selectedShippingOption?.price || 0;
  const giftWrapPrice = isGiftWrapped ? GIFT_WRAP_PRICE : 0;
  const finalTotal = totalPrice + shippingPrice + giftWrapPrice;
  const discountBase = totalPrice;
  const actualDiscount = Math.min(voucherDiscount, discountBase);

  // Handle Packeta widget selection
  const handlePacketaSelection = (point: any) => {
    if (point) {
      const selectedPoint = {
        id: point.id,
        place: point.place || "Unknown",
        name: point.name || "Unknown",
        city: point.city || "Unknown",
        street: point.street || "Unknown",
        zip: point.zip || "",
        country: point.country || "CZ",
        pickupPointType: point.pickupPointType,
        directions: point.directions || "",
      };
      setSelectedPickupPoint(selectedPoint);
    }
  };

  const handleContactChange = (field: string, value: string) => {
    setContactInfo({
      ...contactInfo,
      [field]: value,
    });
    if (errors[field]) {
      setErrors({
        ...errors,
        [field]: "",
      });
    }
  };

  const handleApplyVoucher = async () => {
    if (!voucherCode.trim()) {
      setVoucherError("Zadejte kód poukazu");
      return;
    }

    try {
      const response = await fetch("/api/validate-voucher", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ code: voucherCode }),
      });

      const data = await response.json();

      if (data.success && data.discount !== undefined) {
        const discountValue =
          typeof data.discount === "string"
            ? parseFloat(data.discount)
            : data.discount;
        const type = data.discountType || "fixed";

        let finalDiscountAmount = discountValue;
        if (type === "percent") {
          const discountBase = totalPrice;
          finalDiscountAmount = (discountBase * discountValue) / 100;
        }

        setDiscountType(type as "fixed" | "percent");
        setVoucherDiscount(finalDiscountAmount);
        setVoucherError("");

        const displayValue =
          type === "percent"
            ? `${discountValue}%`
            : `-${finalDiscountAmount.toFixed(2)} Kč`;
        toast.success(`Sleva aplikována: ${displayValue}`);
      } else {
        setVoucherError(data.message || "Neplatný kód poukazu");
        setVoucherDiscount(0);
      }
    } catch (error) {
      setVoucherError("Chyba při ověření poukazu");
      setVoucherDiscount(0);
    }
  };

  const handleApplyCoupon = async (couponCode: string) => {
    setVoucherCode(couponCode.toUpperCase());
    setTimeout(() => {
      const codeInput = couponCode.toUpperCase();

      const coupon = availableCoupons.find((c) => c.code === codeInput);
      if (coupon) {
        const discountVal =
          typeof coupon.discountValue === "string"
            ? parseFloat(coupon.discountValue)
            : coupon.discountValue;

        let finalDiscountAmount = discountVal;
        if (coupon.discountType === "percent") {
          const discountBase = totalPrice;
          finalDiscountAmount = (discountBase * discountVal) / 100;
        }

        setDiscountType(coupon.discountType);
        setVoucherDiscount(finalDiscountAmount);
        setVoucherError("");

        const displayValue =
          coupon.discountType === "percent"
            ? `${discountVal}%`
            : `-${finalDiscountAmount.toFixed(2)} Kč`;
        toast.success(`Kupón aplikován: ${displayValue}`);
      }
    }, 0);
  };

  const validateForm = () => {
    const newErrors: Record<string, string> = {};

    if (!contactInfo.firstName?.trim())
      newErrors.firstName = "Jméno je povinné";
    if (!contactInfo.lastName?.trim())
      newErrors.lastName = "Příjmení je povinné";
    if (!contactInfo.email?.trim()) newErrors.email = "E-mail je povinný";
    if (
      contactInfo.email &&
      !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(contactInfo.email)
    )
      newErrors.email = "Neplatný e-mail";
    if (!contactInfo.phone?.trim()) {
      newErrors.phone = "Telefon je povinný";
    } else {
      const phoneLength = contactInfo.phone.trim().length;
      if (contactInfo.phonePrefix === "+421") {
        if (phoneLength < 8 || phoneLength > 9) {
          newErrors.phone = "SK číslo musí mít 8-9 číslic";
        }
      } else {
        if (phoneLength !== 9) {
          newErrors.phone = "CZ číslo musí mít 9 číslic";
        }
      }
    }
    if (!contactInfo.street?.trim()) newErrors.street = "Ulice je povinná";
    if (!contactInfo.city?.trim()) newErrors.city = "Město je povinné";
    if (!contactInfo.zip?.trim()) newErrors.zip = "PSČ je povinné";

    if (!hasOnlyVouchers()) {
      if (!selectedShipping) newErrors.shipping = "Vyberte způsob dopravy";

      if (selectedShippingOption?.requiresLocation && !selectedPickupPoint) {
        newErrors.pickupPoint =
          selectedShippingOption.type === "zbox"
            ? packetaErrorMessages.zbox
            : packetaErrorMessages.pickupPoint;
      }
    }

    setErrors(newErrors);

    if (Object.keys(newErrors).length > 0) {
      let scrollRef = contactRef;
      let errorMessage = "Prosím vyplňte všechny povinné informace";

      if (
        newErrors.firstName ||
        newErrors.lastName ||
        newErrors.email ||
        newErrors.phone ||
        newErrors.street ||
        newErrors.city ||
        newErrors.zip
      ) {
        scrollRef = contactRef;
        errorMessage = "Prosím vyplňte všechny kontaktní údaje";
      } else if (newErrors.shipping || newErrors.pickupPoint) {
        scrollRef = shippingRef;
        errorMessage = "Prosím vyberte způsob dopravy a místo vyzvednutí";
      }

      toast.error(errorMessage);

      setTimeout(() => {
        scrollRef.current?.scrollIntoView({
          behavior: "smooth",
          block: "center",
        });
      }, 100);
    }

    return Object.keys(newErrors).length === 0;
  };

  const openPacketaWidget = () => {
    if (window.Packeta?.Widget?.pick && packetaApiKey && isClient) {
      const config = {
        ...getPacketaConfig(selectedShippingOption?.type),
        ...(contactInfo.zip?.trim() ? { defaultZip: contactInfo.zip.trim() } : {}),
      };
      window.Packeta.Widget.pick(packetaApiKey, handlePacketaSelection, config);
    }
  };

  const openCarrierMap = () => {
    const carrier = selectedShippingOption?.carrier;
    if (carrier === "packeta") openPacketaWidget();
    else if (carrier === "czech_post") setIsBalikovnaModalOpen(true);
    else if (carrier === "gls") setIsGlsModalOpen(true);
    else if (carrier === "dpd") setIsDpdModalOpen(true);
  };

  const handleOrder = async () => {
    if (isSubmittingRef.current) return;

    if (!validateForm()) return;



    isSubmittingRef.current = true;
    setIsProcessing(true);

    try {
      const orderData = {
        items: items.map((item) => ({
          productId: item.productId,
          variantId: item.variantId,
          name: item.productName,
          brand: item.brandName,
          volume: item.volume,
          quantity: item.quantity,
          price: item.price,
        })),
        shipping: {
          id: selectedShippingOption?.id,
          method:
            hasOnlyVouchers() && !selectedShippingOption
              ? "Elektronické doručení"
              : selectedShippingOption?.name,
          price:
            hasOnlyVouchers() && !selectedShippingOption ? 0 : shippingPrice,
          type: selectedShippingOption?.type,
          carrier: selectedShippingOption?.carrier,
          pickupPoint: selectedPickupPoint
            ? {
                id: selectedPickupPoint.id,
                name: selectedPickupPoint.name,
                city: selectedPickupPoint.city,
                street: selectedPickupPoint.street,
                zip: selectedPickupPoint.zip,
                pickupPointType: selectedPickupPoint.pickupPointType,
              }
            : undefined,
        },
        contact: {
          ...contactInfo,
          phone: `${contactInfo.phonePrefix || "+420"}${contactInfo.phone}`,
        },
        totalPrice: finalTotal,
        orderNote: contactInfo.orderNote,
        voucherCode: voucherCode || null,
        voucherDiscount: actualDiscount,
        discountType: discountType,
        isGiftWrapped: isGiftWrapped,
      };

      const response = await fetch("/api/orders", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(orderData),
      });

      if (!response.ok) {
        const errorData = await response.json();
        if (response.status === 409) {
          if (errorData.code === "STOCK_CHANGED") {
            setStockError({
              message: errorData.error,
              variantId: errorData.details?.variantId,
            });
            await refreshCart();
            isSubmittingRef.current = false;
            setIsProcessing(false);
            return;
          }

          await refreshCart();
        }
        throw new Error(errorData.error || "Chyba při vytváření objednávky");
      }

      const result = await response.json();

      if (result.success && result.redirectUrl) {
        await clearCart();

        window.location.href = result.redirectUrl;
      } else {
        throw new Error(result.error || "Neznámá chyba při vytváření platby");
      }
    } catch (error) {
      isSubmittingRef.current = false;
      setIsProcessing(false);
      const errorMessage =
        error instanceof Error
          ? error.message
          : "Chyba při vytváření objednávky";
      alert(`Chyba: ${errorMessage}`);
    }
  };

  const inputClassName =
    "w-full px-4 py-2.5 bg-luxury-dark/50 border-2 border-luxury-gold/30 text-luxury-light rounded-lg focus:outline-none focus:border-luxury-gold focus:ring-2 focus:ring-luxury-gold/50 transition-all placeholder:text-luxury-gold/40";
  const errorClassName =
    "border-red-500 focus:border-red-500 focus:ring-red-500/50";
  const labelClassName =
    "block text-luxury-light font-bold mb-1.5 text-sm";

  return (
    <>
      <Head>
        <title>Košík | Vystříkejto.cz</title>
        <meta name="robots" content="noindex,nofollow,noarchive" />
      </Head>
      <div className="checkout-page min-h-screen bg-luxury-dark pt-28 sm:pt-32 md:pt-40 lg:pt-44 pb-12 md:pb-16">
        {/* Load Packeta Widget Script */}
        <Script
          src="https://widget.packeta.com/v6/www/js/library.js"
          strategy="lazyOnload"
          onLoad={() => {
            setPacketaLoaded(true);
          }}
        />

        <div className="max-w-7xl mx-auto px-3 sm:px-4 md:px-6 lg:px-8">
          {/* Header */}
          <div className="checkout-heading text-center mb-7 md:mb-9">
            <h1 className="text-4xl sm:text-5xl md:text-6xl font-aptos font-black text-luxury-gold mb-3 uppercase">
              Objednávka
            </h1>
            <div className="w-12 sm:w-16 h-1.5 bg-luxury-gold mx-auto" />
          </div>

          {/* Content */}
          {items.length === 0 ? (
            <div className="bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-8 md:p-12 text-center">
              <svg
                className="w-16 h-16 md:w-24 md:h-24 text-luxury-gold/50 mx-auto mb-8"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1.5}
                  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>
              <h2 className="text-3xl md:text-4xl font-aptos font-black text-luxury-light mb-4">
                VÁŠ KOŠÍK JE PRÁZDNÝ
              </h2>
              <p className="text-luxury-light text-base md:text-lg mb-10 font-medium">
                Přidejte některé produkty, abyste mohli pokračovat v nákupu.
              </p>
              <Link href="/">
                <button className="bg-luxury-gold text-luxury-dark px-10 py-4 rounded-sm font-black text-base uppercase tracking-widest hover:bg-yellow-300 transition-all duration-300 active:scale-95 shadow-lg">
                  Pokračovat v nákupu
                </button>
              </Link>
            </div>
          ) : (
            <div className="checkout-layout">
              {/* Free Shipping Progress Bar */}
              {!hasOnlyVouchers() && (
                <div className="checkout-progress bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-4 md:px-6 md:py-5 hover:border-luxury-gold/40 transition-all duration-300">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-base md:text-lg font-aptos font-black text-luxury-gold uppercase">
                      DOPRAVA ZDARMA
                    </h3>
                  </div>

                  <div className="mb-3">
                    <div className="relative w-full h-2 bg-black/40 rounded-full border border-luxury-gold/20 overflow-hidden">
                      <div
                        className="h-full bg-luxury-gold transition-all duration-700 ease-out"
                        style={{
                          width: `${Math.min((totalPrice / 999) * 100, 100)}%`,
                        }}
                      />
                    </div>
                  </div>

                  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
                    <div className="flex-grow">
                      {totalPrice >= 999 ? (
                        <div className="flex items-center gap-2">
                          <svg
                            className="w-5 h-5 text-green-400 flex-shrink-0"
                            fill="currentColor"
                            viewBox="0 0 20 20"
                          >
                            <path
                              fillRule="evenodd"
                              d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                              clipRule="evenodd"
                            />
                          </svg>
                          <span className="text-green-400 font-bold text-sm md:text-base">
                            Máte nárok na bezplatné doručení!
                          </span>
                        </div>
                      ) : (
                        <p className="text-sm md:text-base text-luxury-light/70">
                          Chybí Vám{" "}
                          <span className="text-luxury-gold font-bold">
                            {(999 - totalPrice).toFixed(2)} Kč
                          </span>{" "}
                          k dopravě{" "}
                          <span className="text-luxury-gold font-bold">
                            ZDARMA
                          </span>
                        </p>
                      )}
                    </div>
                    <p className="text-lg md:text-xl font-aptos font-black text-luxury-gold whitespace-nowrap">
                      {totalPrice.toFixed(2)} Kč / 999 Kč
                    </p>
                  </div>
                </div>
              )}

              {/* Section 1: Shopping Cart */}
              {false && <div className="checkout-cart checkout-card bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-4 md:p-6">
                <div className="checkout-section-title">
                  <h2>Váš nákupní košík</h2>
                </div>
                <div className="space-y-3 md:space-y-4">
                  {items.map((item) => (
                    <div
                      key={item.variantId}
                      className="checkout-cart-item bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-3 flex flex-col md:flex-row md:items-center gap-3 hover:border-luxury-gold/50 transition-all duration-300 group relative"
                    >
                      <div className="flex gap-3 md:gap-4 flex-grow">
                        {item.productType === "bundle" ? (
                          <Link href={`/vyhodne-sady/${item.productSlug}`}>
                            <BundleImageGrid
                              bundleId={item.productId}
                              containerClassName="group-hover:border-luxury-gold/40 transition-all duration-300"
                            />
                          </Link>
                        ) : (
                          <Link
                            href={`/product/${item.productSlug}`}
                            className="checkout-product-image flex-shrink-0 w-20 h-24 md:w-24 md:h-28 bg-luxury-dark/50 rounded-lg overflow-hidden flex items-center justify-center border border-luxury-gold/20 group-hover:border-luxury-gold/40 transition-all duration-300"
                          >
                            <img
                              src={item.image}
                              alt={item.productName}
                              className="w-full h-full object-contain"
                              onError={(e) => {
                                (e.target as HTMLImageElement).src =
                                  "data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%25%22 height=%22100%25%22%3E%3Crect fill=%220a0a0a%22 width=%22100%25%22 height=%22100%25%22/%3E%3Crect fill=%22%23f3bd3533%22 x=%2225%25%22 y=%2225%25%22 width=%2250%25%22 height=%2250%25%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 text-anchor=%22middle%22 dy=%22.3em%22 fill=%22%23f3bd35%22 font-size=%2212%22 font-family=%22serif%22%3E✓%3C/text%3E%3C/svg%3E";
                              }}
                            />
                          </Link>
                        )}

                        <div className="flex-grow">
                          <Link href={item.productType === "bundle" ? `/vyhodne-sady/${item.productSlug}` : `/product/${item.productSlug}`}>
                            <h3 className="text-base md:text-lg font-aptos font-black text-luxury-light mb-0.5 group-hover:text-luxury-gold transition-colors duration-300 line-clamp-2">
                              {item.productName}
                            </h3>
                          </Link>
                          <p className="text-luxury-light/65 text-sm font-medium mb-1">
                            <span className="text-luxury-gold">
                              {item.brandName}
                            </span>{" "}
                            • {item.volume}
                          </p>
                          <p className="text-luxury-gold text-xs font-bold mb-2">
                            Skladem
                          </p>

                          <p className="text-sm font-aptos font-bold text-luxury-gold mb-2 whitespace-nowrap">
                            {Number(item.price).toFixed(2)} Kč / ks
                          </p>

                          {/* Quantity Selector - Desktop */}
                          <div className="hidden md:flex items-center gap-2 bg-luxury-dark/50 rounded-lg px-2 py-1 md:px-3 md:py-1.5 border border-luxury-gold/20 w-fit">
                            <button
                              onClick={() =>
                                updateQuantity(
                                  item.variantId,
                                  Math.max(0, item.quantity - 1),
                                )
                              }
                              className="text-luxury-gold hover:text-yellow-300 font-bold text-xs md:text-sm w-5 h-5 md:w-6 md:h-6 flex items-center justify-center transition-colors duration-200"
                            >
                              −
                            </button>
                            <span className="text-luxury-light font-bold text-xs md:text-sm w-6 md:w-8 text-center">
                              {item.quantity}
                            </span>
                            <button
                              onClick={() =>
                                updateQuantity(
                                  item.variantId,
                                  item.quantity + 1,
                                )
                              }
                              className="text-luxury-gold hover:text-yellow-300 font-bold text-xs md:text-sm w-5 h-5 md:w-6 md:h-6 flex items-center justify-center transition-colors duration-200"
                            >
                              +
                            </button>
                            <span className="text-luxury-light/60 text-xs font-medium ml-1 md:ml-2">
                              ks
                            </span>
                          </div>
                        </div>
                      </div>

                      {/* Mobile Quantity and Price Row */}
                      <div className="flex md:hidden items-center justify-between w-full pt-3 border-t border-luxury-gold/10 gap-2">
                        <div className="flex items-center gap-1 bg-luxury-dark/50 rounded-lg px-1.5 py-1 border border-luxury-gold/20 w-fit">
                          <button
                            onClick={() =>
                              updateQuantity(
                                item.variantId,
                                Math.max(0, item.quantity - 1),
                              )
                            }
                            className="text-luxury-gold hover:text-yellow-300 font-bold text-xs w-5 h-5 flex items-center justify-center transition-colors duration-200"
                          >
                            −
                          </button>
                          <span className="text-luxury-light font-bold text-xs w-6 text-center">
                            {item.quantity}
                          </span>
                          <button
                            onClick={() =>
                              updateQuantity(item.variantId, item.quantity + 1)
                            }
                            className="text-luxury-gold hover:text-yellow-300 font-bold text-xs w-5 h-5 flex items-center justify-center transition-colors duration-200"
                          >
                            +
                          </button>
                          <span className="text-luxury-light/60 text-xs font-medium ml-0.5">
                            ks
                          </span>
                        </div>
                        <div className="text-right flex-grow">
                          <p className="text-lg font-aptos font-black text-luxury-gold whitespace-nowrap">
                            {(Number(item.price) * item.quantity).toFixed(2)} Kč
                          </p>
                        </div>
                        <button
                          onClick={() => removeItem(item.variantId)}
                          className="text-red-500 hover:text-red-300 transition-colors duration-300 p-2 flex-shrink-0"
                          title="Odebrat z košíku"
                        >
                          <svg
                            className="w-5 h-5"
                            fill="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                          </svg>
                        </button>
                      </div>

                      {/* Total Price - Desktop */}
                      <div className="hidden md:block text-right md:px-2">
                        <p className="text-lg md:text-xl font-aptos font-black text-luxury-gold whitespace-nowrap">
                          {(Number(item.price) * item.quantity).toFixed(2)} Kč
                        </p>
                      </div>

                      {/* Remove Button - Desktop only */}
                      <button
                        onClick={() => removeItem(item.variantId)}
                        className="hidden md:block text-red-500 hover:text-red-300 transition-colors duration-300 p-2"
                        title="Odebrat z košíku"
                      >
                        <svg
                          className="w-6 h-6"
                          fill="currentColor"
                          viewBox="0 0 24 24"
                        >
                          <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                        </svg>
                      </button>
                    </div>
                  ))}
                </div>
              </div>}

              {/* Section 2: Contact Information */}
              <div
                ref={contactRef}
                className="checkout-contact checkout-card bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-4 md:p-6"
              >
                <div className="checkout-section-title">
                  <h2>Kontaktní údaje</h2>
                </div>
                <p className="text-xs text-luxury-light/50 mb-4">
                  Pole označená{" "}
                  <span className="text-luxury-gold font-bold">*</span> jsou
                  povinná.
                </p>

                <form className="space-y-4">
                  {/* Name Section */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label htmlFor="firstName" className={labelClassName}>
                        Jméno *
                      </label>
                      <input
                        id="firstName"
                        type="text"
                        placeholder="Vaše jméno"
                        value={contactInfo.firstName || ""}
                        onChange={(e) =>
                          handleContactChange("firstName", e.target.value)
                        }
                        className={`${inputClassName} ${errors.firstName ? errorClassName : ""}`}
                        autoComplete="given-name"
                      />
                      {errors.firstName && (
                        <p className="text-red-500 text-sm mt-1">
                          {errors.firstName}
                        </p>
                      )}
                    </div>

                    <div>
                      <label htmlFor="lastName" className={labelClassName}>
                        Příjmení *
                      </label>
                      <input
                        id="lastName"
                        type="text"
                        placeholder="Vaše příjmení"
                        value={contactInfo.lastName || ""}
                        onChange={(e) =>
                          handleContactChange("lastName", e.target.value)
                        }
                        className={`${inputClassName} ${errors.lastName ? errorClassName : ""}`}
                        autoComplete="family-name"
                      />
                      {errors.lastName && (
                        <p className="text-red-500 text-sm mt-1">
                          {errors.lastName}
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Email and Phone */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label htmlFor="email" className={labelClassName}>
                        Email *
                      </label>
                      <input
                        id="email"
                        type="email"
                        placeholder="Váš e-mail"
                        value={contactInfo.email || ""}
                        onChange={(e) =>
                          handleContactChange("email", e.target.value)
                        }
                        className={`${inputClassName} ${errors.email ? errorClassName : ""}`}
                        autoComplete="email"
                      />
                      {errors.email && (
                        <p className="text-red-500 text-sm mt-1">
                          {errors.email}
                        </p>
                      )}
                    </div>

                    <div>
                      <label className={labelClassName}>Telefon *</label>
                      <div className="flex gap-2">
                        <select
                          value={contactInfo.phonePrefix || "+420"}
                          onChange={(e) =>
                            handleContactChange("phonePrefix", e.target.value)
                          }
                          className={`px-3 py-3 bg-luxury-dark/50 border-2 border-luxury-gold/30 text-luxury-light rounded-lg focus:outline-none focus:border-luxury-gold focus:ring-2 focus:ring-luxury-gold/50 transition-all w-20 flex-shrink-0 cursor-pointer text-sm`}
                          autoComplete="tel-country-code"
                        >
                          <option value="+420">+420</option>
                          <option value="+421">+421</option>
                        </select>
                        <input
                          id="phone"
                          type="tel"
                          placeholder="123456789"
                          value={contactInfo.phone || ""}
                          onChange={(e) => {
                            const value = e.target.value.replace(/\D/g, "");
                            const maxLength =
                              contactInfo.phonePrefix === "+421" ? 9 : 9;
                            if (value.length <= maxLength) {
                              handleContactChange("phone", value);
                            }
                          }}
                          maxLength={contactInfo.phonePrefix === "+421" ? 9 : 9}
                          className={`${inputClassName} ${errors.phone ? errorClassName : ""} flex-grow`}
                          autoComplete="tel-national"
                        />
                      </div>
                      {errors.phone && (
                        <p className="text-red-500 text-sm mt-1">
                          {errors.phone}
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Address - Street */}
                  <div>
                    <label htmlFor="street" className={labelClassName}>
                      Ulice a číslo *
                    </label>
                    <input
                      id="street"
                      type="text"
                      placeholder="Např. Hlavní 123"
                      value={contactInfo.street || ""}
                      onChange={(e) =>
                        handleContactChange("street", e.target.value)
                      }
                      className={`${inputClassName} ${errors.street ? errorClassName : ""}`}
                      autoComplete="street-address"
                    />
                    {errors.street && (
                      <p className="text-red-500 text-sm mt-1">
                        {errors.street}
                      </p>
                    )}
                  </div>

                  {/* City, Postal Code */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                      <label htmlFor="city" className={labelClassName}>
                        Město *
                      </label>
                      <input
                        id="city"
                        type="text"
                        placeholder="Např. Praha"
                        value={contactInfo.city || ""}
                        onChange={(e) =>
                          handleContactChange("city", e.target.value)
                        }
                        className={`${inputClassName} ${errors.city ? errorClassName : ""}`}
                        autoComplete="address-level2"
                      />
                      {errors.city && (
                        <p className="text-red-500 text-sm mt-1">
                          {errors.city}
                        </p>
                      )}
                    </div>

                    <div>
                      <label htmlFor="zip" className={labelClassName}>
                        PSČ *
                      </label>
                      <input
                        id="zip"
                        type="text"
                        placeholder="Např. 110 00"
                        value={contactInfo.zip || ""}
                        onChange={(e) =>
                          handleContactChange("zip", e.target.value)
                        }
                        className={`${inputClassName} ${errors.zip ? errorClassName : ""}`}
                        autoComplete="postal-code"
                      />
                      {errors.zip && (
                        <p className="text-red-500 text-sm mt-1">
                          {errors.zip}
                        </p>
                      )}
                    </div>
                  </div>

                  {/* Order Note */}
                  <div>
                    <label htmlFor="orderNote" className={labelClassName}>
                      Poznámka k objednávce (nepovinné)
                    </label>
                    <textarea
                      id="orderNote"
                      placeholder="Napište svou poznámku..."
                      value={contactInfo.orderNote || ""}
                      onChange={(e) =>
                        handleContactChange("orderNote", e.target.value)
                      }
                      className={`${inputClassName} resize-none min-h-20`}
                    />
                  </div>
                </form>
              </div>

              {/* Section 3: Shipping - skrýt pokud jsou jen voucher produkty */}
              {!hasOnlyVouchers() && (
                <div
                  ref={shippingRef}
                  className="checkout-shipping checkout-card bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-4 md:p-6"
                >
                  <div className="checkout-section-title">
                    <h2>Způsob dopravy</h2>
                  </div>
                  <div className="space-y-2 mb-3">
                    {shippingOptions.map((option) => (
                      <div
                        key={option.id}
                        className={`rounded-lg border-2 transition-all duration-300 ${
                          selectedShipping === option.id
                            ? "border-luxury-gold bg-luxury-dark/80 shadow-lg shadow-luxury-gold/20"
                            : "border-luxury-gold/20 bg-gradient-to-b from-luxury-dark to-luxury-dark hover:border-luxury-gold/50"
                        }`}
                      >
                      <button
                        type="button"
                        onClick={() => {
                          setSelectedShipping(option.id);
                          if (option.requiresLocation) {
                            setSelectedPickupPoint(null);
                          }
                        }}
                        className="w-full p-3 md:p-4 text-left"
                      >
                        <div className="flex items-center justify-between gap-3">
                          <div className="flex items-center gap-3 min-w-0">
                            {option.carrier === "czech_post" && (
                              <div className="checkout-carrier-logo">
                                <img
                                  src="/images/dopravci/balikovna.png"
                                  alt="Balíkovna"
                                  className="w-full h-full object-contain"
                                />
                              </div>
                            )}
                            {option.carrier === "packeta" && (
                              <div className="checkout-carrier-logo">
                                <img
                                  src="/images/dopravci/packeta.png"
                                  alt="Zásilkovna"
                                  className="w-full h-full object-contain"
                                />
                              </div>
                            )}
                            {option.carrier === "ppl" && (
                              <div className="checkout-carrier-logo">
                                <img
                                  src="/images/dopravci/ppl2.png"
                                  alt="PPL"
                                  className="w-full h-full object-contain"
                                />
                              </div>
                            )}
                            {option.carrier === "gls" && (
                              <div className="checkout-carrier-logo">
                                <img
                                  src="/images/dopravci/gls.png"
                                  alt="GLS"
                                  className="w-full h-full object-contain"
                                />
                              </div>
                            )}
                            {option.carrier === "dpd" && (
                              <div className="checkout-carrier-logo">
                                <img
                                  src="/images/dopravci/dpd.png"
                                  alt="DPD"
                                  className="w-full h-full object-contain"
                                />
                              </div>
                            )}
                            <div>
                              <h3 className="text-sm md:text-base font-aptos font-black text-luxury-light mb-0.5 leading-tight">
                                {option.name}
                              </h3>
                              <p className="text-luxury-light/50 text-xs">
                                Doručení přibližně za {option.days}{" "}
                                {option.days === 1 ? "den" : "dny"}
                              </p>
                            </div>
                          </div>
                          <div className="flex flex-shrink-0 items-center gap-2 text-right">
                            {totalPrice >= 999 ? (
                              <p className="text-lg md:text-xl font-aptos font-black text-green-400 whitespace-nowrap">
                                ZDARMA
                              </p>
                            ) : (
                              <p className="text-lg md:text-xl font-aptos font-black text-luxury-gold whitespace-nowrap">
                                {option.price} Kč
                              </p>
                            )}
                            <span
                              className={`flex h-5 w-5 items-center justify-center rounded-full border transition-all duration-300 ${
                                selectedShipping === option.id
                                  ? "border-luxury-gold bg-luxury-gold text-luxury-dark"
                                  : "border-luxury-gold/40 bg-transparent"
                              }`}
                              aria-hidden="true"
                            >
                              {selectedShipping === option.id && (
                                <svg
                                  className="h-3 w-3"
                                  fill="none"
                                  stroke="currentColor"
                                  viewBox="0 0 24 24"
                                >
                                  <path
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                    strokeWidth={3}
                                    d="M5 13l4 4L19 7"
                                  />
                                </svg>
                              )}
                            </span>
                          </div>
                        </div>
                      </button>
                      {selectedShipping === option.id && option.requiresLocation && (
                        <div className="px-4 pb-4 md:px-6 md:pb-6">
                          <PickupPointSuggestions
                            carrier={option.carrier}
                            shippingType={option.type}
                            street={contactInfo.street}
                            city={contactInfo.city}
                            zip={contactInfo.zip}
                            selectedPoint={selectedPickupPoint}
                            onSelect={setSelectedPickupPoint}
                            onOpenMap={openCarrierMap}
                          />
                          {errors.pickupPoint && (
                            <p className="text-red-500 text-sm mt-4">
                              {errors.pickupPoint}
                            </p>
                          )}
                        </div>
                      )}
                      </div>
                    ))}
                  </div>
                  {errors.shipping && (
                    <p className="text-red-500 text-sm">{errors.shipping}</p>
                  )}

                  {isBalikovnaModalOpen && (
                    <div className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center">
                      <div className="relative w-full h-full flex flex-col bg-white">
                        <div className="bg-luxury-dark p-4 flex justify-between items-center border-b border-luxury-gold/20">
                          <h3 className="text-luxury-gold font-bold">
                            Vyberte Balíkovnu
                          </h3>
                          <button
                            onClick={() => setIsBalikovnaModalOpen(false)}
                            className="bg-luxury-gold text-luxury-dark px-6 py-2 rounded-lg font-bold hover:bg-yellow-300 transition-all duration-300"
                          >
                            Zavřít
                          </button>
                        </div>
                        <iframe
                          src="https://b2c.cpost.cz/locations/?type=BALIKOVNY&phone=false&skipLocation=false"
                          style={{
                            flex: 1,
                            width: "100%",
                            height: "100%",
                            border: "none",
                          }}
                          allow="geolocation"
                        />
                      </div>
                    </div>
                  )}

                  {isGlsModalOpen && (
                    <div className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center">
                      <div className="relative w-full h-full flex flex-col bg-white">
                        <div className="bg-luxury-dark p-4 flex justify-between items-center border-b border-luxury-gold/20">
                          <h3 className="text-luxury-gold font-bold">
                            Vyberte výdejní místo GLS
                          </h3>
                          <button
                            onClick={() => setIsGlsModalOpen(false)}
                            className="bg-luxury-gold text-luxury-dark px-6 py-2 rounded-lg font-bold hover:bg-yellow-300 transition-all duration-300"
                          >
                            Zavřít
                          </button>
                        </div>
                        <iframe
                          src={`https://ps-maps.gls-czech.com/?find=1&lng=cs&ctrcode=CZ${
                            contactInfo.street || contactInfo.city
                              ? `&p=${encodeURIComponent(
                                  [contactInfo.street, contactInfo.city]
                                    .filter(Boolean)
                                    .join(", "),
                                )}`
                              : ""
                          }`}
                          style={{
                            flex: 1,
                            width: "100%",
                            height: "100%",
                            border: "none",
                          }}
                          allow="geolocation"
                        />
                      </div>
                    </div>
                  )}

                  {isDpdModalOpen && (
                    <div className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center">
                      <div className="relative w-full h-full flex flex-col bg-white">
                        <div className="bg-luxury-dark p-4 flex justify-between items-center border-b border-luxury-gold/20">
                          <h3 className="text-luxury-gold font-bold">
                            Vyberte výdejní místo DPD
                          </h3>
                          <button
                            onClick={() => setIsDpdModalOpen(false)}
                            className="bg-luxury-gold text-luxury-dark px-6 py-2 rounded-lg font-bold hover:bg-yellow-300 transition-all duration-300"
                          >
                            Zavřít
                          </button>
                        </div>
                        <iframe
                          src="https://api.dpd.cz/widget/latest/index.html?lang=cs&enabledCountries=CZ"
                          style={{
                            flex: 1,
                            width: "100%",
                            height: "100%",
                            border: "none",
                          }}
                          allow="geolocation"
                        />
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Section 4: Order Summary */}
              <div className="checkout-summary checkout-card bg-gradient-to-b from-luxury-dark to-luxury-dark border border-luxury-gold/20 rounded-lg p-4 md:p-6">
                <div className="checkout-section-title">
                  <h2>Shrnutí objednávky</h2>
                </div>

                {/* Items */}
                <div className="mb-4 pb-4 border-b border-luxury-gold/20">
                  <h3 className="text-lg font-aptos font-black text-luxury-gold mb-4">
                    Produkty ({items.length})
                  </h3>
                  <div className="space-y-4">
                    {items.map((item, index) => (
                      <div
                        key={item.variantId}
                        className={`checkout-summary-item flex items-start gap-3 ${index < items.length - 1 ? "pb-3 border-b border-luxury-gold/20" : ""}`}
                      >
                        {item.productType === "bundle" ? (
                          <Link href={`/vyhodne-sady/${item.productSlug}`}>
                            <BundleImageGrid bundleId={item.productId} />
                          </Link>
                        ) : (
                          <Link
                            href={`/product/${item.productSlug}`}
                            className="flex-shrink-0 w-16 h-20 bg-luxury-dark/50 rounded-lg overflow-hidden flex items-center justify-center border border-luxury-gold/20 hover:border-luxury-gold/40 transition-all duration-300"
                          >
                            <img
                              src={item.image}
                              alt={item.productName}
                              className="w-full h-full object-contain"
                              onError={(e) => {
                                (e.target as HTMLImageElement).src =
                                  "data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 width=%22100%25%22 height=%22100%25%22%3E%3Crect fill=%220a0a0a%22 width=%22100%25%22 height=%22100%25%22/%3E%3Crect fill=%22%23f3bd3533%22 x=%2225%25%22 y=%2225%25%22 width=%2250%25%22 height=%2250%25%22/%3E%3Ctext x=%2250%25%22 y=%2250%25%22 text-anchor=%22middle%22 dy=%22.3em%22 fill=%22%23f3bd35%22 font-size=%2212%22 font-family=%22serif%22%3E✓%3C/text%3E%3C/svg%3E";
                              }}
                            />
                          </Link>
                        )}
                        <div className="flex-grow min-w-0">
                          <Link href={item.productType === "bundle" ? `/vyhodne-sady/${item.productSlug}` : `/product/${item.productSlug}`}>
                            <p className="text-sm font-bold text-luxury-light hover:text-luxury-gold transition-colors duration-300 line-clamp-2">
                              {item.productName}
                            </p>
                          </Link>
                          <p className="text-xs text-luxury-light/65 whitespace-nowrap">
                            <span className="text-luxury-gold">
                              {item.brandName}
                            </span>{" "}
                            • {item.volume}
                          </p>
                          <p className="text-[11px] text-luxury-light/45 mt-1">
                            {Number(item.price).toFixed(2)} Kč / ks
                          </p>
                          <div className="flex items-center justify-between gap-2 mt-2">
                            <div className="flex items-center bg-luxury-dark/50 rounded-lg border border-luxury-gold/20 px-1 py-0.5">
                              <button
                                type="button"
                                onClick={() =>
                                  updateQuantity(
                                    item.variantId,
                                    Math.max(0, item.quantity - 1),
                                  )
                                }
                                className="w-7 h-7 flex items-center justify-center text-luxury-gold hover:text-yellow-300 font-bold transition-colors"
                                aria-label={`Snížit počet ${item.productName}`}
                              >
                                −
                              </button>
                              <span className="w-7 text-center text-xs font-bold text-luxury-light">
                                {item.quantity}
                              </span>
                              <button
                                type="button"
                                onClick={() =>
                                  updateQuantity(
                                    item.variantId,
                                    item.quantity + 1,
                                  )
                                }
                                className="w-7 h-7 flex items-center justify-center text-luxury-gold hover:text-yellow-300 font-bold transition-colors"
                                aria-label={`Zvýšit počet ${item.productName}`}
                              >
                                +
                              </button>
                            </div>
                            <p className="text-sm font-bold text-luxury-gold whitespace-nowrap">
                              {(Number(item.price) * item.quantity).toFixed(2)} Kč
                            </p>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={() => removeItem(item.variantId)}
                          className="flex-shrink-0 -mt-1 -mr-1 p-1.5 text-red-500 hover:text-red-300 transition-colors"
                          title="Odebrat z košíku"
                          aria-label={`Odebrat ${item.productName} z košíku`}
                        >
                          <svg
                            className="w-4 h-4"
                            fill="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                          </svg>
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Subtotal */}
                <div className="mb-6 pb-6 border-b border-luxury-gold/20">
                  <div className="flex justify-between text-base">
                    <span className="text-luxury-light font-bold">
                      Mezisoučet:
                    </span>
                    <span className="font-bold text-luxury-gold whitespace-nowrap">
                      {Number(totalPrice).toFixed(2)} Kč
                    </span>
                  </div>
                </div>

                {/* Voucher Section */}
                {!hasOnlyVouchers() ? (
                  <div className="mb-6 pb-6 border-b border-luxury-gold/20">
                    <h3 className="text-lg font-aptos font-black text-luxury-gold mb-4">
                      Slevový / Dárkový poukaz
                    </h3>
                    <div className="flex gap-3">
                      <input
                        type="text"
                        placeholder="Zadejte kód poukazu"
                        value={voucherCode}
                        onChange={(e) => {
                          setVoucherCode(e.target.value.toUpperCase());
                          setVoucherError("");
                        }}
                        className="flex-grow px-4 py-3 bg-luxury-dark/50 border-2 border-luxury-gold/30 text-luxury-light rounded-lg focus:outline-none focus:border-luxury-gold focus:ring-2 focus:ring-luxury-gold/50 transition-all placeholder:text-luxury-gold/40"
                      />
                      <button
                        onClick={handleApplyVoucher}
                        className="px-6 py-3 bg-luxury-gold/20 border-2 border-luxury-gold text-luxury-gold font-bold rounded-lg hover:bg-luxury-gold/30 transition-all duration-300"
                      >
                        Použít
                      </button>
                    </div>

                    {/* Available Coupons for logged-in users */}
                    {session?.user?.email && availableCoupons.length > 0 && (
                      <div className="mt-4 p-4 bg-luxury-dark/30 rounded-lg border border-luxury-gold/30">
                        <p className="text-sm text-luxury-light/70 mb-3">
                          {loadingCoupons
                            ? "Načítám vaše kupony..."
                            : "Dostupné kupony:"}
                        </p>
                        <div className="space-y-2">
                          {availableCoupons.map((coupon) => (
                            <button
                              key={coupon.code}
                              onClick={() => handleApplyCoupon(coupon.code)}
                              className="w-full text-left p-3 bg-luxury-dark/50 border border-luxury-gold/40 rounded-lg hover:border-luxury-gold hover:bg-luxury-dark/60 transition-all duration-300 group"
                            >
                              <div className="flex items-center justify-between">
                                <div>
                                  <p className="font-bold text-luxury-gold group-hover:text-yellow-300 transition-colors">
                                    {coupon.code}
                                  </p>
                                  <p className="text-xs text-luxury-light/60 mt-1">
                                    {coupon.discountType === "percent"
                                      ? `${coupon.discountValue}% sleva`
                                      : `${coupon.discountValue} Kč sleva`}
                                    {" • expiruje: "}
                                    {new Date(
                                      coupon.expiresAt,
                                    ).toLocaleDateString("cs-CZ")}
                                  </p>
                                </div>
                                <span className="text-xs bg-luxury-gold/20 text-luxury-gold px-2 py-1 rounded">
                                  1x použití
                                </span>
                              </div>
                            </button>
                          ))}
                        </div>
                      </div>
                    )}

                    {voucherError && (
                      <p className="text-red-500 text-sm mt-2">
                        {voucherError}
                      </p>
                    )}
                    {voucherDiscount > 0 && (
                      <div className="mt-4 p-3 bg-luxury-dark/50 rounded-lg border border-luxury-gold/20 flex justify-between items-center">
                        <div className="flex flex-col">
                          <span className="text-luxury-light text-xs uppercase font-bold text-luxury-gold/60">
                            Aplikovaná sleva
                          </span>
                          <span className="font-bold text-green-400 whitespace-nowrap">
                            {actualDiscount.toFixed(2)} Kč
                          </span>
                        </div>
                        <button
                          onClick={() => {
                            setVoucherCode("");
                            setVoucherDiscount(0);
                            setVoucherError("");
                            toast.success("Sleva byla odebrána");
                          }}
                          className="text-red-500 hover:text-red-400 text-sm font-bold flex items-center gap-1 transition-colors"
                        >
                          <svg
                            className="w-4 h-4"
                            fill="currentColor"
                            viewBox="0 0 24 24"
                          >
                            <path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z" />
                          </svg>
                          Odebrat
                        </button>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="mb-6 pb-6 border-b border-luxury-gold/20">
                    <h3 className="text-lg font-aptos font-black text-luxury-gold mb-4">
                      Slevový / Dárkový poukaz
                    </h3>
                    <p className="text-luxury-light/60 text-sm">
                      Poukazy nelze kombinovat s nákupem dalších poukazů. Pokud
                      si přejete koupit poukaz, prosím odeberte ostatní poukazy
                      z košíku.
                    </p>
                  </div>
                )}

                {/* Gift Wrap Section */}
                {!hasOnlyVouchers() && (
                  <div className="mb-6 pb-6 border-b border-luxury-gold/20">
                    <h3 className="text-lg font-aptos font-black text-luxury-gold mb-4">
                      Dárkové balení
                    </h3>
                    <label className="flex items-center gap-3 cursor-pointer group">
                      <div className="relative">
                        <input
                          type="checkbox"
                          checked={isGiftWrapped}
                          onChange={(e) => setIsGiftWrapped(e.target.checked)}
                          className="w-6 h-6 accent-luxury-gold cursor-pointer"
                        />
                      </div>
                      <div className="flex-grow">
                        <p className="text-lg text-luxury-light font-bold group-hover:text-luxury-gold transition-colors duration-300">
                          Přidat dárkové balení
                        </p>
                        <p className="text-sm text-luxury-light/60">
                          Prémiově zabaleno se zlatou stuhou.
                        </p>
                      </div>
                      <div className="text-right">
                        <p className="text-xl font-aptos font-black text-luxury-gold whitespace-nowrap">
                          +{GIFT_WRAP_PRICE} Kč
                        </p>
                      </div>
                    </label>
                  </div>
                )}

                {/* Total */}
                <div className="mb-8">
                  <div className="space-y-3">
                    {hasPerfume() && selectedShipping && (
                      <>
                        <div className="flex justify-between items-center text-base">
                          <span className="text-luxury-light font-bold">
                            Zvolená doprava:
                          </span>
                          <span className="font-bold text-luxury-gold">
                            {selectedShippingOption?.name}
                          </span>
                        </div>
                        <div className="flex justify-between items-center text-base">
                          <span className="text-luxury-light font-bold">
                            Cena zvolené dopravy:
                          </span>
                          {shippingPrice === 0 ? (
                            <span className="font-bold text-green-400 whitespace-nowrap">
                              Zdarma
                            </span>
                          ) : (
                            <span className="font-bold text-luxury-gold whitespace-nowrap">
                              +{shippingPrice} Kč
                            </span>
                          )}
                        </div>
                      </>
                    )}
                    {isGiftWrapped && (
                      <div className="flex justify-between items-center text-base">
                        <span className="text-luxury-light font-bold">
                          Dárkové balení:
                        </span>
                        <span className="font-bold text-luxury-gold whitespace-nowrap">
                          +{GIFT_WRAP_PRICE} Kč
                        </span>
                      </div>
                    )}
                    {voucherDiscount > 0 && (
                      <div className="flex justify-between items-center text-base">
                        <span className="text-luxury-light font-bold">
                          Sleva:
                        </span>
                        <span className="font-bold text-green-400 whitespace-nowrap">
                          -{actualDiscount.toFixed(2)} Kč
                        </span>
                      </div>
                    )}

                    <div className="flex justify-between items-center pt-3 border-t border-luxury-gold/20">
                      <span className="text-luxury-light text-lg font-bold">
                        CELKEM:
                      </span>
                      <span className="text-4xl font-aptos font-black text-luxury-gold whitespace-nowrap">
                        {Number(finalTotal - actualDiscount).toFixed(2)} Kč
                      </span>
                    </div>
                  </div>
                </div>

                {/* Order Button */}
                <button
                  onClick={handleOrder}
                  disabled={isProcessing}
                  className="w-full bg-luxury-gold text-luxury-dark px-4 py-4 md:py-5 rounded-sm font-black text-base md:text-lg uppercase tracking-widest hover:bg-yellow-300 transition-all duration-300 active:scale-95 shadow-lg disabled:opacity-50 disabled:cursor-not-allowed mb-6"
                >
                  {isProcessing ? "Ověřuji cenu a dostupnost…" : "Objednat"}
                </button>
              </div>
            </div>
          )}
        </div>

        {stockError && (
          <div
            className="fixed inset-0 z-[10000] flex items-end justify-center bg-black/75 p-0 backdrop-blur-[3px] sm:items-center sm:p-6"
            role="presentation"
            onMouseDown={(event) => {
              if (event.target === event.currentTarget) setStockError(null);
            }}
          >
            <section
              role="alertdialog"
              aria-modal="true"
              aria-labelledby="stock-error-title"
              aria-describedby="stock-error-description"
              className="relative w-full overflow-hidden rounded-t-[28px] border border-luxury-gold/25 bg-[#11100e] px-5 pb-[max(1.5rem,env(safe-area-inset-bottom))] pt-6 text-left shadow-[0_30px_90px_rgba(0,0,0,0.65)] sm:max-w-[520px] sm:rounded-[28px] sm:px-9 sm:pb-9 sm:pt-8"
            >
              <div className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-luxury-gold to-transparent" />
              <div className="pointer-events-none absolute -right-16 -top-16 h-44 w-44 rounded-full bg-luxury-gold/10 blur-3xl" />

              <button
                ref={stockErrorCloseRef}
                type="button"
                onClick={() => setStockError(null)}
                className="absolute right-4 top-4 flex h-10 w-10 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-luxury-light/65 transition hover:border-luxury-gold/40 hover:bg-luxury-gold/10 hover:text-luxury-gold focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-luxury-gold sm:right-5 sm:top-5"
                aria-label="Zavřít upozornění"
              >
                <svg aria-hidden="true" viewBox="0 0 24 24" className="h-5 w-5" fill="none" stroke="currentColor" strokeWidth="1.8">
                  <path strokeLinecap="round" d="M6 6l12 12M18 6 6 18" />
                </svg>
              </button>

              <div className="mb-6 flex items-start gap-4 pr-11 sm:gap-5">
                <div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-luxury-gold/25 bg-luxury-gold/10 text-luxury-gold sm:h-14 sm:w-14">
                  <svg aria-hidden="true" viewBox="0 0 24 24" className="h-6 w-6 sm:h-7 sm:w-7" fill="none" stroke="currentColor" strokeWidth="1.7">
                    <path strokeLinecap="round" strokeLinejoin="round" d="M6.75 8.25V6.75a5.25 5.25 0 0110.5 0v1.5M5.25 8.25h13.5l-.75 12H6l-.75-12z" />
                    <path strokeLinecap="round" d="M12 11.5v3M12 17.25h.01" />
                  </svg>
                </div>
                <div>
                  <p className="mb-1.5 text-[11px] font-bold uppercase tracking-[0.22em] text-luxury-gold/80">
                    Změna dostupnosti
                  </p>
                  <h2 id="stock-error-title" className="font-aptos text-2xl font-black leading-tight text-luxury-light sm:text-[28px]">
                    Produkt už není skladem
                  </h2>
                </div>
              </div>

              <p id="stock-error-description" className="mb-7 text-[15px] leading-6 text-luxury-light/70 sm:text-base sm:leading-7">
                {stockError.message}
              </p>

              <div className="flex flex-col gap-3 sm:flex-row-reverse">
                {stockError.variantId && (
                  <button
                    type="button"
                    onClick={async () => {
                      await removeItem(stockError.variantId!);
                      setStockError(null);
                    }}
                    className="min-h-12 flex-1 rounded-xl bg-luxury-gold px-5 py-3 text-sm font-black uppercase tracking-[0.12em] text-luxury-dark shadow-[0_12px_30px_rgba(243,189,53,0.16)] transition hover:bg-yellow-300 active:scale-[0.98]"
                  >
                    Odebrat z košíku
                  </button>
                )}
                <button
                  type="button"
                  onClick={() => setStockError(null)}
                  className="min-h-12 flex-1 rounded-xl border border-luxury-gold/35 bg-transparent px-5 py-3 text-sm font-bold text-luxury-light transition hover:border-luxury-gold/70 hover:bg-luxury-gold/[0.07] active:scale-[0.98]"
                >
                  Zpět do košíku
                </button>
              </div>
            </section>
          </div>
        )}
      </div>
    </>
  );
};

export default Cart;
