import React, { useState, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client';
import { ShoppingBag, X, Plus, Minus, MapPin, Clock, Phone, MessageCircle, ChefHat, Thermometer, Sparkles, Flame, ArrowRight, ArrowLeft, Smartphone } from 'lucide-react';

// ============ PRODUCTS DATA ============
const PRODUCTS = {
  carnes: [
    { id: 'c1', name: 'Bife do Lombo', sub: 'Vaca', price: 28.90, unit: 'kg', desc: 'Corte nobre, extra macio. A peça mais procurada do balcão.', tip: 'Frigideira bem quente, 2 min cada lado.', temp: '52°C mal · 57°C médio', tone: 'from-red-900 to-red-700' },
    { id: 'c2', name: 'Vazia', sub: 'Vaca', price: 19.50, unit: 'kg', desc: 'Saborosa e versátil. O clássico para o bife do dia a dia.', tip: 'Sal grosso na hora. Manteiga e alho no fim.', temp: '54°C ao ponto', tone: 'from-red-900 to-red-700' },
    { id: 'c3', name: 'Alcatra', sub: 'Vaca', price: 17.90, unit: 'kg', desc: 'Equilíbrio entre maciez e sabor.', tip: 'Excelente para grelhar inteira e fatiar.', temp: '55°C ao ponto', tone: 'from-red-900 to-red-700' },
    { id: 'c4', name: 'Carne Picada', sub: 'Vaca', price: 9.90, unit: 'kg', desc: 'Picada na hora, sem aditivos.', tip: 'Para hambúrgueres caseiros, não amasse demais.', temp: '70°C interior', tone: 'from-red-900 to-red-700' },
    { id: 'c5', name: 'Entremeada', sub: 'Porco', price: 8.50, unit: 'kg', desc: 'Camadas de carne e gordura. Ideal para o churrasco.', tip: 'Marinada em vinho branco, alho e colorau.', temp: '75°C interior', tone: 'from-orange-900 to-amber-700' },
    { id: 'c6', name: 'Lombo de Porco', sub: 'Porco', price: 11.90, unit: 'kg', desc: 'Magro e tenro. Para assar inteiro ou cortar em medalhões.', tip: 'Cuidado para não passar do ponto.', temp: '63°C interior', tone: 'from-orange-900 to-amber-700' },
    { id: 'c7', name: 'Frango do Campo', sub: 'Aves', price: 6.90, unit: 'kg', desc: 'Frango inteiro, criado ao ar livre. Sabor a sério.', tip: 'Esfregar com limão e ervas por dentro.', temp: '74°C no peito', tone: 'from-amber-800 to-yellow-700' },
    { id: 'c8', name: 'Chouriço Tradicional', sub: 'Enchidos', price: 14.50, unit: 'kg', desc: 'Receita da casa. Curado lentamente.', tip: 'À brasa ou cru em fatias finas.', temp: 'Pronto a consumir', tone: 'from-red-950 to-red-800' }
  ],
  preparados: [
    { id: 'p1', name: 'Espetadas Mistas', sub: 'Espetadas', price: 13.90, unit: 'kg', desc: 'Vaca, porco e pimentos. Já temperadas.', tip: 'Brasa média-alta. 4 min cada lado.', temp: 'Brasa média-alta', tone: 'from-amber-800 to-orange-700' },
    { id: 'p2', name: 'Frango Recheado', sub: 'Recheados', price: 9.90, unit: 'kg', desc: 'Frango inteiro recheado, pronto para o forno.', tip: 'Forno a 190°C durante 1h-1h15.', temp: '74°C no peito', tone: 'from-orange-900 to-amber-700' },
    { id: 'p3', name: 'Hambúrguer da Casa', sub: 'Almôndegas', price: 14.90, unit: 'kg', desc: 'Picado na hora, moldado à mão.', tip: 'Frigideira ou grelha bem quente.', temp: '63°C ao ponto', tone: 'from-amber-800 to-orange-700' },
    { id: 'p4', name: 'Bife Wellington', sub: 'Folhados', price: 22.90, unit: 'kg', desc: 'Lombo em massa folhada, especialidade clássica.', tip: 'Forno a 200°C durante 25-30 min.', temp: '57°C ao ponto', tone: 'from-yellow-800 to-amber-700' },
    { id: 'p5', name: 'Lasanha', sub: 'Para Forno', price: 11.90, unit: 'kg', desc: 'Lasanha de carne, pronta para o forno.', tip: 'Forno a 180°C, 35-40 min.', temp: 'Topo gratinado', tone: 'from-rose-900 to-red-800' },
    { id: 'p6', name: 'Croquetes', sub: 'Empanados', price: 9.90, unit: 'kg', desc: 'Croquetes da casa, prontos a fritar.', tip: 'Air fryer 200°C, 10 min.', temp: 'Dourados', tone: 'from-yellow-800 to-amber-700' }
  ]
};

const CATEGORY_META = {
  carnes: { title: 'Carnes', sub: 'Frescas · Ao Natural', desc: 'Vaca, porco, borrego, aves e enchidos. Cortados na hora.', tone: 'from-red-900 to-red-700', icon: Sparkles },
  preparados: { title: 'Preparados', sub: 'Prontos a cozinhar', desc: 'Espetadas, hambúrgueres, lasanhas. Prontos a aquecer e servir.', tone: 'from-amber-800 to-orange-700', icon: Flame }
};

// ============ LOGO ============
const Logo = ({ className = 'w-10 h-10' }) => (
  <svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" className={className}>
    <circle cx="50" cy="50" r="47" fill="#FBF8F1" stroke="#6B4226" strokeWidth="2.5" />
    <path d="M 68 20 A 32 32 0 0 1 78 78 L 22 78 Z" fill="#C9B89A" opacity="0.55" />
    <rect x="14" y="58" width="72" height="2.5" fill="#A89579" />
    <polygon points="86,55 91,59.5 86,64" fill="#A89579" />
    <path d="M30 28 Q24 22 28 16 Q34 20 38 28 Z" fill="#5C3D2E" />
    <path d="M70 28 Q76 22 72 16 Q66 20 62 28 Z" fill="#5C3D2E" />
    <path d="M30 32 C 28 38, 28 45, 32 50 C 35 58, 42 65, 50 67 C 58 65, 65 58, 68 50 C 72 45, 72 38, 70 32 C 65 28, 58 27, 50 28 C 42 27, 35 28, 30 32 Z" fill="#5C3D2E" />
    <ellipse cx="50" cy="58" rx="7" ry="4" fill="#4A2F22" />
    <circle cx="47" cy="58" r="0.8" fill="#FBF8F1" />
    <circle cx="53" cy="58" r="0.8" fill="#FBF8F1" />
  </svg>
);

// ============ QR CODE (real, aponta para talhodaluz.pt) ============
const FakeQR = ({ size = 128, url = 'https://talhodaluz.pt' }) => (
  <div className="bg-white p-3 rounded-2xl shadow-2xl relative" style={{ width: size, height: size }}>
    <img
      src={`https://api.qrserver.com/v1/create-qr-code/?size=300x300&ecc=H&margin=0&data=${encodeURIComponent(url)}`}
      alt={`QR Code para ${url}`}
      className="w-full h-full block"
    />
    <div className="absolute inset-0 flex items-center justify-center pointer-events-none">
      <div className="w-7 h-7 bg-red-900 rounded-full border-2 border-white shadow-md" />
    </div>
  </div>
);

// ============ COUNT UP ============
function CountUp({ end, suffix = '', start = false }) {
  const [value, setValue] = useState(0);
  useEffect(() => {
    if (!start) return;
    let frame, startTime;
    const animate = (t) => {
      if (!startTime) startTime = t;
      const progress = Math.min((t - startTime) / 2000, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setValue(Math.floor(eased * end));
      if (progress < 1) frame = requestAnimationFrame(animate);
      else setValue(end);
    };
    frame = requestAnimationFrame(animate);
    return () => cancelAnimationFrame(frame);
  }, [start, end]);
  return <>{value}{suffix}</>;
}

// ============ PRODUCT CARD ============
const ProductCard = ({ p, onClick }) => (
  <button onClick={onClick} className="group cursor-pointer text-left hover:scale-[1.02] transition-transform">
    <div className="relative aspect-[4/5] rounded-2xl overflow-hidden mb-3">
      <div className={`absolute inset-0 bg-gradient-to-br ${p.tone} transition-transform duration-700 group-hover:scale-105`} />
      <div className="absolute inset-0 opacity-20" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.4) 1px, transparent 0)', backgroundSize: '24px 24px' }} />
      <div className="absolute inset-0 flex flex-col items-center justify-center text-amber-50/40">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" className="w-12 h-12">
          <rect x="3" y="6" width="18" height="14" rx="2" /><circle cx="12" cy="13" r="3.5" /><path d="M8 6l1.5-2h5L16 6" />
        </svg>
        <div className="tracking-[0.25em] uppercase mt-2 text-[10px]">Foto em breve</div>
      </div>
      <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-transparent to-black/10" />
      <div className="absolute inset-0 p-4 flex flex-col justify-between text-amber-50">
        <div className="text-[9px] tracking-[0.25em] uppercase opacity-90 backdrop-blur-sm bg-black/30 self-start px-2.5 py-1 rounded-full">{p.sub}</div>
        <div className="font-serif text-xl leading-tight drop-shadow-lg">{p.name}</div>
      </div>
      <div className="absolute bottom-3 right-3 w-10 h-10 bg-amber-50 text-stone-900 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity shadow-lg">
        <Plus className="w-5 h-5" />
      </div>
    </div>
    <div className="flex justify-between items-baseline">
      <span className="text-sm text-stone-900 font-medium">{p.name}</span>
      <span className="text-sm font-medium text-stone-900">{p.price.toFixed(2)}€<span className="text-stone-500 text-xs">/{p.unit}</span></span>
    </div>
    <p className="text-stone-500 text-xs mt-0.5 line-clamp-1">{p.desc}</p>
  </button>
);

// ============ PRODUCT MODAL ============
function ProductModal({ product, onClose, onAdd }) {
  const [qty, setQty] = useState(0.5);
  return (
    <>
      <div onClick={onClose} className="fixed inset-0 z-40 bg-stone-900/60 backdrop-blur-sm anim-fade-in" />
      <div className="fixed inset-0 z-50 flex items-center justify-center p-8 pointer-events-none">
        <div className="bg-white rounded-3xl shadow-2xl max-w-4xl w-full overflow-hidden grid grid-cols-2 anim-modal-in pointer-events-auto">
          <div className="relative aspect-square">
            <div className={`absolute inset-0 bg-gradient-to-br ${product.tone}`} />
            <div className="absolute inset-0 opacity-20" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.4) 1px, transparent 0)', backgroundSize: '32px 32px' }} />
            <div className="absolute inset-0 flex flex-col items-center justify-center text-amber-50/40">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" className="w-24 h-24">
                <rect x="3" y="6" width="18" height="14" rx="2" /><circle cx="12" cy="13" r="3.5" /><path d="M8 6l1.5-2h5L16 6" />
              </svg>
              <div className="tracking-[0.25em] uppercase mt-3 text-xs">Foto em breve</div>
            </div>
            <div className="absolute top-5 left-5 text-[10px] tracking-[0.25em] uppercase opacity-90 backdrop-blur-sm bg-black/30 px-3 py-1.5 rounded-full text-amber-50">{product.sub}</div>
          </div>
          <div className="p-8 flex flex-col">
            <button onClick={onClose} className="self-end w-9 h-9 rounded-full bg-stone-100 hover:bg-stone-200 flex items-center justify-center transition-colors">
              <X className="w-4 h-4 text-stone-700" />
            </button>
            <div className="text-[10px] tracking-[0.3em] uppercase text-stone-500 mt-2 mb-2">{product.sub}</div>
            <h2 className="font-serif text-4xl text-stone-900 mb-3 leading-tight">{product.name}</h2>
            <div className="text-3xl text-red-900 font-medium mb-4">
              {product.price.toFixed(2)}€ <span className="text-base text-stone-500">/{product.unit}</span>
            </div>
            <p className="text-stone-600 text-sm leading-relaxed mb-6">{product.desc}</p>
            <div className="mb-5">
              <div className="text-[10px] tracking-widest uppercase text-stone-500 mb-2">Quantidade ({product.unit})</div>
              <div className="flex items-center gap-3">
                <button onClick={() => setQty(q => Math.max(0.25, +(q - 0.25).toFixed(2)))} className="w-10 h-10 rounded-full border border-stone-300 hover:bg-stone-100 flex items-center justify-center"><Minus className="w-4 h-4" /></button>
                <div className="font-serif text-2xl text-stone-900 min-w-[80px] text-center">{qty} {product.unit}</div>
                <button onClick={() => setQty(q => +(q + 0.25).toFixed(2))} className="w-10 h-10 rounded-full border border-stone-300 hover:bg-stone-100 flex items-center justify-center"><Plus className="w-4 h-4" /></button>
                <div className="ml-auto text-stone-500 text-sm">Total <span className="font-medium text-stone-900 text-base">{(qty * product.price).toFixed(2)}€</span></div>
              </div>
            </div>
            <button onClick={() => onAdd(product, qty)} className="w-full bg-red-900 hover:bg-red-800 text-amber-50 py-4 rounded-full font-medium text-sm mb-5 transition-colors">
              Adicionar ao carrinho
            </button>
            <div className="bg-stone-50 rounded-2xl p-4 border-l-4 border-amber-700 mt-auto">
              <div className="flex items-center gap-2 text-[10px] tracking-widest uppercase text-amber-800 mb-2">
                <ChefHat className="w-3.5 h-3.5" /> Mini-lição da casa
              </div>
              <p className="text-stone-700 text-sm leading-relaxed mb-2">{product.tip}</p>
              <div className="flex items-center gap-1.5 text-xs text-stone-500">
                <Thermometer className="w-3.5 h-3.5" /><span>{product.temp}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// ============ CART DRAWER ============
function CartDrawer({ cart, updateQty, cartTotal, onClose }) {
  return (
    <>
      <div onClick={onClose} className="fixed inset-0 z-40 bg-stone-900/50 anim-fade-in" />
      <div className="fixed top-0 right-0 bottom-0 z-50 w-[420px] bg-white shadow-2xl flex flex-col anim-slide-in-right">
        <div className="p-5 border-b border-stone-200 flex items-center justify-between flex-shrink-0">
          <div>
            <h2 className="font-serif text-2xl text-stone-900 leading-none">A sua encomenda</h2>
            <div className="text-xs text-stone-500 mt-1">{cart.length} {cart.length === 1 ? 'artigo' : 'artigos'}</div>
          </div>
          <button onClick={onClose} className="w-9 h-9 rounded-full bg-stone-100 hover:bg-stone-200 flex items-center justify-center"><X className="w-4 h-4" /></button>
        </div>
        {cart.length === 0 ? (
          <div className="flex-1 flex flex-col items-center justify-center px-8 text-center">
            <ShoppingBag className="w-12 h-12 text-stone-300 mb-4" />
            <p className="text-stone-500 text-sm mb-6">O carrinho ainda está vazio.</p>
            <button onClick={onClose} className="bg-red-900 hover:bg-red-800 text-amber-50 px-6 py-3 rounded-full text-sm font-medium">Ver produtos</button>
          </div>
        ) : (
          <>
            <div className="flex-1 overflow-y-auto p-5 space-y-3">
              {cart.map(i => (
                <div key={i.id} className="flex items-center gap-3 bg-stone-50 rounded-xl p-3">
                  <div className="flex-1 min-w-0">
                    <div className="font-medium text-sm truncate">{i.name}</div>
                    <div className="text-xs text-stone-500">{i.price.toFixed(2)}€/{i.unit}</div>
                  </div>
                  <div className="flex items-center gap-1.5">
                    <button onClick={() => updateQty(i.id, +(i.qty - 0.25).toFixed(2))} className="w-7 h-7 rounded-full border border-stone-300 hover:bg-stone-100 flex items-center justify-center"><Minus className="w-3 h-3" /></button>
                    <span className="text-sm font-medium min-w-[52px] text-center">{i.qty} {i.unit}</span>
                    <button onClick={() => updateQty(i.id, +(i.qty + 0.25).toFixed(2))} className="w-7 h-7 rounded-full border border-stone-300 hover:bg-stone-100 flex items-center justify-center"><Plus className="w-3 h-3" /></button>
                  </div>
                  <div className="font-medium text-sm w-16 text-right text-stone-900">{(i.qty * i.price).toFixed(2)}€</div>
                </div>
              ))}
            </div>
            <div className="p-5 border-t border-stone-200 bg-stone-50 flex-shrink-0">
              <div className="flex justify-between items-baseline mb-4">
                <span className="font-serif text-xl text-stone-900">Total</span>
                <span className="font-serif text-2xl text-stone-900">{cartTotal.toFixed(2)}€</span>
              </div>
              <button
                onClick={() => {
                  const phone = '351964595456'; // Talho da Luz
                  const lines = cart.map(i => `• ${i.name} — ${i.qty} ${i.unit} (${(i.qty * i.price).toFixed(2)}€)`).join('\n');
                  const text = `Olá! Gostaria de fazer uma encomenda:\n\n${lines}\n\nTotal: ${cartTotal.toFixed(2)}€\n\nLevanto na loja, no Mercado do Livramento.`;
                  window.open(`https://wa.me/${phone}?text=${encodeURIComponent(text)}`, '_blank');
                }}
                className="w-full bg-green-700 hover:bg-green-800 text-white py-3.5 rounded-full text-sm font-medium flex items-center justify-center gap-2"
              ><MessageCircle className="w-4 h-4" /> Finalizar por WhatsApp</button>
              <p className="text-[11px] text-stone-500 text-center mt-3 leading-relaxed">Sem entregas. Levante na loja, no Mercado do Livramento.</p>
            </div>
          </>
        )}
      </div>
    </>
  );
}

// ============ CONFIRMATION DIALOG ============
function ConfirmationDialog({ product, qty, onContinue, onViewCart, onClose }) {
  return (
    <>
      <div onClick={onClose} className="fixed inset-0 z-[60] bg-stone-900/60 backdrop-blur-sm anim-fade-in" />
      <div className="fixed inset-0 z-[70] flex items-center justify-center p-8 pointer-events-none">
        <div className="bg-white rounded-3xl shadow-2xl max-w-md w-full overflow-hidden anim-modal-in pointer-events-auto">
          <div className="bg-gradient-to-br from-green-700 to-green-600 px-8 py-8 text-center">
            <div className="w-16 h-16 bg-white rounded-full flex items-center justify-center mx-auto mb-3 anim-check">
              <svg className="w-10 h-10 text-green-700" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                <polyline points="20 6 9 17 4 12" />
              </svg>
            </div>
            <div className="text-amber-50 font-serif text-2xl">Adicionado!</div>
          </div>
          <div className="px-8 py-6 text-center">
            <div className="text-stone-900 text-base font-medium mb-1">{product.name}</div>
            <div className="text-stone-500 text-sm mb-5">{qty} {product.unit} · {(qty * product.price).toFixed(2)}€</div>
            <p className="text-stone-700 text-sm mb-5 leading-relaxed">Deseja continuar a comprar ou ir para o carrinho?</p>
            <div className="flex flex-col gap-2">
              <button onClick={onContinue} className="w-full bg-red-900 hover:bg-red-800 text-amber-50 py-3 rounded-full font-medium text-sm">Continuar a comprar</button>
              <button onClick={onViewCart} className="w-full bg-stone-100 hover:bg-stone-200 text-stone-700 py-3 rounded-full font-medium text-sm flex items-center justify-center gap-2"><ShoppingBag className="w-4 h-4" /> Ver carrinho</button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

// ============ MOBILE INSTALL STRIP ============
function MobileInstallStrip() {
  return (
    <section className="py-16 px-8 bg-gradient-to-br from-stone-900 via-red-950 to-stone-900 text-amber-50 relative overflow-hidden">
      <div className="absolute inset-0 opacity-15" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.3) 1px, transparent 0)', backgroundSize: '28px 28px' }} />
      <div className="relative max-w-6xl mx-auto flex items-center gap-10">
        <div className="flex-shrink-0"><FakeQR size={140} /></div>
        <div className="flex-1">
          <div className="flex items-center gap-2 text-[11px] tracking-[0.4em] uppercase text-amber-200 mb-3">
            <Smartphone className="w-3.5 h-3.5" /> No telemóvel
          </div>
          <h3 className="font-serif text-4xl mb-4 leading-tight">Tenha o talho <span className="italic shimmer-text">no bolso.</span></h3>
          <p className="text-stone-300 text-base leading-relaxed max-w-xl">
            Aceda ao site pelo telemóvel e <span className="text-amber-200 font-medium">instale como aplicação</span> no seu ecrã principal. Compras rápidas, sem barras do navegador, mesmo com rede fraca.
          </p>
        </div>
        <div className="flex-shrink-0 text-right border-l border-amber-200/20 pl-8">
          <div className="text-[10px] tracking-[0.3em] uppercase text-stone-400 mb-2">Aponte com a câmara</div>
          <div className="text-amber-200 text-base font-medium font-serif">talhodaluz.pt</div>
        </div>
      </div>
    </section>
  );
}

// ============ SITE HEADER (sticky, simplified — só logo + carrinho) ============
function SiteHeader({ cartCount, onLogoClick, onCartClick }) {
  return (
    <header className="sticky top-0 z-30 bg-stone-50/95 backdrop-blur-md border-b border-stone-200/60">
      <div className="max-w-6xl mx-auto px-8 py-4 flex items-center justify-between">
        <button onClick={onLogoClick} className="flex items-center gap-3 hover:opacity-80 transition-opacity">
          <Logo className="w-11 h-11" />
          <div className="text-left">
            <div className="font-serif text-stone-900 text-lg leading-none">Talho da Luz</div>
            <div className="text-[9px] tracking-[0.25em] uppercase text-stone-500 mt-1">Mercado do Livramento</div>
          </div>
        </button>
        <button onClick={onCartClick} className="relative p-2 rounded-full hover:bg-stone-200 transition-colors">
          <ShoppingBag className="w-5 h-5 text-stone-900" />
          {cartCount > 0 && (
            <span key={cartCount} className="absolute -top-1 -right-1 bg-red-700 text-amber-50 text-[10px] font-semibold rounded-full min-w-[20px] h-5 px-1 flex items-center justify-center anim-bump tabular-nums">
              {cartCount % 1 === 0 ? cartCount : cartCount.toFixed(1)}
            </span>
          )}
        </button>
      </div>
    </header>
  );
}

// ============ SITE FOOTER ============
function SiteFooter() {
  return (
    <footer className="bg-stone-950 text-stone-500 text-xs py-8 px-8">
      <div className="max-w-6xl mx-auto flex justify-between items-center">
        <div className="flex items-center gap-3">
          <Logo className="w-8 h-8" />
          <div>
            <div className="font-serif text-amber-50/80 text-sm leading-none">Talho da Luz</div>
            <div className="text-[9px] tracking-[0.25em] uppercase mt-1">Desde 1930</div>
          </div>
        </div>
        <div>© 2026 Talho da Luz · Todos os direitos reservados</div>
        <div className="flex gap-5">
          <a className="hover:text-amber-50 transition-colors cursor-pointer">Política de Privacidade</a>
          <a className="hover:text-amber-50 transition-colors cursor-pointer">Termos</a>
        </div>
      </div>
    </footer>
  );
}

// ============ HOME PAGE ============
function HomePage({ onCategoryClick, onScrollSection }) {
  const aboutRef = useRef(null);
  const [aboutShown, setAboutShown] = useState(false);

  useEffect(() => {
    const el = aboutRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(([entry]) => { if (entry.isIntersecting) setAboutShown(true); }, { threshold: 0.3 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  return (
    <div className="anim-page-in">
      {/* HERO */}
      <section className="relative bg-gradient-to-br from-stone-900 via-red-950 to-stone-900 text-amber-50 overflow-hidden">
        <div className="absolute inset-0 opacity-20" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.3) 1px, transparent 0)', backgroundSize: '32px 32px' }} />
        <div className="relative max-w-6xl mx-auto px-8 py-32 text-center">
          <div className="text-xs tracking-[0.4em] uppercase text-amber-200 mb-6">Desde 1930 · Mercado do Livramento</div>
          <h1 className="font-serif text-7xl leading-[1.05] mb-8">
            Do talho<br />
            <span className="shimmer-text italic">para a sua mesa.</span>
          </h1>
          <p className="text-stone-300 text-lg max-w-xl mx-auto mb-10">Tradição evoluída no coração de Setúbal.</p>
          <div className="flex justify-center gap-3">
            <button onClick={() => onScrollSection('produtos')} className="bg-amber-50 text-stone-900 px-8 py-3.5 rounded-full font-medium text-sm flex items-center gap-2 hover:scale-105 transition-transform">
              Ver Produtos <ArrowRight className="w-4 h-4" />
            </button>
            <button onClick={() => onScrollSection('sobre')} className="border border-amber-200/40 text-amber-100 px-8 py-3.5 rounded-full font-medium text-sm hover:bg-amber-50/10 transition-colors">
              Conhecer a Casa
            </button>
          </div>
        </div>
      </section>

      {/* SOBRE */}
      <section id="sobre" ref={aboutRef} className="py-24 px-8 bg-stone-50 text-center">
        <div className="max-w-3xl mx-auto">
          <div className="text-xs tracking-[0.4em] uppercase text-stone-500 mb-4">Quem Somos</div>
          <h2 className="font-serif text-5xl text-stone-900 mb-8 leading-tight">
            Tradição evoluída,<br /><span className="italic">feita à mão.</span>
          </h2>
          <p className="text-stone-600 text-base leading-relaxed mb-3">Estamos no Mercado do Livramento há gerações. Conhecemos cada corte, cada peça, cada cliente.</p>
          <p className="text-stone-600 text-base leading-relaxed mb-12">O que mudou foi a forma de chegarmos a si. O que se mantém é o que importa.</p>
          <div className="flex justify-center gap-16">
            {[{ end: 95, suffix: '+', label: 'anos no mercado' }, { end: 3, suffix: '', label: 'gerações' }, { end: 100, suffix: '%', label: 'fresco diário' }].map(s => (
              <div key={s.label}>
                <div className="font-serif text-5xl text-red-900 mb-2 tabular-nums">
                  <CountUp end={s.end} suffix={s.suffix} start={aboutShown} />
                </div>
                <div className="text-[10px] uppercase tracking-widest text-stone-500">{s.label}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* PRODUTOS — clicar leva para a página da categoria */}
      <section id="produtos" className="py-24 px-8 bg-stone-100">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-12">
            <div className="text-xs tracking-[0.4em] uppercase text-stone-500 mb-3">Os Nossos Produtos</div>
            <h2 className="font-serif text-4xl text-stone-900 mb-3">Dois mundos<br /><span className="italic">no mesmo balcão.</span></h2>
            <p className="text-stone-600 text-sm max-w-md mx-auto mt-5">Escolha o seu mundo para ver os produtos disponíveis.</p>
          </div>
          <div className="grid grid-cols-2 gap-5">
            {['carnes', 'preparados'].map(cat => {
              const meta = CATEGORY_META[cat];
              return (
                <button key={cat} onClick={() => onCategoryClick(cat)} className="group relative overflow-hidden rounded-2xl text-left text-amber-50 min-h-[280px] hover:scale-[1.02] transition-transform">
                  <div className={`absolute inset-0 bg-gradient-to-br ${meta.tone} transition-transform duration-700 group-hover:scale-105`} />
                  <div className="absolute inset-0 opacity-25" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.4) 1px, transparent 0)', backgroundSize: '24px 24px' }} />
                  <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-black/10 to-transparent" />
                  <div className="relative p-8 flex flex-col justify-between min-h-[280px]">
                    <div className="flex justify-between items-start">
                      <meta.icon className="w-7 h-7 opacity-90" />
                      <span className="text-[10px] tracking-widest uppercase opacity-70">{PRODUCTS[cat].length} produtos</span>
                    </div>
                    <div>
                      <div className="text-[10px] tracking-[0.3em] uppercase text-amber-200 mb-2">{meta.sub}</div>
                      <h3 className="font-serif text-4xl mb-2">{meta.title}</h3>
                      <p className="text-amber-100/80 text-sm mb-5">{meta.desc}</p>
                      <div className="inline-flex items-center gap-2 text-sm font-medium border-b border-amber-200/40 pb-1 group-hover:gap-3 transition-all">
                        Explorar {meta.title.toLowerCase()} <ArrowRight className="w-4 h-4" />
                      </div>
                    </div>
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      </section>

      {/* MOBILE INSTALL */}
      <MobileInstallStrip />

      {/* CONTACTO */}
      <section id="contacto" className="py-24 px-8 bg-stone-900 text-stone-100">
        <div className="max-w-6xl mx-auto">
          <div className="text-center mb-12">
            <div className="text-xs tracking-[0.4em] uppercase text-amber-200 mb-3">Visite-nos</div>
            <h2 className="font-serif text-4xl text-amber-50">Apareça lá pelo<br /><span className="italic">mercado.</span></h2>
          </div>
          <div className="grid grid-cols-3 gap-6">
            <div className="bg-stone-800/50 border border-amber-200/10 rounded-2xl p-6 text-center">
              <div className="w-12 h-12 rounded-full bg-amber-50/10 border border-amber-200/20 flex items-center justify-center mx-auto mb-4"><MapPin className="w-5 h-5 text-amber-200" /></div>
              <div className="text-amber-50 mb-1 font-medium">Mercado do Livramento</div>
              <div className="text-stone-400 text-sm">Loja 15A · 2900-462 Setúbal</div>
            </div>
            <div className="bg-stone-800/50 border border-amber-200/10 rounded-2xl p-6 text-center">
              <div className="w-12 h-12 rounded-full bg-amber-50/10 border border-amber-200/20 flex items-center justify-center mx-auto mb-4"><Clock className="w-5 h-5 text-amber-200" /></div>
              <div className="text-amber-50 mb-1 font-medium">Horário</div>
              <div className="text-stone-400 text-sm leading-relaxed">Ter–Sex · 7h–19h<br />Sáb · 7h–14h e 16h–18h<br />Dom e Feriados · 7h–14h</div>
            </div>
            <div className="bg-stone-800/50 border border-amber-200/10 rounded-2xl p-6 text-center">
              <div className="w-12 h-12 rounded-full bg-amber-50/10 border border-amber-200/20 flex items-center justify-center mx-auto mb-4"><Phone className="w-5 h-5 text-amber-200" /></div>
              <div className="text-amber-50 mb-1 font-medium">Contacto</div>
              <div className="text-stone-400 text-sm">964 595 456</div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}

// ============ SHOP PAGE ============
function ShopPage({ cat, onBackHome, onProductClick, onSwitchCategory }) {
  const [filterSub, setFilterSub] = useState('Todos');
  const meta = CATEGORY_META[cat];
  const subs = [...new Set(PRODUCTS[cat].map(p => p.sub))];
  const filtered = filterSub === 'Todos' ? PRODUCTS[cat] : PRODUCTS[cat].filter(p => p.sub === filterSub);
  const otherCat = cat === 'carnes' ? 'preparados' : 'carnes';

  // Reset filter when category changes
  useEffect(() => { setFilterSub('Todos'); }, [cat]);

  return (
    <div className="bg-stone-50 anim-page-in">
      {/* BREADCRUMB + HERO */}
      <section className={`relative bg-gradient-to-br ${meta.tone} text-amber-50 overflow-hidden`}>
        <div className="absolute inset-0 opacity-20" style={{ backgroundImage: 'radial-gradient(circle at 1px 1px, rgba(255,255,255,0.3) 1px, transparent 0)', backgroundSize: '28px 28px' }} />
        <div className="absolute inset-0 bg-gradient-to-b from-transparent to-black/30" />
        <div className="relative max-w-6xl mx-auto px-8 pt-8 pb-16">
          <div className="flex items-center gap-2 text-xs text-amber-100/80 mb-8">
            <button onClick={onBackHome} className="flex items-center gap-1 hover:text-amber-50 transition-colors">
              <ArrowLeft className="w-3 h-3" /> Casa
            </button>
            <span>/</span>
            <span className="text-amber-50">{meta.title}</span>
          </div>
          <div className="flex items-end justify-between gap-8">
            <div>
              <div className="text-[11px] tracking-[0.4em] uppercase text-amber-200 mb-3 flex items-center gap-2">
                <meta.icon className="w-3.5 h-3.5" /> {meta.sub}
              </div>
              <h1 className="font-serif text-6xl leading-[1.05] mb-3">{meta.title}</h1>
              <p className="text-amber-100/80 text-base max-w-md">{meta.desc}</p>
            </div>
            <div className="text-right">
              <div className="text-[10px] tracking-[0.3em] uppercase text-amber-200/70 mb-1">Disponíveis</div>
              <div className="font-serif text-4xl tabular-nums">{PRODUCTS[cat].length}</div>
            </div>
          </div>
        </div>
      </section>

      {/* FILTERS + GRID */}
      <section className="py-12 px-8">
        <div className="max-w-6xl mx-auto">
          <div className="flex items-center justify-between mb-8 pb-6 border-b border-stone-200">
            <div className="flex flex-wrap gap-1.5">
              <button onClick={() => setFilterSub('Todos')} className={`px-3 py-1.5 rounded-full text-xs transition-colors ${filterSub === 'Todos' ? 'bg-red-900 text-amber-50' : 'bg-white text-stone-700 border border-stone-200 hover:border-stone-300'}`}>Todos</button>
              {subs.map(s => (
                <button key={s} onClick={() => setFilterSub(s)} className={`px-3 py-1.5 rounded-full text-xs transition-colors ${filterSub === s ? 'bg-red-900 text-amber-50' : 'bg-white text-stone-700 border border-stone-200 hover:border-stone-300'}`}>{s}</button>
              ))}
            </div>
            <div className="text-xs text-stone-500">
              <span className="font-medium text-stone-900">{filtered.length}</span> {filtered.length === 1 ? 'produto' : 'produtos'}
            </div>
          </div>

          <div className="grid grid-cols-4 gap-5">
            {filtered.map(p => <ProductCard key={p.id} p={p} onClick={() => onProductClick(p)} />)}
          </div>

          <div className="mt-16 text-center pt-12 border-t border-stone-200">
            <div className="text-xs tracking-[0.3em] uppercase text-stone-500 mb-3">Também temos</div>
            <button onClick={() => onSwitchCategory(otherCat)} className="font-serif text-3xl text-stone-900 hover:text-red-900 transition-colors inline-flex items-center gap-3 group">
              Ver {CATEGORY_META[otherCat].title} <ArrowRight className="w-6 h-6 group-hover:translate-x-1 transition-transform" />
            </button>
          </div>
        </div>
      </section>
    </div>
  );
}

// ============ MAIN APP ============
function App() {
  const [page, setPage] = useState('home');
  const [activeCat, setActiveCat] = useState('carnes');
  const [cart, setCart] = useState([]);
  const [cartOpen, setCartOpen] = useState(false);
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [confirmedItem, setConfirmedItem] = useState(null);

  const cartCount = cart.reduce((s, i) => s + i.qty, 0);
  const cartTotal = cart.reduce((s, i) => s + i.qty * i.price, 0);

  const goHome = () => {
    setPage('home');
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  const goToCategory = (cat) => {
    setActiveCat(cat);
    setPage('shop');
    window.scrollTo({ top: 0, behavior: 'auto' });
  };

  const scrollToSection = (id) => {
    const el = document.getElementById(id);
    if (el) {
      const headerHeight = 76;
      const top = el.getBoundingClientRect().top + window.scrollY - headerHeight;
      window.scrollTo({ top, behavior: 'smooth' });
    }
  };

  const addToCart = (p, qty) => {
    setCart(c => {
      const ex = c.find(i => i.id === p.id);
      if (ex) return c.map(i => i.id === p.id ? { ...i, qty: +(i.qty + qty).toFixed(2) } : i);
      return [...c, { id: p.id, name: p.name, price: p.price, unit: p.unit, qty }];
    });
    setConfirmedItem({ product: p, qty });
    setSelectedProduct(null);
  };

  const updateQty = (id, qty) => {
    if (qty <= 0) setCart(c => c.filter(i => i.id !== id));
    else setCart(c => c.map(i => i.id === id ? { ...i, qty } : i));
  };

  const handleContinueShopping = () => {
    setConfirmedItem(null);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const handleViewCart = () => {
    setConfirmedItem(null);
    setCartOpen(true);
  };

  return (
    <div className="min-h-screen bg-stone-50 relative">
      <style>{`
        @keyframes shimmer { 0%,100% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideInRight { from { transform: translateX(100%); } to { transform: translateX(0); } }
        @keyframes modalIn { from { opacity: 0; transform: scale(0.92); } to { opacity: 1; transform: scale(1); } }
        @keyframes checkPop { 0% { transform: scale(0); } 60% { transform: scale(1.15); } 100% { transform: scale(1); } }
        @keyframes bump { 0%, 100% { transform: scale(1); } 30% { transform: scale(1.3); } 60% { transform: scale(0.95); } }
        @keyframes pageIn { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
        .shimmer-text {
          background: linear-gradient(90deg, #fde68a 0%, #fcd34d 50%, #fde68a 100%);
          background-size: 200% 100%;
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: transparent;
          animation: shimmer 4s ease-in-out infinite;
        }
        .anim-fade-in { animation: fadeIn 0.25s ease-out forwards; }
        .anim-slide-in-right { animation: slideInRight 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
        .anim-modal-in { animation: modalIn 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
        .anim-check { animation: checkPop 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
        .anim-bump { animation: bump 0.5s cubic-bezier(0.16, 1, 0.3, 1); }
        .anim-page-in { animation: pageIn 0.35s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
      `}</style>

      <SiteHeader cartCount={cartCount} onLogoClick={goHome} onCartClick={() => setCartOpen(true)} />

      {page === 'home' ? (
        <HomePage onCategoryClick={goToCategory} onScrollSection={scrollToSection} />
      ) : (
        <ShopPage
          cat={activeCat}
          onBackHome={goHome}
          onProductClick={(p) => setSelectedProduct(p)}
          onSwitchCategory={goToCategory}
        />
      )}

      <SiteFooter />

      {selectedProduct && (
        <ProductModal product={selectedProduct} onClose={() => setSelectedProduct(null)} onAdd={addToCart} />
      )}
      {cartOpen && (
        <CartDrawer cart={cart} updateQty={updateQty} cartTotal={cartTotal} onClose={() => setCartOpen(false)} />
      )}
      {confirmedItem && (
        <ConfirmationDialog
          product={confirmedItem.product}
          qty={confirmedItem.qty}
          onContinue={handleContinueShopping}
          onViewCart={handleViewCart}
          onClose={() => setConfirmedItem(null)}
        />
      )}
    </div>
  );
}

createRoot(document.getElementById('root')).render(<App />);
