import React, { useState, useEffect, useMemo, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { collection, query as firestoreQuery, where, getDocs, orderBy, limit, addDoc, updateDoc, doc, serverTimestamp } from 'firebase/firestore';
import { db } from "../firebase/config";
import { useShop } from '../context/ShopContext';
import { useFavicon } from '../hooks/useFavicon';
import { formatPrice } from '../utils/pricing';
import SectionRenderer from '../components/builder/SectionRenderer';
import { PageLoader } from '../components/PageLoader';
import { motion, AnimatePresence } from 'framer-motion';
import {
    Plus, Minus, Search, ShoppingBag, Menu, X, Instagram as InstagramIcon,
    Phone as PhoneIcon, MapPin as MapPinIcon, Clock as ClockIcon,
    ChevronRight, CheckCircle2, Loader2, Flame, User, MapPin, Phone
} from 'lucide-react';

const slugify = (text) => {
    return text.toString().toLowerCase()
        .normalize("NFD").replace(/[\u0300-\u036f]/g, "")
        .replace(/\s+/g, '-')
        .replace(/[^\w\-]+/g, '')
        .replace(/\-\-+/g, '-')
        .replace(/^-+/, '')
        .replace(/-+$/, '');
};

const getOptimizedUrl = (url, w) => {
    if (!url) return '';
    // Skip placeholder or base64
    if (url.includes('via.placeholder') || url.startsWith('data:')) return url;
    
    // Using a high-performance, globally cached proxy for dynamic resizing.
    // This allows serving 300px images to mobile users instead of original 3MB files.
    const width = w || 800; // Default reasonable resolution
    return `https://images.weserv.nl/?url=${encodeURIComponent(url)}&w=${width}&output=webp&q=82`;
};

function WhatsappIcon({ size = 24, className = "" }) {
    return (
        <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="currentColor" className={className}>
            <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.894-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.017-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.248-.695.248-1.29.173-1.414z" />
        </svg>
    );
}

const ProductMedia = ({ src, alt, className = "", loading = "lazy", fetchpriority = "auto", width = 400 }) => {
    const [loaded, setLoaded] = useState(false);
    const isVideo = src?.toLowerCase().match(/\.(mp4|webm|mov)$/);

    if (isVideo) {
        return (
            <div className={`relative w-full h-full bg-gray-100 ${className}`}>
                <video
                    src={src}
                    className={`w-full h-full object-cover transition-opacity duration-300 ${loaded ? 'opacity-100' : 'opacity-0'}`}
                    autoPlay loop muted playsInline
                    onLoadedData={() => setLoaded(true)}
                />
                {!loaded && <div className="absolute inset-0 animate-pulse bg-gray-200" />}
            </div>
        );
    }

    const optimizedSrc = src ? getOptimizedUrl(src, width) : 'https://via.placeholder.com/300';

    return (
        <div className={`relative w-full h-full bg-gray-50 overflow-hidden ${className}`}>
            <img
                src={optimizedSrc}
                alt={alt}
                className={`w-full h-full object-cover transition-opacity duration-500 scale-100 group-hover:scale-110 ${loaded ? 'opacity-100' : 'opacity-0'}`}
                onLoad={() => setLoaded(true)}
                loading={loading}
                fetchpriority={fetchpriority}
            />
            {!loaded && (
                <div className="absolute inset-0 bg-gray-100 animate-pulse flex items-center justify-center">
                   <div className="w-full h-full bg-gradient-to-br from-gray-50 via-gray-100 to-gray-200 animate-shimmer" style={{ backgroundSize: '200% 100%' }} />
                </div>
            )}
        </div>
    );
};

const THEMES = {
    light: { bg: 'bg-gray-50', text: 'text-gray-900', card: 'bg-white', border: 'border-gray-200', primary: 'bg-orange-600', accent: 'text-orange-600' },
    dark: { bg: 'bg-gray-900', text: 'text-white', card: 'bg-gray-800', border: 'border-gray-700', primary: 'bg-orange-500', accent: 'text-orange-400' },
    "dark-pro": { bg: 'bg-[#0a0a0b]', text: 'text-white', card: 'bg-[#18181b]', border: 'border-white/5', primary: 'bg-[#ea580c]', accent: 'text-[#ea580c]' },
    elegant: { bg: 'bg-slate-50', text: 'text-slate-800', card: 'bg-white', border: 'border-slate-200', primary: 'bg-black', accent: 'text-black' },
    midnight: { bg: 'bg-[#0f172a]', text: 'text-slate-100', card: 'bg-[#1e293b]', border: 'border-slate-700', primary: 'bg-indigo-500', accent: 'text-indigo-400' },
};

const CartButton = ({ cartCount, onClick, isAnimatingCart }) => (
    <button
        onClick={onClick}
        className={`bg-white text-gray-900 hover:bg-orange-50 p-3 rounded-full shadow-xl transition-all active:scale-95 flex items-center justify-center gap-2 group ring-1 ring-gray-100 ${isAnimatingCart ? 'scale-110 ring-orange-400 ring-2' : ''}`}
    >
        <div className="relative">
            <ShoppingBag size={24} className={`text-gray-900 group-hover:text-orange-600 transition-colors ${isAnimatingCart ? 'text-orange-600' : ''}`} />
            {cartCount > 0 && <span className="absolute -top-2 -right-2 bg-orange-600 text-white text-[10px] font-bold w-5 h-5 flex items-center justify-center rounded-full border-2 border-white shadow-sm">{cartCount}</span>}
        </div>
        <span className="font-bold text-sm hidden md:block text-gray-900">Tu Pedido</span>
    </button>
);

const GlobalStyles = () => (
    <style>{`
        ::-webkit-scrollbar { width: 6px; height: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: rgba(0, 0, 0, 0.1); border-radius: 10px; }
        ::-webkit-scrollbar-thumb:hover { background: rgba(249, 115, 22, 0.4); }
        .scrollbar-pro::-webkit-scrollbar { width: 4px; }
        .scrollbar-pro::-webkit-scrollbar-thumb { background: #f97316; }
        @keyframes heartbeat {
            0% { transform: scale(1); }
            14% { transform: scale(1.3); }
            28% { transform: scale(1); }
            42% { transform: scale(1.3); }
            70% { transform: scale(1); }
        }
        .animate-heartbeat {
            animation: heartbeat 1.5s ease-in-out infinite;
        }
        @keyframes shimmer {
            0% { background-position: -200% 0; }
            100% { background-position: 200% 0; }
        }
        .animate-shimmer {
            background: linear-gradient(90deg, #f3f4f6 25%, #e5e7eb 50%, #f3f4f6 75%);
            background-size: 200% 100%;
            animation: shimmer 2s infinite linear;
        }
    `}</style>
);

export default function StorefrontPage({ isCustom, customHostname }) {
    const { slug } = useParams();
    const navigate = useNavigate();
    const { cart, cartCount, cartTotal, removeFromCart, addToCart, clearCart, setActiveCompanyId, isCartOpen, setIsCartOpen } = useShop();

    const getCached = (key) => {
        try {
            const data = localStorage.getItem(`cache_${slug || 'domain'}_${key}`);
            return data ? JSON.parse(data) : null;
        } catch (e) { return null; }
    };

    const setCached = (key, data) => {
        try {
            localStorage.setItem(`cache_${slug || 'domain'}_${key}`, JSON.stringify(data));
        } catch (e) {}
    };

    const [company, setCompany] = useState(() => getCached('company'));
    const [products, setProducts] = useState(() => getCached('products') || []);
    const [categories, setCategories] = useState(() => getCached('categories') || []);
    const [loading, setLoading] = useState(!getCached('company'));
    const [activeCategory, setActiveCategory] = useState(null);
    const [searchTerm, setSearchTerm] = useState('');
    const [promoPopupOpen, setPromoPopupOpen] = useState(false);
    const [isAnimatingCart, setIsAnimatingCart] = useState(false);
    const [isCheckoutOpen, setIsCheckoutOpen] = useState(false);
    const [orderSuccess, setOrderSuccess] = useState(false);
    const [customerInfo, setCustomerInfo] = useState({ name: '', phone: '', note: '', type: 'table', address: '' });
    const [isProcessing, setIsProcessing] = useState(false);
    const productListRef = useRef(null);

    useFavicon(company?.logo || '/logo.svg');

    useEffect(() => {
        const savedScroll = sessionStorage.getItem(`scroll_${slug}_${activeCategory}`);
        if (savedScroll && productListRef.current) {
            setTimeout(() => {
                productListRef.current.scrollTo({ top: parseInt(savedScroll), behavior: 'instant' });
            }, 100);
        }
    }, [activeCategory, slug]);

    const handleProductClick = (product) => {
        if (productListRef.current) {
            sessionStorage.setItem(`scroll_${slug}_${activeCategory}`, productListRef.current.scrollTop);
        }
        const productUrl = isCustom ? `/menu/p/${slugify(product.name)}` : `/menu/${slug || company.slug}/p/${slugify(product.name)}`;
        navigate(productUrl, { state: { productId: product.id } });
    };

    useEffect(() => {
        if (cartCount > 0) {
            setIsAnimatingCart(true);
            const timer = setTimeout(() => setIsAnimatingCart(false), 300);
            return () => clearTimeout(timer);
        }
    }, [cartCount]);

    const theme = useMemo(() => {
        const style = company?.theme?.themeStyle || 'light';
        return THEMES[style] || THEMES['light'];
    }, [company]);

    useEffect(() => {
        const fetchData = async () => {
            try {
                let companyData = null;
                const cleanHostname = (customHostname || window.location.hostname).toLowerCase().trim();
                const noWww = cleanHostname.replace(/^www\./, '');
                const withWww = `www.${noWww}`;
                const domainVariants = [cleanHostname, noWww, withWww].filter((v, i, a) => v && a.indexOf(v) === i);

                const useHostnameMatch = isCustom || (!cleanHostname.includes('menu-app-master') && !cleanHostname.includes('web.app') && !cleanHostname.includes('localhost'));

                if (useHostnameMatch && domainVariants.length > 0) {
                    const domainSnap = await getDocs(firestoreQuery(collection(db, "companies"), where("customDomain", "in", domainVariants), limit(1)));
                    if (!domainSnap.empty) {
                        companyData = { id: domainSnap.docs[0].id, ...domainSnap.docs[0].data() };
                    }
                }

                if (!companyData && slug) {
                    const compSnap = await getDocs(firestoreQuery(collection(db, "companies"), where("slug", "==", slug), limit(1)));
                    if (!compSnap.empty) {
                        companyData = { id: compSnap.docs[0].id, ...compSnap.docs[0].data() };
                    }
                }
                
                if (!companyData) { setLoading(false); return; }

                setCompany(companyData);
                setCached('company', companyData);
                setActiveCompanyId(companyData.id);

                const catQuery = firestoreQuery(collection(db, "categories"), where("companyId", "==", companyData.id), orderBy("order", "asc"));
                const catSnap = await getDocs(catQuery);
                const cats = catSnap.docs.map(d => ({ id: d.id, ...d.data() }));
                setCategories(cats);
                setCached('categories', cats);
                if (cats.length > 0 && !activeCategory) setActiveCategory(cats[0].id);

                const prodQuery = firestoreQuery(collection(db, "products"), where("companyId", "==", companyData.id), orderBy("order", "asc"));
                const prodSnap = await getDocs(prodQuery);
                const prods = prodSnap.docs.map(d => ({ id: d.id, ...d.data() }));
                setProducts(prods);
                setCached('products', prods);

                if (companyData.promos?.welcome) setTimeout(() => setPromoPopupOpen(true), 2000);
            } catch (err) { console.error(err); } finally { setLoading(false); }
        };
        fetchData();
    }, [slug, isCustom, customHostname, setActiveCompanyId]);

    const templateId = company?.theme?.templateId || 'classic';

    const businessStatus = useMemo(() => {
        if (!company?.openingHours) return { isOpen: false, text: 'Consultar horario' };
        const now = new Date();
        const days = ['domingo', 'lunes', 'martes', 'miercoles', 'jueves', 'viernes', 'sabado'];
        const schedule = company.openingHours[days[now.getDay()]];
        if (!schedule || schedule.isClosed) return { isOpen: false, text: 'Cerrado hoy' };

        const currentMinutes = now.getHours() * 60 + now.getMinutes();
        const [openH, openM] = schedule.open.split(':').map(Number);
        const [closeH, closeM] = schedule.close.split(':').map(Number);
        let openMinutes = openH * 60 + openM;
        let closeMinutes = closeH * 60 + closeM;
        if (closeMinutes < openMinutes) closeMinutes += 24 * 60;

        let currentMinutesAdjusted = currentMinutes;
        if (currentMinutes < openMinutes && currentMinutes < closeH * 60 + closeM) currentMinutesAdjusted += 24 * 60;

        if (currentMinutesAdjusted >= openMinutes && currentMinutesAdjusted < closeMinutes) {
            const timeString = new Intl.DateTimeFormat('es-CO', { hour: 'numeric', minute: '2-digit', hour12: true }).format(new Date().setHours(closeH, closeM));
            return { isOpen: true, text: `Abierto • Cierra ${timeString} ` };
        }
        return { isOpen: false, text: 'Cerrado' };
    }, [company]);

    const handleProcessOrder = async (e) => {
        e.preventDefault();
        if (!customerInfo.name || !customerInfo.phone) return alert("Por favor completa tu nombre y teléfono.");
        if (customerInfo.type === 'delivery' && !customerInfo.address) return alert("Por favor ingresa tu dirección.");

        setIsProcessing(true);
        try {
            const ordersRef = collection(db, "companies", company.id, "orders");
            const orderData = {
                customerName: customerInfo.name, customerPhone: customerInfo.phone, customerNote: customerInfo.note, orderType: customerInfo.type, address: customerInfo.address,
                items: cart.map(item => ({ id: item.id || '', name: item.name, qty: item.quantity, price: item.price, modifiers: item.modifiers || [], note: item.note || '', image: item.image || '' })),
                total: cartTotal, status: 'pending', createdAt: serverTimestamp()
            };

            const docRef = await addDoc(ordersRef, orderData);
            const orderId = docRef.id.slice(-5).toUpperCase();

            const customersRef = collection(db, "companies", company.id, "customers");
            const qCustomer = query(customersRef, where("phone", "==", customerInfo.phone), limit(1));
            const snapCustomer = await getDocs(qCustomer);

            if (snapCustomer.empty) {
                await addDoc(customersRef, { name: customerInfo.name, phone: customerInfo.phone, address: customerInfo.address || '', totalOrders: 1, totalSpent: cartTotal, lastOrderAt: serverTimestamp(), createdAt: serverTimestamp() });
            } else {
                const customerDoc = snapCustomer.docs[0];
                const currentData = customerDoc.data();
                await updateDoc(doc(db, "companies", company.id, "customers", customerDoc.id), { name: customerInfo.name, address: customerInfo.address || currentData.address, totalOrders: (currentData.totalOrders || 0) + 1, totalSpent: (currentData.totalSpent || 0) + cartTotal, lastOrderAt: serverTimestamp() });
            }

            let message = `*✨ NUEVO PEDIDO #${orderId} ✨*\n━━━━━━━━━━━━━━━━━\n👤 * CLIENTE:* ${customerInfo.name.toUpperCase()} \n📞 * TELÉFONO:* ${customerInfo.phone} \n📍 * TIPO:* ${customerInfo.type === 'table' ? '🍽️ EN LOCAL' : '🛵 DOMICILIO'} \n`;
            if (customerInfo.type === 'delivery' && customerInfo.address) message += `🏠 * DIRECCIÓN:* ${customerInfo.address} \n`;
            message += `━━━━━━━━━━━━━━━━━\n\n*🛒 DETALLE DEL PEDIDO:*\n`;
            cart.forEach(item => {
                message += `▪️ * ${item.quantity} x * ${item.name.toUpperCase()} \n   Subtotal: $${formatPrice(item.price * item.quantity)} \n`;
                if (item.note) message += `   📝 _"${item.note}"_\n`;
                message += `\n`;
            });
            message += `━━━━━━━━━━━━━━━━━\n💰 * TOTAL A PAGAR: $${formatPrice(cartTotal)}*\n━━━━━━━━━━━━━━━━━\n`;
            if (customerInfo.note) message += `\n💬 *COMENTARIOS:* _${customerInfo.note}_\n`;
            message += `\n⚡ *Gracias por tu preferencia!*`;

            setOrderSuccess(true);
            const waUrl = `https://api.whatsapp.com/send?phone=${company.socials.whatsapp}&text=${encodeURIComponent(message)}`;
            setTimeout(() => { window.location.href = waUrl; }, 2000);
        } catch (error) { console.error(error); alert("Error al procesar pedido."); } finally { setIsProcessing(false); }
    };

    const activeProducts = useMemo(() => {
        if (!activeCategory) return [];
        const activeCatData = categories.find(c => c.id === activeCategory);
        if (!activeCatData) return [];
        return products.filter(p => {
            const matchesCategory = p.categoryId === activeCategory || p.category === activeCategory || p.category === activeCatData.name;
            const matchesSearch = p.name.toLowerCase().includes(searchTerm.toLowerCase());
            return matchesCategory && matchesSearch;
        });
    }, [products, activeCategory, categories, searchTerm]);

    const activeCategoryData = categories.find(c => c.id === activeCategory);

    if (loading && !company) return <PageLoader />;
    if (!loading && !company) {
        return (
            <div className="min-h-screen bg-gray-50 flex flex-col items-center justify-center p-6 text-center text-gray-900 uppercase">
                <div className="w-24 h-24 bg-red-100 text-red-500 rounded-3xl flex items-center justify-center mb-6 shadow-xl shadow-red-200/50"><X size={48} /></div>
                <h1 className="text-3xl font-black italic tracking-tighter">Empresa No Encontrada</h1>
                <p className="text-gray-400 font-bold text-[10px] mt-2 mb-8 italic">El link utilizado parece no ser válido o la empresa no existe.</p>
                <button onClick={() => navigate('/')} className="bg-gray-900 text-white font-black px-8 py-4 rounded-2xl shadow-xl active:scale-95 transition-all italic tracking-tighter">Volver Al Inicio</button>
            </div>
        );
    }

    const renderHeader = () => (
        <header className={`${theme?.card || 'bg-white'} shadow-sm shrink-0 z-40 relative border-b ${theme?.border || 'border-gray-200'}`}>
            {(company.banner || company.bannerMobile) && (
                <div className="h-24 md:h-32 w-full overflow-hidden relative">
                    <picture>
                        {company.bannerMobile && <source media="(max-width: 640px)" srcSet={getOptimizedUrl(company.bannerMobile, 450, 800)} />}
                        <img src={getOptimizedUrl(company.banner || company.bannerMobile, 1200, 450)} className="w-full h-full object-cover" fetchpriority="high" loading="eager" alt="Banner" />
                    </picture>
                    <div className="absolute inset-0 bg-black/30"></div>
                </div>
            )}
            <div className="max-w-7xl mx-auto px-4 py-3 flex items-center justify-between -mt-10 relative z-10">
                <div className="flex items-center gap-4">
                    <motion.img initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} src={getOptimizedUrl(company.logo, 200)} onClick={() => navigate('/')} className="w-24 h-24 rounded-2xl shadow-2xl border-4 border-white bg-white object-cover cursor-pointer hover:scale-105 transition-transform" title="Ir al inicio" />
                    <div className="pt-8">
                        <h1 className="text-3xl font-black leading-tight text-white drop-shadow-lg">{company.name}</h1>
                        <span className={`inline-flex items-center gap-1 text-[10px] font-bold px-2 py-0.5 rounded-full ${businessStatus.isOpen ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400'} backdrop-blur-md border border-white/10 uppercase`}>
                            <ClockIconComp size={10} /> {businessStatus.text}
                        </span>
                    </div>
                </div>
                <div className="flex items-center gap-3 pt-8">
                    <div className="hidden sm:flex gap-2">
                        {company.socials?.instagram && <a href={`https://instagram.com/${company.socials.instagram}`} target="_blank" className="p-2.5 bg-white/10 text-white rounded-xl backdrop-blur-md"><InstagramIcon size={18} /></a>}
                        {company.socials?.whatsapp && <a href={`https://wa.me/${company.socials.whatsapp}`} target="_blank" className="p-2.5 bg-green-500/20 text-green-400 rounded-xl backdrop-blur-md"><WhatsappIconComp size={18} /></a>}
                    </div>
                    <CartButton cartCount={cartCount} onClick={() => setIsCartOpen(!isCartOpen)} isAnimatingCart={isAnimatingCart} />
                </div>
            </div>
        </header>
    );

    const TemplateClassic = () => (
        <div className={`flex-1 ${theme?.bg || 'bg-white'} min-h-screen flex flex-col`}>
            <div className="relative h-48 md:h-64 shrink-0">
                <picture>
                    {company.bannerMobile && <source media="(max-width: 640px)" srcSet={getOptimizedUrl(company.bannerMobile, 450, 800)} />}
                    <img src={getOptimizedUrl(company.banner || company.bannerMobile || company.cover || company.logo, 1000, 450)} className="w-full h-full object-cover" />
                </picture>
                <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/20 to-transparent"></div>
                <div className="absolute -bottom-10 left-6 right-6 flex items-end gap-4">
                    <div onClick={() => navigate('/')} className={`w-24 h-24 rounded-3xl border-4 border-white ${theme?.card || 'bg-white'} shadow-xl overflow-hidden shrink-0 cursor-pointer hover:scale-105 transition-transform`} title="Ir al inicio">
                        <img src={getOptimizedUrl(company.logo, 200)} className="w-full h-full object-cover" />
                    </div>
                    <div className="flex-1 pb-4 text-white">
                        <h2 className="text-2xl font-black italic tracking-tighter">{company.name}</h2>
                        <span className={`inline-flex items-center gap-1 text-[9px] font-bold px-2 py-0.5 rounded-full uppercase ${businessStatus.isOpen ? 'bg-green-500 text-white' : 'bg-red-500 text-white'}`}>
                            <ClockIconComp size={10} /> {businessStatus.isOpen ? 'Abierto' : 'Cerrado'}
                        </span>
                    </div>
                </div>
            </div>
            <div className={`mt-14 sticky top-0 z-[40] ${theme?.bg || 'bg-white/90'} backdrop-blur-md border-b border-gray-100 px-4 py-3 overflow-x-auto whitespace-nowrap scrollbar-hide`}>
                <div className="flex gap-2">
                    {categories.map(cat => (
                        <button key={cat.id} onClick={() => { setActiveCategory(cat.id); window.scrollTo({ top: 180, behavior: 'smooth' }); }} className={`px-5 py-2 rounded-full text-[10px] font-black uppercase tracking-widest ${activeCategory === cat.id ? 'bg-gray-900 text-white' : 'bg-gray-100 text-gray-500'}`}>{cat.name}</button>
                    ))}
                </div>
            </div>
            <main className="p-4 md:p-8 max-w-5xl mx-auto w-full">
                <div className="flex items-center justify-between mb-6">
                    <h3 className={`text-xl font-black italic uppercase ${theme?.text || 'text-gray-900'}`}>{activeCategoryData?.name}</h3>
                    <div className="relative w-32 md:w-48">
                        <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
                        <input type="text" placeholder="Buscar..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className={`w-full pl-8 pr-3 py-2 ${theme?.bg || 'bg-gray-50'} rounded-xl text-xs font-bold outline-none uppercase ${theme?.text || 'text-gray-900'}`} />
                    </div>
                </div>
                <AnimatePresence mode="wait">
                    <motion.div key={activeCategory} initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        {activeProducts.map((product, idx) => {
                            const hasDiscount = product.discountPercent > 0;
                            const finalPrice = hasDiscount ? product.price * (1 - product.discountPercent / 100) : product.price;
                            const isAboveFold = idx < 4;
                            return (
                                <div key={product.id} onClick={() => handleProductClick(product)} className={`flex gap-4 p-4 rounded-3xl ${theme?.card || 'bg-white'} border border-gray-100 shadow-sm cursor-pointer`}>
                                    <div className="flex-1 flex flex-col min-w-0">
                                        <h4 className={`font-black text-sm uppercase italic`}>{product.name}</h4>
                                        <p className="text-[10px] text-gray-400 line-clamp-2 mb-3 leading-relaxed">{product.desc}</p>
                                        <div className="mt-auto flex items-center justify-between">
                                            <span className="font-black text-lg">${formatPrice(finalPrice)}</span>
                                            <button onClick={(e) => { e.stopPropagation(); addToCart({ ...product, price: finalPrice }, 1); }} className="w-9 h-9 rounded-full bg-gray-100 flex items-center justify-center hover:bg-orange-600 hover:text-white transition-all"><Plus size={18} /></button>
                                        </div>
                                    </div>
                                    <div className="w-24 aspect-square rounded-2xl bg-gray-50 overflow-hidden shrink-0 shadow-inner">
                                        <ProductMedia 
                                            src={product.image} 
                                            alt={product.name} 
                                            loading={isAboveFold ? "eager" : "lazy"} 
                                            fetchpriority={isAboveFold ? "high" : "auto"} 
                                        />
                                    </div>
                                </div>
                            );
                        })}
                    </motion.div>
                </AnimatePresence>
                <div className="h-40"></div>
            </main>
        </div>
    );

    const TemplateModern = () => (
        <div className="flex-1 flex flex-col min-h-0 overflow-hidden uppercase">
            {renderHeader()}
            <main className="flex-1 flex flex-col min-h-0 bg-gray-50/50">
                <section className="h-[35%] flex flex-col border-b bg-white overflow-y-auto p-4 scrollbar-pro shrink-0">
                    <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-6 gap-3">
                        {categories.map(cat => (
                            <button key={cat.id} onClick={() => setActiveCategory(cat.id)} className={`relative aspect-[16/10] rounded-2xl overflow-hidden transition-all ${activeCategory === cat.id ? 'ring-4 ring-orange-500 scale-95' : 'opacity-70'}`}>
                                <img src={getOptimizedUrl(cat.image, 400)} className="absolute inset-0 w-full h-full object-cover" />
                                <div className="absolute inset-0 bg-black/40 flex items-center justify-center p-2"><h3 className="text-[10px] font-black italic text-white">{cat.name}</h3></div>
                            </button>
                        ))}
                    </div>
                </section>
                <section className="flex-1 flex flex-col min-h-0">
                    <div className="bg-white px-6 py-4 border-b flex items-center justify-between gap-6 shrink-0">
                        <h2 className="text-xl font-black italic">{activeCategoryData?.name}</h2>
                        <div className="relative w-48"><Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" /><input type="text" placeholder="BUSCAR..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="w-full pl-9 pr-4 py-2 bg-gray-100 rounded-xl text-[10px] font-bold outline-none" /></div>
                    </div>
                    <div ref={productListRef} className="flex-1 overflow-y-auto p-4 md:p-6 scrollbar-pro">
                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">{activeProducts.map(product => <ProductCard key={product.id} product={product} />)}</div>
                        <div className="h-32"></div>
                    </div>
                </section>
            </main>
        </div>
    );

    const TemplateColumns = () => (
        <div className="flex-1 flex flex-col uppercase">
            {renderHeader()}
            <main className="flex-1 grid grid-cols-1 lg:grid-cols-12 bg-gray-50/30">
                {/* Category sticky sidebar on mobile for < lg */}                <section className="hidden lg:block lg:col-span-8 border-r bg-white p-8">
                    <div className="grid grid-cols-2 xl:grid-cols-3 gap-6">
                        {categories.map(cat => (
                            <button key={cat.id} onClick={() => setActiveCategory(cat.id)} className={`relative aspect-square rounded-[2rem] overflow-hidden transition-all shadow-lg ${activeCategory === cat.id ? 'ring-8 ring-orange-500 scale-95' : 'hover:scale-[0.98]'}`}>
                                <img src={getOptimizedUrl(cat.image, 400)} className="absolute inset-0 w-full h-full object-cover" loading="lazy" width="400" height="400" />
                                <div className="absolute inset-0 bg-black/50 flex items-center justify-center p-4"><h3 className="text-2xl font-black text-white italic text-center tracking-tighter">{cat.name}</h3></div>
                            </button>
                        ))}
                    </div>
                </section>
                <section className="col-span-1 lg:col-span-4 flex flex-col lg:h-screen lg:sticky lg:top-0 bg-white shadow-2xl border-l">
                    <div className="lg:hidden shrink-0 bg-white/80 backdrop-blur-md border-b px-4 py-3 overflow-x-auto whitespace-nowrap scrollbar-hide z-20">
                        <div className="flex gap-2">
                            {categories.map(cat => (
                                <button key={cat.id} onClick={() => setActiveCategory(cat.id)} className={`px-4 py-1.5 rounded-full text-[9px] font-black ${activeCategory === cat.id ? 'bg-orange-600 text-white shadow-lg' : 'bg-gray-100 text-gray-400'}`}>{cat.name}</button>
                            ))}
                        </div>
                    </div>
                    <div className="p-6 border-b flex flex-col gap-4 shrink-0 bg-white z-10 text-gray-900 uppercase">
                        <div className="flex items-center justify-between"><h2 className="text-2xl font-black italic tracking-tighter">{activeCategoryData?.name || 'Selecciona'}</h2><span className="text-[10px] bg-gray-50 px-3 py-1 rounded-full opacity-50">{activeProducts.length} Items</span></div>
                        <div className="relative"><Search size={14} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500" /><input type="text" placeholder="Filtrar productos..." value={searchTerm} onChange={e => setSearchTerm(e.target.value)} className="w-full pl-10 pr-4 py-3 bg-gray-50 rounded-2xl text-[10px] font-bold outline-none" /></div>
                    </div>
                    <div ref={productListRef} className="flex-1 overflow-y-auto p-4 space-y-4 scrollbar-pro pb-32">
                        {activeProducts.length > 0 ? activeProducts.map((product, idx) => (
                            <ProductCard 
                                key={product.id} 
                                product={product} 
                                layout="list" 
                                loading={idx < 6 ? "eager" : "lazy"}
                                fetchpriority={idx < 6 ? "high" : "auto"}
                            />
                        )) : <div className="py-20 text-center opacity-30 italic font-black text-xs">Sin productos</div>}
                    </div>
                </section>
            </main>
        </div>
    );

    const TemplateNamastePro = () => {
        const container = { hidden: { opacity: 0 }, show: { opacity: 1, transition: { staggerChildren: 0.1 } } };
        const item = { hidden: { opacity: 0, y: 20 }, show: { opacity: 1, y: 0 } };
        return (
            <div className="min-h-screen bg-[#0a0a0b] text-white flex flex-col">
                <div className="relative h-40 md:h-56 shrink-0">
                    <img src={getOptimizedUrl(company.cover || company.banner || company.logo, 1000)} className="w-full h-full object-cover" />
                    <div className="absolute inset-0 bg-gradient-to-t from-[#0a0a0b]"></div>
                    <div className="absolute -bottom-2 left-6 right-6 flex items-end gap-4">
                        <div onClick={() => navigate('/')} className="w-20 h-20 rounded-2xl border-2 border-white/10 bg-[#121214] shadow-2xl overflow-hidden shrink-0 cursor-pointer hover:scale-105 transition-transform"><img src={getOptimizedUrl(company.logo, 200)} className="w-full h-full object-cover" /></div>
                        <div className="flex-1 pb-2"><h2 className="text-2xl font-black italic tracking-tighter uppercase">{company.name}</h2><span className={`inline-flex items-center gap-1 text-[9px] font-bold px-2 py-0.5 rounded-full uppercase ${businessStatus.isOpen ? 'text-green-400' : 'text-red-400'}`}><ClockIconComp size={10} /> {businessStatus.isOpen ? 'Abierto' : 'Cerrado'}</span></div>
                    </div>
                </div>
                <div className="sticky top-0 z-[50] bg-[#0a0a0b]/80 backdrop-blur-xl px-4 py-8">
                    <div className="max-w-4xl mx-auto flex items-center gap-3">
                        <div className="flex-1 relative"><Search size={18} className="absolute left-6 top-1/2 -translate-y-1/2 text-gray-500" /><input type="text" placeholder="Buscar..." value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} className="w-full bg-[#121214] text-white text-sm pl-14 pr-4 py-4 rounded-[1.2rem] outline-none" /></div>
                        <button onClick={() => setIsCartOpen(true)} className="w-14 h-14 bg-[#ea580c] rounded-2xl flex items-center justify-center relative"><ShoppingBag size={24} />{cartCount > 0 && <span className="absolute -top-2 -right-2 bg-white text-orange-600 text-[10px] font-black w-6 h-6 rounded-full flex items-center justify-center border-2 border-[#ea580c]">{cartCount}</span>}</button>
                    </div>
                </div>
                <main className="flex-1 max-w-4xl mx-auto w-full px-4 pb-32">
                    <motion.div variants={container} initial="hidden" animate="show" className="space-y-4 pt-4">
                        {categories.map(cat => (
                            <div key={cat.id} onClick={() => setActiveCategory(activeCategory === cat.id ? null : cat.id)} className={`rounded-[2rem] border transition-colors flex items-center gap-6 p-4 cursor-pointer ${activeCategory === cat.id ? 'bg-[#18181b] border-orange-600/30 shadow-2xl' : 'bg-[#121214] border-white/5'}`}>
                                <div className="w-20 aspect-square rounded-[1.5rem] overflow-hidden shrink-0 relative"><ProductMedia src={cat.image} alt={cat.name} width={200} />{activeCategory === cat.id && <div className="absolute inset-0 bg-orange-600/20" />}</div>
                                <h3 className={`flex-1 text-xl font-black italic tracking-tighter uppercase ${activeCategory === cat.id ? 'text-orange-500' : 'text-white'}`}>{cat.name}</h3>
                                {activeCategory === cat.id ? <Minus size={24} className="text-orange-500" /> : <Plus size={24} />}
                            </div>
                        ))}
                    </motion.div>
                    <AnimatePresence>
                        {activeCategory && (
                            <motion.div key={activeCategory} initial={{ opacity: 0, scale: 0.95 }} animate={{ opacity: 1, scale: 1 }} exit={{ opacity: 0, scale: 0.95 }} className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-8 pb-10">{activeProducts.map(product => <ProductCard key={product.id} product={product} />)}</motion.div>
                        )}
                    </AnimatePresence>
                </main>
            </div>
        );
    };

    const ProductCard = ({ product, layout = 'grid', loading = "lazy", fetchpriority = "auto" }) => {
        const hasDiscount = product.discountPercent > 0;
        const finalPrice = hasDiscount ? product.price * (1 - product.discountPercent / 100) : product.price;
        const isHot = product.isHot;
        if (layout === 'list') {
            return (
                <div onClick={() => handleProductClick(product)} className={`flex gap-4 p-3 rounded-3xl ${theme?.card || 'bg-white'} border cursor-pointer group active:scale-[0.98] transition-all relative ${isHot ? 'border-red-500 shadow-[0_0_20px_rgba(239,68,68,0.35)]' : `${theme?.border || 'border-gray-200'} shadow-sm`}`}>
                    <div className="w-20 aspect-square rounded-2xl overflow-hidden shrink-0">
                        <ProductMedia src={product.image} alt={product.name} loading={loading} fetchpriority={fetchpriority} />
                    </div>
                    {isHot && (
                        <div className="absolute -top-2 -right-1 z-30 bg-red-600 p-2 rounded-xl shadow-lg border-2 border-white animate-heartbeat">
                            <Flame size={20} className="text-white" fill="currentColor" />
                        </div>
                    )}
                    <div className="flex-1 flex flex-col py-0.5">
                        <h4 className={`font-black text-[11px] uppercase italic ${isHot ? 'text-red-500' : ''}`}>{product.name}</h4>
                        {isHot && <span className="text-[9px] font-black text-red-500 uppercase tracking-widest leading-none mb-1">🔥 Más pedido</span>}
                        <div className="mt-auto flex items-center justify-between"><div className="flex flex-col">{hasDiscount && <span className="text-[10px] text-gray-400 line-through leading-none opacity-50">${formatPrice(product.price)}</span>}<span className="font-black text-xl text-orange-600 leading-none">${formatPrice(finalPrice)}</span></div><button onClick={(e) => { e.stopPropagation(); addToCart({ ...product, price: finalPrice }, 1); }} className="w-10 h-10 rounded-full bg-orange-600 text-white flex items-center justify-center shadow-lg active:scale-90 transition-all"><Plus size={18} /></button></div>
                    </div>
                </div>
            );
        }
        return (
            <div onClick={() => handleProductClick(product)} className={`p-3 rounded-[2rem] ${theme?.card || 'bg-white'} border border-gray-100 shadow-sm transition-all cursor-pointer flex flex-col relative group ${isHot ? 'scale-[1.02] border-orange-500' : ''}`}>
                <div className="aspect-square rounded-2xl overflow-hidden relative mb-3">
                    <ProductMedia src={product.image} alt={product.name} loading={loading} fetchpriority={fetchpriority} />
                </div>
                {isHot && (
                    <div className="absolute top-0 right-1 z-30 bg-red-600 p-2.5 rounded-2xl shadow-xl border-2 border-white animate-heartbeat">
                        <Flame size={24} className="text-white" fill="currentColor" />
                    </div>
                )}
                <h4 className="font-black text-[10px] italic uppercase mb-2 h-8 line-clamp-2">{product.name}</h4>
                <div className="mt-auto flex items-center justify-between"><div className="flex flex-col">{hasDiscount && <span className="text-[10px] line-through text-gray-400">${formatPrice(product.price)}</span>}<span className="font-black text-xl text-orange-600">${formatPrice(finalPrice)}</span></div><button onClick={(e) => { e.stopPropagation(); addToCart({ ...product, price: finalPrice }, 1); }} className="w-10 h-10 rounded-full bg-orange-600 text-white flex items-center justify-center shadow-lg"><Plus size={18} /></button></div>
            </div>
        );
    };

    return (
        <SectionRenderer sections={company?.sections} company={company}>
            <div className={`min-h-screen ${templateId === 'classic' ? 'bg-white' : templateId === 'namaste-pro' ? 'h-[100dvh] overflow-hidden' : ''} ${theme?.bg || 'bg-gray-50'} ${theme?.text || 'text-gray-900'} font-sans flex flex-col uppercase`}>
                <GlobalStyles />
                {templateId === 'classic' ? TemplateClassic() : templateId === 'modern' ? TemplateModern() : templateId === 'namaste-pro' ? TemplateNamastePro() : TemplateColumns()}
                <AnimatePresence>
                    {isCartOpen && (
                        <>
                            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => setIsCartOpen(false)} className="fixed inset-0 bg-black/50 z-50 backdrop-blur-sm" />
                            <motion.div initial={{ x: '100%' }} animate={{ x: 0 }} exit={{ x: '100%' }} className="fixed top-0 right-0 bottom-0 w-full sm:w-[400px] bg-white z-[51] shadow-2xl flex flex-col">
                                <div className="p-6 border-b flex justify-between items-center bg-gray-50"><h2 className="text-xl font-bold flex items-center gap-2 text-gray-900 uppercase italic leading-none"><ShoppingBag /> Tu Pedido</h2><button onClick={() => setIsCartOpen(false)} className="p-2 bg-gray-200 rounded-full"><X size={20} className="text-gray-900" /></button></div>
                                <div className="flex-1 overflow-y-auto p-6 space-y-6">
                                    {cart.length === 0 ? <div className="text-center py-20 opacity-50 uppercase italic font-black text-gray-400">Carrito vacío</div> : cart.map((item, idx) => (
                                        <div key={idx} className="flex gap-4 border-b border-gray-50 pb-4">
                                            <div className="w-16 h-16 rounded-lg overflow-hidden shrink-0"><img src={item.image} className="w-full h-full object-cover" /></div>
                                            <div className="flex-1">
                                                <div className="flex justify-between items-start"><h3 className="font-bold text-sm text-gray-900 line-clamp-1">{item.name}</h3><button onClick={() => removeFromCart(idx)} className="text-gray-400 hover:text-red-500"><X size={14} /></button></div>
                                                <div className="text-xs text-gray-500 mt-1">{item.quantity} x ${formatPrice(item.price)}</div>
                                                <div className="font-bold text-sm mt-1 text-gray-900">${formatPrice(item.price * item.quantity)}</div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                                {cart.length > 0 && (
                                    <div className="p-6 border-t bg-gray-50 flex flex-col gap-3">
                                        <div className="flex justify-between items-baseline px-2"><span className="text-gray-400 font-black text-[10px] uppercase italic tracking-widest">Total</span><span className="text-2xl font-black italic text-gray-900">${formatPrice(cartTotal)}</span></div>
                                        <button onClick={() => setIsCheckoutOpen(true)} className="w-full bg-orange-600 text-white font-black py-4 rounded-2xl shadow-xl uppercase italic tracking-tighter">Continuar Al Pago <ChevronRight size={20} className="inline ml-1" /></button>
                                    </div>
                                )}
                            </motion.div>
                        </>
                    )}
                </AnimatePresence>
                <AnimatePresence>
                    {isCheckoutOpen && (
                        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4">
                            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} onClick={() => !orderSuccess && setIsCheckoutOpen(false)} className="absolute inset-0 bg-black/60 backdrop-blur-md" />
                            <motion.div initial={{ scale: 0.9 }} animate={{ scale: 1 }} exit={{ scale: 0.9 }} className="relative w-full max-w-lg bg-white rounded-[2.5rem] shadow-2xl overflow-hidden uppercase">
                                {!orderSuccess ? (
                                    <form onSubmit={handleProcessOrder} className="flex flex-col h-full">
                                        <div className="p-8 border-b flex justify-between items-center"><h2 className="text-2xl font-black italic tracking-tighter">Tu Información</h2><button type="button" onClick={() => setIsCheckoutOpen(false)}><X size={20} /></button></div>
                                        <div className="p-8 space-y-4 max-h-[60vh] overflow-y-auto">
                                            <input required type="text" placeholder="Nombre completo" value={customerInfo.name} onChange={e => setCustomerInfo({ ...customerInfo, name: e.target.value })} className="w-full px-4 py-4 bg-gray-50 rounded-2xl text-[10px] font-black outline-none" />
                                            <input required type="tel" placeholder="WhatsApp" value={customerInfo.phone} onChange={e => setCustomerInfo({ ...customerInfo, phone: e.target.value })} className="w-full px-4 py-4 bg-gray-50 rounded-2xl text-[10px] font-black outline-none" />
                                            <div className="grid grid-cols-2 gap-3">
                                                <button type="button" onClick={() => setCustomerInfo({ ...customerInfo, type: 'table' })} className={`py-4 rounded-2xl border-2 italic font-black text-[9px] tracking-widest ${customerInfo.type === 'table' ? 'border-orange-500 bg-orange-50' : 'border-gray-100'}`}>En Local</button>
                                                <button type="button" onClick={() => setCustomerInfo({ ...customerInfo, type: 'delivery' })} className={`py-4 rounded-2xl border-2 italic font-black text-[9px] tracking-widest ${customerInfo.type === 'delivery' ? 'border-orange-500 bg-orange-50' : 'border-gray-100'}`}>Domicilio</button>
                                            </div>
                                            {customerInfo.type === 'delivery' && <textarea required placeholder="Dirección..." value={customerInfo.address} onChange={e => setCustomerInfo({ ...customerInfo, address: e.target.value })} className="w-full px-4 py-4 bg-gray-50 rounded-2xl text-[10px] font-black min-h-[80px]" />}
                                            <textarea placeholder="Notas..." value={customerInfo.note} onChange={e => setCustomerInfo({ ...customerInfo, note: e.target.value })} className="w-full px-4 py-4 bg-gray-50 rounded-2xl text-[10px] font-black min-h-[80px]" />
                                        </div>
                                        <div className="p-8 border-t bg-gray-50"><button type="submit" className="w-full bg-gray-900 text-white font-black py-4 rounded-2xl italic">{isProcessing ? 'Procesando...' : 'Confirmar Pedido'}</button></div>
                                    </form>
                                ) : (
                                    <div className="p-12 text-center space-y-6 italic">
                                        <div className="w-20 h-20 bg-green-100 text-green-600 rounded-full flex items-center justify-center mx-auto"><CheckCircle2 size={40} /></div>
                                        <h2 className="text-3xl font-black italic tracking-tighter">¡Listo!</h2>
                                        <button onClick={() => { setIsCheckoutOpen(false); setOrderSuccess(false); clearCart(); }} className="w-full bg-gray-900 text-white font-black py-4 rounded-2xl uppercase">Volver</button>
                                    </div>
                                )}
                            </motion.div>
                        </div>
                    )}
                </AnimatePresence>
            </div>
        </SectionRenderer>
    );
}

const ClockIconComp = ({ size }) => <ClockIcon size={size} />;
const WhatsappIconComp = ({ size }) => <PhoneIcon size={size} />;