const { useState, useEffect, useMemo, useCallback } = React;

// Cliente Supabase com chave anônima (acesso público limitado)
const sb = window.supabase.createClient(window.CONFIG.SUPABASE_URL, window.CONFIG.SUPABASE_KEY);

// Paleta
const colors = {
  primary: '#8B2331', primaryDark: '#6B1A26', accent: '#D9A521',
  cream: '#F7F3EC', surface: '#FFFFFF', surfaceAlt: '#F0EBE0',
  text: '#2A2520', textSoft: '#5C5147', textMute: '#8B7E6F',
  border: '#E5DDD0', success: '#3F8A5C', danger: '#B33A3A',
};
const display = "'Fraunces', serif";
const body = "'Inter', sans-serif";

const fmtBRL = (v) => `R$ ${Number(v || 0).toFixed(2).replace('.', ',')}`;
const newId = () => `${Date.now().toString(16)}${Math.floor(Math.random() * 0xfffff).toString(16)}`;

// camel ↔ snake (mesma lógica do app principal)
const toCamel = (obj) => {
  if (!obj || typeof obj !== 'object') return obj;
  const out = {};
  for (const k in obj) out[k.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = obj[k];
  return out;
};
const toSnake = (obj) => {
  if (!obj || typeof obj !== 'object') return obj;
  const out = {};
  for (const k in obj) out[k.replace(/([A-Z])/g, '_$1').toLowerCase()] = obj[k];
  return out;
};

// Pega o número da mesa pela URL: cardapio.html?mesa=5
function useTableParam() {
  const params = new URLSearchParams(window.location.search);
  return params.get('mesa') || '';
}

// ============================================================
// APP PRINCIPAL
// ============================================================
function App() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [cart, setCart] = useState([]);
  const [notes, setNotes] = useState('');
  const [tableNumber, setTableNumber] = useState(useTableParam());
  const [orderType, setOrderType] = useState(useTableParam() ? 'mesa' : 'mesa'); // 'mesa' ou 'retirada'
  const [customerName, setCustomerName] = useState('');
  const [customerPhone, setCustomerPhone] = useState('');
  const [paymentMethod, setPaymentMethod] = useState('');
  // Endereço (só usado em entrega)
  const [addrCep, setAddrCep] = useState('');
  const [addrStreet, setAddrStreet] = useState('');
  const [addrNumber, setAddrNumber] = useState('');
  const [addrComplement, setAddrComplement] = useState('');
  const [addrNeighborhood, setAddrNeighborhood] = useState('');
  const [view, setView] = useState('menu'); // menu | cart | sent
  const [sending, setSending] = useState(false);
  const [error, setError] = useState('');
  const [orderId, setOrderId] = useState(null);
  const [deliveryTimes, setDeliveryTimes] = useState({
    mesa: { min: 10, max: 20 },
    retirada: { min: 15, max: 25 },
    entrega: { min: 30, max: 50 },
  });

  // Carrega cardápio (só itens disponíveis) + configurações de tempo
  useEffect(() => {
    (async () => {
      try {
        const { data, error } = await sb.from('products').select('*').order('name');
        if (error) throw error;
        const list = (data || []).map(toCamel).filter(p => p.available !== false);
        setProducts(list);
      } catch (e) {
        setError('Não foi possível carregar o cardápio. Verifique sua conexão.');
      } finally {
        setLoading(false);
      }
    })();
    // Lê configurações (silencioso, se falhar usa defaults)
    (async () => {
      try {
        const { data } = await sb.from('settings').select('*').eq('key', 'delivery_times').single();
        if (data && data.value) {
          setDeliveryTimes(prev => ({ ...prev, ...data.value }));
        }
      } catch {}
    })();
  }, []);

  // Categorias do cardápio
  const categories = useMemo(() => {
    const set = new Set(products.map(p => p.category || 'Outros'));
    return ['Todos', ...Array.from(set).sort()];
  }, [products]);

  const [filterCategory, setFilterCategory] = useState('Todos');
  const visibleProducts = useMemo(() => {
    if (filterCategory === 'Todos') return products;
    return products.filter(p => (p.category || 'Outros') === filterCategory);
  }, [products, filterCategory]);

  // Agrupa por categoria (quando "Todos")
  const grouped = useMemo(() => {
    const map = {};
    visibleProducts.forEach(p => {
      const c = p.category || 'Outros';
      if (!map[c]) map[c] = [];
      map[c].push(p);
    });
    return Object.entries(map).sort(([a], [b]) => a.localeCompare(b));
  }, [visibleProducts]);

  // Carrinho
  const addToCart = (product) => {
    setCart(prev => {
      const existing = prev.find(c => c.productId === product.id);
      if (existing) return prev.map(c => c.productId === product.id ? { ...c, quantity: c.quantity + 1 } : c);
      return [...prev, { productId: product.id, name: product.name, price: Number(product.price) || 0, quantity: 1 }];
    });
  };
  const removeFromCart = (productId) => {
    setCart(prev => {
      const existing = prev.find(c => c.productId === productId);
      if (existing && existing.quantity > 1) return prev.map(c => c.productId === productId ? { ...c, quantity: c.quantity - 1 } : c);
      return prev.filter(c => c.productId !== productId);
    });
  };
  const cartTotal = cart.reduce((s, c) => s + c.price * c.quantity, 0);
  const cartCount = cart.reduce((s, c) => s + c.quantity, 0);

  // Enviar pedido
  const sendOrder = async () => {
    if (orderType === 'mesa' && !tableNumber.trim()) { setError('Informe o número da mesa.'); return; }
    if (orderType === 'retirada' && !customerName.trim()) { setError('Informe seu nome para retirada.'); return; }
    if (orderType === 'entrega') {
      if (!customerName.trim()) { setError('Informe seu nome para entrega.'); return; }
      if (!addrStreet.trim() || !addrNumber.trim() || !addrNeighborhood.trim()) {
        setError('Preencha rua, número e bairro para entrega.'); return;
      }
    }
    const phoneDigits = customerPhone.replace(/\D/g, '');
    if (phoneDigits.length < 10) { setError('Informe um telefone válido (com DDD).'); return; }
    if (!paymentMethod) { setError('Escolha a forma de pagamento.'); return; }
    if (cart.length === 0) { setError('Adicione pelo menos um item.'); return; }
    setSending(true); setError('');
    try {
      const id = newId();
      // Etiqueta de identificação (aparece no card e na cozinha)
      let label = '';
      if (orderType === 'mesa') label = tableNumber.trim();
      else if (orderType === 'retirada') label = `RET: ${customerName.trim()}`;
      else if (orderType === 'entrega') label = `ENT: ${customerName.trim()}`;

      // Endereço formatado
      const fullAddress = orderType === 'entrega'
        ? `${addrStreet.trim()}, ${addrNumber.trim()}${addrComplement.trim() ? ' - ' + addrComplement.trim() : ''} - ${addrNeighborhood.trim()}${addrCep.trim() ? ' (CEP ' + addrCep.trim() + ')' : ''}`
        : null;

      const order = {
        id,
        tableNumber: label,
        orderType,
        customerName: customerName.trim() || null,
        customerPhone: phoneDigits,
        deliveryAddress: fullAddress,
        paymentMethod,
        items: cart,
        total: cartTotal,
        notes: notes.trim() || null,
        status: 'pendente',
        createdAt: new Date().toISOString(),
      };
      const { error } = await sb.from('pending_orders').insert(toSnake(order));
      if (error) throw error;
      setOrderId(id);
      setView('sent');
      setCart([]);
      setNotes('');
    } catch (e) {
      setError(e.message ? `Erro: ${e.message}` : 'Erro ao enviar pedido. Tente novamente.');
    } finally {
      setSending(false);
    }
  };

  // Máscara de telefone brasileiro: (XX) XXXXX-XXXX
  const formatPhone = (raw) => {
    const d = raw.replace(/\D/g, '').slice(0, 11);
    if (d.length === 0) return '';
    if (d.length <= 2) return `(${d}`;
    if (d.length <= 6) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
    if (d.length <= 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
    return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
  };

  // Máscara de CEP brasileiro: XXXXX-XXX
  const formatCep = (raw) => {
    const d = raw.replace(/\D/g, '').slice(0, 8);
    if (d.length <= 5) return d;
    return `${d.slice(0, 5)}-${d.slice(5)}`;
  };

  // === RENDER ===
  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: colors.textMute, fontFamily: body }}>
        Carregando cardápio...
      </div>
    );
  }

  if (view === 'sent') {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20, backgroundColor: colors.cream }}>
        <div style={{ maxWidth: 420, width: '100%', backgroundColor: colors.surface, borderRadius: 16, padding: 28, textAlign: 'center', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
          <div style={{ width: 72, height: 72, borderRadius: 999, backgroundColor: '#E9F5EE', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', marginBottom: 16 }}>
            <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke={colors.success} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
          </div>
          <h1 style={{ fontFamily: display, fontSize: 24, fontWeight: 700, color: colors.text, margin: '0 0 8px' }}>Pedido enviado!</h1>
          <p style={{ fontFamily: body, fontSize: 15, color: colors.textSoft, margin: '0 0 6px' }}>
            Seu pedido foi recebido e está aguardando confirmação.
          </p>
          <p style={{ fontFamily: body, fontSize: 14, color: colors.textMute, margin: '0 0 16px' }}>
            {orderType === 'mesa' && <>Mesa <strong style={{ color: colors.text }}>{tableNumber}</strong></>}
            {orderType === 'retirada' && <>Retirada para <strong style={{ color: colors.text }}>{customerName}</strong></>}
            {orderType === 'entrega' && <>Entrega para <strong style={{ color: colors.text }}>{customerName}</strong></>}
          </p>
          {(orderType === 'retirada' || orderType === 'entrega') && deliveryTimes[orderType] && (
            <div style={{ padding: 14, backgroundColor: '#FFF6E5', borderRadius: 10, marginBottom: 18, fontFamily: body, border: `1px solid ${colors.accent}` }}>
              <div style={{ fontSize: 12, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.4, fontWeight: 600 }}>
                ⏱ Tempo estimado
              </div>
              <div style={{ fontFamily: display, fontSize: 22, fontWeight: 700, color: colors.text }}>
                {deliveryTimes[orderType].min} a {deliveryTimes[orderType].max} minutos
              </div>
              <div style={{ fontSize: 11, color: colors.textMute, marginTop: 4 }}>
                {orderType === 'entrega' ? 'a partir da confirmação do pedido' : 'a partir da confirmação para retirada'}
              </div>
            </div>
          )}
          <button onClick={() => { setView('menu'); setOrderId(null); }}
            style={{ width: '100%', padding: '14px', backgroundColor: colors.primary, color: '#fff', border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 600, cursor: 'pointer', fontFamily: body }}>
            Fazer outro pedido
          </button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ minHeight: '100vh', paddingBottom: cartCount > 0 ? 96 : 24 }}>
      {/* Header */}
      <header style={{ backgroundColor: colors.primary, color: '#fff', padding: '20px 18px', boxShadow: '0 2px 8px rgba(0,0,0,0.1)' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <h1 style={{ fontFamily: display, fontSize: 22, fontWeight: 700, margin: 0, lineHeight: 1 }}>{window.CONFIG.NOME_NEGOCIO || 'Cardápio'}</h1>
            <p style={{ fontFamily: body, fontSize: 13, margin: '4px 0 0', opacity: 0.85 }}>Cardápio digital</p>
          </div>
          {orderType === 'mesa' && tableNumber && (
            <div style={{ padding: '6px 14px', backgroundColor: 'rgba(255,255,255,0.18)', borderRadius: 999, fontFamily: body, fontSize: 13, fontWeight: 600 }}>
              Mesa {tableNumber}
            </div>
          )}
          {orderType === 'retirada' && (
            <div style={{ padding: '6px 14px', backgroundColor: 'rgba(255,255,255,0.18)', borderRadius: 999, fontFamily: body, fontSize: 13, fontWeight: 600 }}>
              🥡 Retirada
            </div>
          )}
          {orderType === 'entrega' && (
            <div style={{ padding: '6px 14px', backgroundColor: 'rgba(255,255,255,0.18)', borderRadius: 999, fontFamily: body, fontSize: 13, fontWeight: 600 }}>
              🛵 Entrega
            </div>
          )}
        </div>
      </header>

      {/* Filtros de categoria */}
      <div style={{ padding: '14px 18px 0', display: 'flex', gap: 6, overflowX: 'auto', WebkitOverflowScrolling: 'touch' }}>
        {categories.map(c => (
          <button key={c} onClick={() => setFilterCategory(c)}
            style={{
              flexShrink: 0, padding: '7px 14px', borderRadius: 999,
              border: `1px solid ${filterCategory === c ? colors.primary : colors.border}`,
              backgroundColor: filterCategory === c ? colors.primary : 'transparent',
              color: filterCategory === c ? '#fff' : colors.textSoft,
              fontFamily: body, fontSize: 13, fontWeight: 500, cursor: 'pointer',
            }}>
            {c}
          </button>
        ))}
      </div>

      {/* Lista de produtos */}
      <main style={{ padding: '16px 18px' }}>
        {products.length === 0 ? (
          <div style={{ textAlign: 'center', padding: 40, color: colors.textMute, fontFamily: body, fontSize: 14 }}>
            Nenhum item disponível no cardápio no momento.
          </div>
        ) : (
          (filterCategory === 'Todos' ? grouped : [['', visibleProducts]]).map(([catName, list]) => (
            <div key={catName} style={{ marginBottom: 20 }}>
              {filterCategory === 'Todos' && catName && (
                <h2 style={{ fontFamily: display, fontSize: 17, fontWeight: 700, color: colors.text, margin: '8px 0 10px', borderBottom: `2px solid ${colors.accent}`, paddingBottom: 4, display: 'inline-block' }}>
                  {catName}
                </h2>
              )}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {list.map(p => {
                  const inCart = cart.find(c => c.productId === p.id);
                  return (
                    <div key={p.id} style={{
                      backgroundColor: colors.surface, borderRadius: 12, padding: 14,
                      boxShadow: '0 1px 3px rgba(0,0,0,0.06)', border: `1px solid ${colors.border}`,
                      display: 'flex', alignItems: 'flex-start', gap: 12,
                    }}>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontFamily: display, fontSize: 16, fontWeight: 600, color: colors.text, marginBottom: 2 }}>{p.name}</div>
                        {p.description && (
                          <div style={{ fontFamily: body, fontSize: 13, color: colors.textSoft, marginBottom: 6, lineHeight: 1.4 }}>{p.description}</div>
                        )}
                        <div style={{ fontFamily: display, fontSize: 17, fontWeight: 700, color: colors.primary }}>{fmtBRL(p.price)}</div>
                      </div>
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'center' }}>
                        {inCart ? (
                          <div style={{ display: 'flex', alignItems: 'center', gap: 8, backgroundColor: colors.surfaceAlt, borderRadius: 999, padding: '4px 6px' }}>
                            <button onClick={() => removeFromCart(p.id)} style={{ width: 28, height: 28, borderRadius: 999, border: 'none', backgroundColor: colors.surface, color: colors.text, fontSize: 18, cursor: 'pointer', fontWeight: 600 }}>−</button>
                            <span style={{ fontFamily: display, fontSize: 15, fontWeight: 700, color: colors.text, minWidth: 16, textAlign: 'center' }}>{inCart.quantity}</span>
                            <button onClick={() => addToCart(p)} style={{ width: 28, height: 28, borderRadius: 999, border: 'none', backgroundColor: colors.primary, color: '#fff', fontSize: 18, cursor: 'pointer', fontWeight: 600 }}>+</button>
                          </div>
                        ) : (
                          <button onClick={() => addToCart(p)} style={{ padding: '8px 16px', backgroundColor: colors.primary, color: '#fff', border: 'none', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: body }}>+ Adicionar</button>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          ))
        )}
      </main>

      {/* Barra do carrinho fixa */}
      {cartCount > 0 && view === 'menu' && (
        <div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, padding: 14, backgroundColor: colors.surface, borderTop: `1px solid ${colors.border}`, boxShadow: '0 -4px 12px rgba(0,0,0,0.08)' }}>
          <button onClick={() => setView('cart')} style={{ width: '100%', padding: '14px', backgroundColor: colors.primary, color: '#fff', border: 'none', borderRadius: 10, fontFamily: body, fontSize: 15, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span>Ver carrinho · {cartCount} item{cartCount === 1 ? '' : 's'}</span>
            <span style={{ fontFamily: display, fontSize: 17 }}>{fmtBRL(cartTotal)}</span>
          </button>
        </div>
      )}

      {/* Tela do carrinho */}
      {view === 'cart' && (
        <div style={{ position: 'fixed', inset: 0, backgroundColor: colors.cream, overflowY: 'auto', zIndex: 100 }}>
          <header style={{ backgroundColor: colors.primary, color: '#fff', padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 12 }}>
            <button onClick={() => setView('menu')} style={{ background: 'transparent', border: 'none', color: '#fff', cursor: 'pointer', padding: 4, fontSize: 24 }}>←</button>
            <h2 style={{ fontFamily: display, fontSize: 20, fontWeight: 700, margin: 0 }}>Seu pedido</h2>
          </header>
          <div style={{ padding: 18 }}>
            <div style={{ backgroundColor: colors.surface, borderRadius: 12, padding: 16, marginBottom: 14, border: `1px solid ${colors.border}` }}>
              <div style={{ fontFamily: body, fontSize: 12, fontWeight: 500, color: colors.textSoft, marginBottom: 8, textTransform: 'uppercase', letterSpacing: 0.3 }}>Como você vai consumir?</div>
              <div style={{ display: 'flex', gap: 6, marginBottom: 14, flexWrap: 'wrap' }}>
                {[
                  { v: 'mesa', l: '🍽 Comer aqui' },
                  { v: 'retirada', l: '🥡 Retirada' },
                  { v: 'entrega', l: '🛵 Entrega' },
                ].map(t => (
                  <button key={t.v} onClick={() => setOrderType(t.v)}
                    style={{
                      flex: '1 1 0', minWidth: 100, padding: '12px 8px', borderRadius: 10,
                      border: `2px solid ${orderType === t.v ? colors.primary : colors.border}`,
                      backgroundColor: orderType === t.v ? colors.primary : colors.surface,
                      color: orderType === t.v ? '#fff' : colors.text,
                      fontFamily: body, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                    }}>
                    {t.l}
                  </button>
                ))}
              </div>
              {orderType === 'mesa' && (
                <>
                  <div style={{ fontFamily: body, fontSize: 12, fontWeight: 500, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Mesa</div>
                  <input type="text" value={tableNumber} onChange={e => setTableNumber(e.target.value)}
                    placeholder="Ex: 5"
                    style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface, marginBottom: 12 }} />
                </>
              )}
              {(orderType === 'retirada' || orderType === 'entrega') && (
                <>
                  <div style={{ fontFamily: body, fontSize: 12, fontWeight: 500, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Seu nome</div>
                  <input type="text" value={customerName} onChange={e => setCustomerName(e.target.value)}
                    placeholder="Ex: João Silva"
                    style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface, marginBottom: 12 }} />
                </>
              )}
              <div style={{ fontFamily: body, fontSize: 12, fontWeight: 500, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Telefone (WhatsApp)</div>
              <input type="tel" inputMode="numeric" value={customerPhone}
                onChange={e => setCustomerPhone(formatPhone(e.target.value))}
                placeholder="(51) 99999-9999"
                style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface, marginBottom: 14 }} />

              {/* Forma de pagamento */}
              <div style={{ fontFamily: body, fontSize: 12, fontWeight: 500, color: colors.textSoft, marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.3 }}>Como vai pagar?</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6, marginBottom: orderType === 'entrega' ? 16 : 0 }}>
                {[
                  { v: 'Pix', icon: '💸' },
                  { v: 'Crédito', icon: '💳' },
                  { v: 'Débito', icon: '💳' },
                  { v: 'Dinheiro', icon: '💵' },
                ].map(p => (
                  <button key={p.v} onClick={() => setPaymentMethod(p.v)}
                    style={{
                      padding: '12px 8px', borderRadius: 10,
                      border: `2px solid ${paymentMethod === p.v ? colors.primary : colors.border}`,
                      backgroundColor: paymentMethod === p.v ? colors.primary : colors.surface,
                      color: paymentMethod === p.v ? '#fff' : colors.text,
                      fontFamily: body, fontSize: 13, fontWeight: 600, cursor: 'pointer',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                    }}>
                    <span style={{ fontSize: 16 }}>{p.icon}</span>
                    <span>{p.v}</span>
                  </button>
                ))}
              </div>

              {orderType === 'entrega' && (
                <div style={{ paddingTop: 8, borderTop: `1px dashed ${colors.border}` }}>
                  <div style={{ fontFamily: body, fontSize: 13, fontWeight: 600, color: colors.text, marginBottom: 10 }}>📍 Endereço de entrega</div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
                    <div>
                      <div style={{ fontFamily: body, fontSize: 11, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>CEP</div>
                      <input type="text" inputMode="numeric" value={addrCep}
                        onChange={e => setAddrCep(formatCep(e.target.value))}
                        placeholder="00000-000"
                        style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface }} />
                    </div>
                    <div>
                      <div style={{ fontFamily: body, fontSize: 11, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Número</div>
                      <input type="text" value={addrNumber} onChange={e => setAddrNumber(e.target.value)}
                        placeholder="Ex: 123"
                        style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface }} />
                    </div>
                  </div>
                  <div style={{ fontFamily: body, fontSize: 11, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Rua</div>
                  <input type="text" value={addrStreet} onChange={e => setAddrStreet(e.target.value)}
                    placeholder="Ex: Av. Brasil"
                    style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface, marginBottom: 10 }} />
                  <div style={{ fontFamily: body, fontSize: 11, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Complemento (opcional)</div>
                  <input type="text" value={addrComplement} onChange={e => setAddrComplement(e.target.value)}
                    placeholder="Apto 401, Bloco B..."
                    style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface, marginBottom: 10 }} />
                  <div style={{ fontFamily: body, fontSize: 11, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Bairro</div>
                  <input type="text" value={addrNeighborhood} onChange={e => setAddrNeighborhood(e.target.value)}
                    placeholder="Ex: Centro"
                    style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 15, fontFamily: body, backgroundColor: colors.surface }} />
                </div>
              )}
            </div>
            <div style={{ backgroundColor: colors.surface, borderRadius: 12, marginBottom: 14, border: `1px solid ${colors.border}`, overflow: 'hidden' }}>
              {cart.map(item => (
                <div key={item.productId} style={{ padding: '14px 16px', borderBottom: `1px solid ${colors.border}`, display: 'flex', alignItems: 'center', gap: 10 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontFamily: body, fontSize: 14, fontWeight: 500, color: colors.text }}>{item.name}</div>
                    <div style={{ fontFamily: body, fontSize: 12, color: colors.textMute }}>{fmtBRL(item.price)} · un</div>
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, backgroundColor: colors.surfaceAlt, borderRadius: 999, padding: '4px 6px' }}>
                    <button onClick={() => removeFromCart(item.productId)} style={{ width: 26, height: 26, borderRadius: 999, border: 'none', backgroundColor: colors.surface, color: colors.text, fontSize: 16, cursor: 'pointer' }}>−</button>
                    <span style={{ fontFamily: display, fontSize: 14, fontWeight: 700, minWidth: 18, textAlign: 'center' }}>{item.quantity}</span>
                    <button onClick={() => addToCart({ id: item.productId, name: item.name, price: item.price })} style={{ width: 26, height: 26, borderRadius: 999, border: 'none', backgroundColor: colors.primary, color: '#fff', fontSize: 16, cursor: 'pointer' }}>+</button>
                  </div>
                  <div style={{ fontFamily: display, fontSize: 14, fontWeight: 700, color: colors.text, minWidth: 70, textAlign: 'right' }}>{fmtBRL(item.price * item.quantity)}</div>
                </div>
              ))}
              <div style={{ padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', backgroundColor: colors.surfaceAlt }}>
                <span style={{ fontFamily: body, fontSize: 14, color: colors.textSoft, fontWeight: 500 }}>Total</span>
                <span style={{ fontFamily: display, fontSize: 22, fontWeight: 700, color: colors.primary }}>{fmtBRL(cartTotal)}</span>
              </div>
            </div>
            <div style={{ backgroundColor: colors.surface, borderRadius: 12, padding: 16, marginBottom: 14, border: `1px solid ${colors.border}` }}>
              <div style={{ fontFamily: body, fontSize: 12, fontWeight: 500, color: colors.textSoft, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.3 }}>Observações (opcional)</div>
              <textarea value={notes} onChange={e => setNotes(e.target.value)}
                placeholder="Ex: sem cebola, ponto da carne, alergias..."
                rows={3}
                style={{ width: '100%', padding: '10px 12px', border: `1px solid ${colors.border}`, borderRadius: 8, fontSize: 14, fontFamily: body, resize: 'vertical', backgroundColor: colors.surface }} />
            </div>
            {error && (
              <div style={{ padding: 12, backgroundColor: '#FBEDE8', border: `1px solid ${colors.danger}`, borderRadius: 8, fontSize: 13, color: colors.danger, fontFamily: body, marginBottom: 12 }}>{error}</div>
            )}
            <button onClick={sendOrder} disabled={sending || cart.length === 0}
              style={{
                width: '100%', padding: '16px', backgroundColor: colors.primary, color: '#fff',
                border: 'none', borderRadius: 10, fontFamily: body, fontSize: 16, fontWeight: 600,
                cursor: sending ? 'not-allowed' : 'pointer', opacity: sending ? 0.6 : 1,
              }}>
              {sending ? 'Enviando...' : 'Enviar pedido'}
            </button>
            <p style={{ textAlign: 'center', fontFamily: body, fontSize: 11, color: colors.textMute, marginTop: 10 }}>
              O pagamento será feito no caixa.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

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