"use client";

import React, { useState, useEffect } from "react";
import { Plus, Minus, ShoppingBag, X, Send, Sparkles, Image as ImageIcon, ArrowUpRight, Trash2 } from "lucide-react";
import { MenuItem, Category } from "@/types";
import { useSiteSettings } from "@/components/SettingsProvider";
import { BUSINESS_CONFIG, getWhatsAppUrl } from "@/config/business";

interface CartItem {
  item: MenuItem;
  quantity: number;
}

interface CategoryGroup {
  slug: string;
  name: string;
  image?: string | null;
  items: MenuItem[];
}

export default function MenuPublicPage() {
  const { enable_promotions, use_category_images } = useSiteSettings();
  const [menu, setMenu] = useState<MenuItem[]>([]);
  const [categoriesList, setCategoriesList] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState("all");

  // Cart State
  const [cart, setCart] = useState<CartItem[]>([]);
  const [cartModalOpen, setCartModalOpen] = useState(false);
  const [customerName, setCustomerName] = useState("");
  const [customerAddress, setCustomerAddress] = useState("");
  const availableSectors = BUSINESS_CONFIG.coverage.sectors.filter((s) => s.enabled !== false);
  const [customerNeighborhood, setCustomerNeighborhood] = useState(
    availableSectors[0]?.name || BUSINESS_CONFIG.location.sector || "Galicia"
  );
  const availablePaymentMethods = BUSINESS_CONFIG.paymentMethods.filter((pm) => pm.enabled !== false);
  const [paymentMethod, setPaymentMethod] = useState(
    availablePaymentMethods[0]?.value || "Transferencia Nequi"
  );
  const [customerNotes, setCustomerNotes] = useState("");

  useEffect(() => {
    Promise.all([
      fetch("/api/menu").then((res) => res.json()),
      fetch("/api/categories").then((res) => res.json()),
    ])
      .then(([menuData, catData]) => {
        setMenu(menuData || []);
        setCategoriesList(Array.isArray(catData) ? catData : []);
        setLoading(false);
      })
      .catch((err) => {
        console.error("Error loading menu or categories:", err);
        setLoading(false);
      });
  }, []);

  const addToCart = (item: MenuItem) => {
    setCart((prev) => {
      const existing = prev.find((ci) => ci.item.id === item.id);
      if (existing) {
        return prev.map((ci) =>
          ci.item.id === item.id ? { ...ci, quantity: ci.quantity + 1 } : ci
        );
      }
      return [...prev, { item, quantity: 1 }];
    });
  };

  const removeFromCart = (itemId: number) => {
    setCart((prev) => {
      const existing = prev.find((ci) => ci.item.id === itemId);
      if (!existing) return prev;
      if (existing.quantity <= 1) {
        return prev.filter((ci) => ci.item.id !== itemId);
      }
      return prev.map((ci) =>
        ci.item.id === itemId ? { ...ci, quantity: ci.quantity - 1 } : ci
      );
    });
  };

  const clearCart = () => {
    if (confirm("¿Estás seguro de que deseas eliminar todo el pedido?")) {
      setCart([]);
      setCartModalOpen(false);
    }
  };

  const getItemQuantity = (itemId: number) => {
    return cart.find((ci) => ci.item.id === itemId)?.quantity || 0;
  };

  const totalItemsCount = cart.reduce((sum, ci) => sum + ci.quantity, 0);
  const totalPrice = cart.reduce((sum, ci) => sum + Number(ci.item.price) * ci.quantity, 0);

  useEffect(() => {
    if (totalItemsCount > 0) {
      document.body.classList.add("cart-active");
    } else {
      document.body.classList.remove("cart-active");
    }
    return () => {
      document.body.classList.remove("cart-active");
    };
  }, [totalItemsCount]);

  // Filter items if promotions are disabled
  const filteredMenu = menu.filter((item) => {
    if (!enable_promotions) {
      const cat = (item.category || "").toLowerCase();
      const title = (item.title || "").toLowerCase();
      if (cat.includes("promo") || cat.includes("oferta") || title.includes("combo promo")) {
        return false;
      }
    }
    return true;
  });

  // Build ordered category groups based on DB categories order
  const categoryGroups: CategoryGroup[] = [];
  const handledCategorySlugs = new Set<string>();

  categoriesList.forEach((cat) => {
    const items = filteredMenu.filter(
      (item) => item.category?.toLowerCase() === cat.slug.toLowerCase()
    );
    if (items.length > 0) {
      categoryGroups.push({
        slug: cat.slug,
        name: cat.name,
        image: cat.image,
        items,
      });
      handledCategorySlugs.add(cat.slug.toLowerCase());
    }
  });

  // Fallback for items with categories not defined in DB categories
  filteredMenu.forEach((item) => {
    const catSlug = (item.category || "otros").toLowerCase();
    if (!handledCategorySlugs.has(catSlug)) {
      let existingGroup = categoryGroups.find((g) => g.slug === catSlug);
      if (!existingGroup) {
        existingGroup = {
          slug: catSlug,
          name: catSlug.charAt(0).toUpperCase() + catSlug.slice(1),
          image: null,
          items: [],
        };
        categoryGroups.push(existingGroup);
        handledCategorySlugs.add(catSlug);
      }
      existingGroup.items.push(item);
    }
  });

  const displayedGroups =
    activeCategory === "all"
      ? categoryGroups
      : categoryGroups.filter((g) => g.slug.toLowerCase() === activeCategory.toLowerCase());

  const handleCheckoutWhatsApp = (e: React.FormEvent) => {
    e.preventDefault();
    if (cart.length === 0) return;

    let itemsList = "";
    cart.forEach((ci) => {
      itemsList += `• ${ci.quantity}x ${ci.item.title} ($${Number(ci.item.price).toLocaleString("es-CO")})\n`;
    });

    const msg =
      `¡Hola Sanlore Pizza! 🍕 Quiero pedir este domicilio artesanal:\n\n` +
      `📋 *PEDIDO ARTESANAL:*\n${itemsList}\n` +
      `💰 *Total:* $${totalPrice.toLocaleString("es-CO")} COP\n\n` +
      `👤 *Nombre:* ${customerName}\n` +
      `📍 *Dirección:* ${customerAddress} (${customerNeighborhood})\n` +
      `💳 *Método de Pago:* ${paymentMethod}\n` +
      (customerNotes.trim() ? `📝 *Notas:* ${customerNotes}\n` : "") +
      `\n¿Me confirman tiempo estimado de entrega a Galicia/Pereira?`;

    const waUrl = getWhatsAppUrl(msg);
    window.open(waUrl, "_blank");
    setCartModalOpen(false);
  };

  return (
    <div className="max-w-7xl mx-auto px-6 sm:px-8 lg:px-12 py-16 md:py-24 space-y-16 bg-[#F7F5F0]">
      {/* Header with increased spaciousness */}
      <div className="text-center max-w-2xl mx-auto space-y-4">
        <span className="inline-flex items-center gap-1.5 px-3.5 py-1 rounded-[6px] text-xs font-black bg-[#67d2f2] text-[#083F78] uppercase tracking-wider font-artisan-sans">
          <Sparkles size={13} />
          <span>Masa Madre 48h • Horno Tipo Siciliano</span>
        </span>
        <h1 className="text-3xl sm:text-5xl font-artisan-serif font-bold text-[#083F78] tracking-tight">
          Menú & Carta Artesanal
        </h1>
        <p className="text-xs sm:text-sm text-[#2b394a]/80 font-artisan-sans max-w-lg mx-auto leading-relaxed">
          Pizzas artesanales de fermentación lenta por 48 horas, preparadas con ingredientes frescos de primera calidad y horneadas en horno tipo siciliano. Añade tus platos y consolida tu pedido directo a WhatsApp.
        </p>
      </div>

      {/* Category Navigation - Minimal Sharp Tags */}
      {categoryGroups.length > 0 && (
        <div className="flex gap-2.5 overflow-x-auto pb-3 scrollbar-none justify-start sm:justify-center border-b border-[#a1a39e]/20">
          <button
            onClick={() => setActiveCategory("all")}
            className={`px-5 py-2 rounded-[8px] text-xs uppercase tracking-wider font-bold whitespace-nowrap transition-all duration-150 ${
              activeCategory === "all"
                ? "bg-[#083F78] text-white"
                : "bg-white text-[#083F78] border border-[#a1a39e]/25 hover:border-[#083F78]"
            }`}
          >
            Todos los Platos
          </button>
          {categoryGroups.map((group) => (
            <button
              key={group.slug}
              onClick={() => setActiveCategory(group.slug)}
              className={`px-5 py-2 rounded-[8px] text-xs uppercase tracking-wider font-bold whitespace-nowrap transition-all duration-150 ${
                activeCategory.toLowerCase() === group.slug.toLowerCase()
                  ? "bg-[#083F78] text-white"
                  : "bg-white text-[#083F78] border border-[#a1a39e]/25 hover:border-[#083F78]"
              }`}
            >
              {group.name}
            </button>
          ))}
        </div>
      )}

      {/* Asymmetrical Block Grid for Menu Items */}
      {loading ? (
        <div className="text-center py-28 text-slate-400">
          <div className="w-8 h-8 border-3 border-[#67d2f2] border-t-transparent rounded-full animate-spin mx-auto mb-3"></div>
          <p className="text-xs uppercase tracking-wider font-artisan-sans text-[#2b394a]/70">Preparando carta artesanal...</p>
        </div>
      ) : (
        displayedGroups.map((group) => {
          const items = group.items;

          if (use_category_images) {
            return (
              <div key={group.slug} className="space-y-6">
                {/* Category Header Banner with Category Image */}
                <div className="relative rounded-[12px] overflow-hidden border border-[#a1a39e]/20 bg-white shadow-sm">
                  {group.image ? (
                    <div className="relative h-48 sm:h-64 w-full overflow-hidden bg-[#083F78]">
                      <img
                        src={group.image}
                        alt={group.name}
                        className="w-full h-full object-cover object-center"
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/85 via-black/40 to-black/10" />
                      <div className="absolute bottom-0 left-0 right-0 p-6 sm:p-8 text-white flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
                        <div>
                          <span className="inline-block px-2.5 py-0.5 rounded-[4px] text-[10px] font-black uppercase tracking-wider bg-[#ffc324] text-[#083F78] mb-2 font-artisan-sans">
                            Categoría Artesanal
                          </span>
                          <h2 className="text-2xl sm:text-4xl font-artisan-serif font-bold text-white drop-shadow-sm">
                            {group.name}
                          </h2>
                        </div>
                        <span className="text-xs font-mono text-white/90 bg-white/15 backdrop-blur-md px-3.5 py-1.5 rounded-full w-fit">
                          {items.length} opciones disponibles
                        </span>
                      </div>
                    </div>
                  ) : (
                    <div className="p-6 sm:p-8 bg-[#083F78] text-white flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                      <div>
                        <span className="inline-block px-2.5 py-0.5 rounded-[4px] text-[10px] font-black uppercase tracking-wider bg-[#ffc324] text-[#083F78] mb-2 font-artisan-sans">
                          Categoría
                        </span>
                        <h2 className="text-2xl sm:text-3xl font-artisan-serif font-bold text-white">
                          {group.name}
                        </h2>
                      </div>
                      <span className="text-xs font-mono text-white/90 bg-white/15 px-3.5 py-1.5 rounded-full w-fit">
                        {items.length} opciones
                      </span>
                    </div>
                  )}
                </div>

                {/* Editorial List of Dishes (Without individual dish images) */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 sm:gap-5">
                  {items.map((item) => {
                    const qty = getItemQuantity(item.id);
                    return (
                      <div
                        key={item.id}
                        className="bg-white border border-[#a1a39e]/20 rounded-[8px] p-5 sm:p-6 flex flex-col justify-between hover:border-[#083F78]/40 transition group"
                      >
                        <div className="space-y-2">
                          <div className="flex items-start justify-between gap-3">
                            <h3 className="font-artisan-serif font-bold text-[#083F78] text-lg sm:text-xl leading-tight">
                              {item.title}
                            </h3>
                            <span className="font-mono font-bold text-base sm:text-lg text-[#083F78] whitespace-nowrap">
                              ${Number(item.price).toLocaleString("es-CO")}
                            </span>
                          </div>
                          {item.description && (
                            <p className="text-xs sm:text-sm text-[#2b394a]/80 leading-relaxed font-artisan-sans">
                              {item.description}
                            </p>
                          )}
                        </div>

                        <div className="pt-4 mt-4 border-t border-[#a1a39e]/15 flex items-center justify-between">
                          <span className="text-[11px] font-artisan-sans font-semibold text-[#a1a39e] uppercase tracking-wider">
                            Horno Siciliano
                          </span>
                          {qty > 0 ? (
                            <div className="flex items-center gap-2 bg-[#F7F5F0] border border-[#a1a39e]/25 rounded-[8px] p-1">
                              <button
                                onClick={() => removeFromCart(item.id)}
                                className="w-8 h-8 rounded-[6px] bg-white text-[#083F78] flex items-center justify-center font-bold hover:bg-slate-100"
                              >
                                <Minus size={14} />
                              </button>
                              <span className="font-bold text-xs text-[#083F78] px-2">{qty}</span>
                              <button
                                onClick={() => addToCart(item)}
                                className="w-8 h-8 rounded-[6px] bg-[#ffc324] text-[#083F78] flex items-center justify-center font-black"
                              >
                                <Plus size={14} />
                              </button>
                            </div>
                          ) : (
                            <button
                              onClick={() => addToCart(item)}
                              className="inline-flex items-center gap-1.5 bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black px-4 py-2 rounded-[8px] text-xs uppercase tracking-wider transition shadow-sm shadow-[#ffc324]/20"
                            >
                              <Plus size={14} />
                              <span>Agregar</span>
                            </button>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            );
          }

          return (
            <div key={group.slug} className="space-y-8">
              <div className="flex items-center justify-between border-b border-[#a1a39e]/20 pb-3">
                <h2 className="text-2xl sm:text-3xl font-artisan-serif font-bold text-[#083F78]">
                  {group.name}
                </h2>
                <span className="text-xs font-mono text-[#a1a39e]">{items.length} opciones</span>
              </div>

              {/* Asymmetrical Block Grid (Editorial Layout with Varied Card Widths) */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-7">
                {items.map((item, index) => {
                  const qty = getItemQuantity(item.id);
                  const isFeatured = index % 4 === 0 && items.length > 2;

                  if (isFeatured) {
                    return (
                      <div
                        key={item.id}
                        className="md:col-span-2 bg-white border border-[#a1a39e]/20 rounded-[8px] overflow-hidden flex flex-col md:flex-row group transition hover:border-[#a1a39e]/40"
                      >
                        {item.image ? (
                          <div className="md:w-1/2 h-64 md:h-auto overflow-hidden bg-[#F7F5F0]">
                            <img
                              src={item.image}
                              alt={item.title}
                              className="w-full h-full object-cover group-hover:scale-105 transition duration-500"
                            />
                          </div>
                        ) : (
                          <div className="md:w-1/2 h-56 md:h-auto bg-[#F7F5F0] flex items-center justify-center text-[#a1a39e]">
                            <ImageIcon size={36} />
                          </div>
                        )}

                        <div className="md:w-1/2 p-7 md:p-9 flex flex-col justify-between space-y-6">
                          <div className="space-y-3">
                            <div className="flex items-center gap-2">
                              <span className="px-2 py-0.5 rounded-[4px] text-[10px] font-black uppercase tracking-wider bg-[#67d2f2]/20 text-[#083F78]">
                                Especialidad
                              </span>
                              <span className="px-2 py-0.5 rounded-[4px] text-[10px] font-bold uppercase tracking-wider bg-[#F7F5F0] text-[#a1a39e] border border-[#a1a39e]/20">
                                Masa Madre 48h
                              </span>
                            </div>

                            <h3 className="font-artisan-serif font-bold text-[#083F78] text-2xl leading-tight">
                              {item.title}
                            </h3>

                            <p className="text-xs sm:text-sm text-[#2b394a]/80 leading-relaxed font-artisan-sans">
                              {item.description || "Receta tradicional artesanal en horno tipo siciliano con ingredientes frescos de calidad."}
                            </p>
                          </div>

                          <div className="pt-4 border-t border-[#a1a39e]/15 flex items-center justify-between gap-4">
                            <span className="font-mono font-bold text-lg text-[#083F78]">
                              ${Number(item.price).toLocaleString("es-CO")}
                            </span>

                            {qty > 0 ? (
                              <div className="flex items-center gap-2 bg-[#F7F5F0] border border-[#a1a39e]/25 rounded-[8px] p-1">
                                <button
                                  onClick={() => removeFromCart(item.id)}
                                  className="w-8 h-8 rounded-[6px] bg-white text-[#083F78] flex items-center justify-center font-bold hover:bg-slate-100"
                                >
                                  <Minus size={14} />
                                </button>
                                <span className="font-bold text-xs text-[#083F78] px-2">{qty}</span>
                                <button
                                  onClick={() => addToCart(item)}
                                  className="w-8 h-8 rounded-[6px] bg-[#ffc324] text-[#083F78] flex items-center justify-center font-black"
                                >
                                  <Plus size={14} />
                                </button>
                              </div>
                            ) : (
                              <button
                                onClick={() => addToCart(item)}
                                className="inline-flex items-center gap-2 bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black px-6 py-2.5 rounded-[8px] text-xs uppercase tracking-wider transition shadow-sm shadow-[#ffc324]/20"
                              >
                                <Plus size={14} />
                                <span>Agregar</span>
                              </button>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  }

                  // Standard 1-column card with micro-radius 8px
                  return (
                    <div
                      key={item.id}
                      className="md:col-span-1 bg-white border border-[#a1a39e]/20 rounded-[8px] overflow-hidden flex flex-col justify-between group transition hover:border-[#a1a39e]/40"
                    >
                      <div>
                        {item.image ? (
                          <div className="h-52 overflow-hidden bg-[#F7F5F0]">
                            <img
                              src={item.image}
                              alt={item.title}
                              className="w-full h-full object-cover group-hover:scale-105 transition duration-500"
                            />
                          </div>
                        ) : (
                          <div className="h-44 bg-[#F7F5F0] flex items-center justify-center text-[#a1a39e]">
                            <ImageIcon size={30} />
                          </div>
                        )}

                        <div className="p-6 space-y-2.5">
                          <div className="flex items-start justify-between gap-2">
                            <h3 className="font-artisan-serif font-bold text-[#083F78] text-lg leading-tight">
                              {item.title}
                            </h3>
                            <span className="font-mono font-bold text-base text-[#083F78] whitespace-nowrap">
                              ${Number(item.price).toLocaleString("es-CO")}
                            </span>
                          </div>

                          {item.description && (
                            <p className="text-xs text-[#2b394a]/80 line-clamp-2 leading-relaxed font-artisan-sans">
                              {item.description}
                            </p>
                          )}
                        </div>
                      </div>

                      <div className="p-6 pt-0">
                        {qty > 0 ? (
                          <div className="flex items-center justify-between bg-[#F7F5F0] border border-[#a1a39e]/25 rounded-[8px] p-1.5">
                            <button
                              onClick={() => removeFromCart(item.id)}
                              className="w-8 h-8 rounded-[6px] bg-white text-[#083F78] flex items-center justify-center font-bold hover:bg-slate-100"
                            >
                              <Minus size={14} />
                            </button>
                            <span className="font-bold text-xs text-[#083F78]">{qty} en pedido</span>
                            <button
                              onClick={() => addToCart(item)}
                              className="w-8 h-8 rounded-[6px] bg-[#ffc324] text-[#083F78] flex items-center justify-center font-black"
                            >
                              <Plus size={14} />
                            </button>
                          </div>
                        ) : (
                          <button
                            onClick={() => addToCart(item)}
                            className="w-full inline-flex items-center justify-center gap-2 bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black py-3 rounded-[8px] text-xs uppercase tracking-wider transition shadow-sm shadow-[#ffc324]/20"
                          >
                            <Plus size={14} />
                            <span>Agregar al Pedido</span>
                          </button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })
      )}

      {/* Floating Bottom Cart Bar */}
      {totalItemsCount > 0 && (
        <div className="fixed bottom-4 sm:bottom-6 left-1/2 -translate-x-1/2 z-50 w-[calc(100%-1.5rem)] sm:w-11/12 max-w-lg">
          <div className="bg-[#083F78] text-[#F7F5F0] rounded-[8px] p-3.5 sm:p-4 border border-white/15 flex items-center justify-between gap-3 sm:gap-4 shadow-2xl">
            <div className="flex items-center gap-2.5 sm:gap-3">
              <div className="w-9 h-9 sm:w-10 sm:h-10 bg-[#67d2f2] text-[#083F78] rounded-[6px] flex items-center justify-center font-black shrink-0">
                <ShoppingBag size={18} />
              </div>
              <div>
                <div className="text-[11px] sm:text-xs text-[#a1a39e] font-artisan-sans uppercase tracking-wider font-semibold">
                  {totalItemsCount} {totalItemsCount === 1 ? "plato" : "platos"}
                </div>
                <div className="font-bold text-sm sm:text-base text-white font-mono">
                  ${totalPrice.toLocaleString("es-CO")} COP
                </div>
              </div>
            </div>

            <div className="flex items-center gap-2 shrink-0">
              <button
                type="button"
                onClick={clearCart}
                className="p-2 sm:px-3 sm:py-2 rounded-[8px] text-white/70 hover:text-rose-400 hover:bg-white/10 active:scale-95 transition flex items-center gap-1.5 text-xs font-semibold"
                title="Eliminar pedido completo"
                aria-label="Eliminar pedido"
              >
                <Trash2 size={15} />
                <span className="hidden sm:inline text-[11px]">Vaciar</span>
              </button>
              <button
                onClick={() => setCartModalOpen(true)}
                className="bg-[#ffc324] hover:bg-[#e8b01c] active:scale-95 text-[#083F78] font-black text-xs uppercase tracking-wider px-4 sm:px-5 py-2.5 rounded-[8px] transition flex items-center gap-1.5 shadow-md shadow-[#ffc324]/20"
              >
                <span>Ver Pedido</span>
                <ArrowUpRight size={14} />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* WhatsApp Checkout Modal */}
      {cartModalOpen && (
        <div className="fixed inset-0 z-50 bg-[#083F78]/80 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-[#F7F5F0] border border-[#a1a39e]/30 rounded-[8px] max-w-md w-full p-7 sm:p-8 max-h-[92vh] overflow-y-auto">
            <div className="flex items-center justify-between border-b border-[#a1a39e]/20 pb-4 mb-5">
              <h3 className="text-xl font-artisan-serif font-bold text-[#083F78]">
                Resumen de tu Pedido
              </h3>
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={clearCart}
                  className="inline-flex items-center gap-1 text-[11px] font-semibold text-rose-600 hover:text-rose-700 hover:bg-rose-50 px-2.5 py-1.5 rounded-[6px] transition border border-rose-200"
                  title="Eliminar todo el pedido"
                >
                  <Trash2 size={13} />
                  <span>Vaciar Pedido</span>
                </button>
                <button
                  onClick={() => setCartModalOpen(false)}
                  className="p-1.5 text-[#a1a39e] hover:text-[#083F78] transition"
                  title="Cerrar ventana"
                >
                  <X size={20} />
                </button>
              </div>
            </div>

            {/* Cart Items List */}
            <div className="divide-y divide-[#a1a39e]/15 max-h-48 overflow-y-auto mb-5 space-y-2 pr-1">
              {cart.map((ci) => (
                <div key={ci.item.id} className="pt-2 flex items-center justify-between text-xs">
                  <div>
                    <span className="font-bold text-[#083F78]">
                      {ci.quantity}x {ci.item.title}
                    </span>
                    <div className="text-[#a1a39e] font-mono">
                      ${(Number(ci.item.price) * ci.quantity).toLocaleString("es-CO")}
                    </div>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <button
                      onClick={() => removeFromCart(ci.item.id)}
                      className="w-6 h-6 rounded-[4px] bg-white border border-[#a1a39e]/30 text-[#083F78] flex items-center justify-center font-bold"
                    >
                      -
                    </button>
                    <span className="font-bold px-1 text-[#083F78]">{ci.quantity}</span>
                    <button
                      onClick={() => addToCart(ci.item)}
                      className="w-6 h-6 rounded-[4px] bg-[#67d2f2] text-[#083F78] flex items-center justify-center font-black"
                    >
                      +
                    </button>
                  </div>
                </div>
              ))}
            </div>

            <div className="bg-white border border-[#a1a39e]/20 rounded-[8px] p-4 flex justify-between items-center font-bold text-sm mb-5">
              <span className="text-[#083F78]">Total a Pagar:</span>
              <span className="text-[#083F78] font-mono text-base font-black">
                ${totalPrice.toLocaleString("es-CO")} COP
              </span>
            </div>

            {/* Delivery Data Form */}
            <form onSubmit={handleCheckoutWhatsApp} className="space-y-3.5 font-artisan-sans">
              <div>
                <label className="block text-xs font-bold uppercase tracking-wider text-[#083F78] mb-1">Nombre Completo</label>
                <input
                  type="text"
                  placeholder="Ej. Juan Gómez"
                  value={customerName}
                  onChange={(e) => setCustomerName(e.target.value)}
                  className="w-full bg-white border border-[#a1a39e]/30 rounded-[8px] p-2.5 text-xs text-[#083F78] focus:outline-none focus:border-[#67d2f2]"
                  required
                />
              </div>

              <div>
                <label className="block text-xs font-bold uppercase tracking-wider text-[#083F78] mb-1">Dirección de Domicilio</label>
                <input
                  type="text"
                  placeholder="Ej. Cra 15 # 20-30, Casa 12 / Apto 402"
                  value={customerAddress}
                  onChange={(e) => setCustomerAddress(e.target.value)}
                  className="w-full bg-white border border-[#a1a39e]/30 rounded-[8px] p-2.5 text-xs text-[#083F78] focus:outline-none focus:border-[#67d2f2]"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-2.5">
                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-[#083F78] mb-1">Sector / Barrio</label>
                  <select
                    value={customerNeighborhood}
                    onChange={(e) => setCustomerNeighborhood(e.target.value)}
                    className="w-full bg-white border border-[#a1a39e]/30 rounded-[8px] p-2.5 text-xs text-[#083F78] focus:outline-none focus:border-[#67d2f2]"
                  >
                    {availableSectors.map((sec, idx) => (
                      <option key={idx} value={sec.name}>
                        {sec.name}
                      </option>
                    ))}
                    <option value="Otro sector">Otro sector</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold uppercase tracking-wider text-[#083F78] mb-1">Método de Pago</label>
                  <select
                    value={paymentMethod}
                    onChange={(e) => setPaymentMethod(e.target.value)}
                    className="w-full bg-white border border-[#a1a39e]/30 rounded-[8px] p-2.5 text-xs text-[#083F78] focus:outline-none focus:border-[#67d2f2]"
                  >
                    {availablePaymentMethods.map((pm) => (
                      <option key={pm.id} value={pm.value}>
                        {pm.name}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div>
                <label className="block text-xs font-bold uppercase tracking-wider text-[#083F78] mb-1">Notas especiales (Opcional)</label>
                <input
                  type="text"
                  placeholder="Ej. Masa bien tostada, timbre dañado..."
                  value={customerNotes}
                  onChange={(e) => setCustomerNotes(e.target.value)}
                  className="w-full bg-white border border-[#a1a39e]/30 rounded-[8px] p-2.5 text-xs text-[#083F78] focus:outline-none focus:border-[#67d2f2]"
                />
              </div>

              <button
                type="submit"
                className="w-full mt-3 bg-[#ffc324] hover:bg-[#e8b01c] text-[#083F78] font-black py-4 rounded-[8px] text-xs uppercase tracking-wider transition flex items-center justify-center gap-2 shadow-md shadow-[#ffc324]/20"
              >
                <Send size={15} />
                <span>Enviar Pedido a WhatsApp</span>
              </button>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
