const { useState, useEffect, useRef } = React; const CATS = ["Tudo", "Uniformes", "Treino", "Acessórios", "Promoções"]; const HERO_SLIDES = [ { img: "BANNER1.jpeg", cat: "Uniformes" }, { img: "BANNER2.jpeg", cat: "Treino" } ]; const darkenColor = (hex, percent) => { let num = parseInt(hex.replace("#",""), 16), amt = Math.round(2.55 * percent), R = (num >> 16) + amt, G = (num >> 8 & 0x00FF) + amt, B = (num & 0x0000FF) + amt; return "#" + (0x1000000 + (R<255?R<0?0:R:255)*0x10000 + (G<255?G<0?0:G:255)*0x100 + (B<255?B<0?0:B:255)).toString(16).slice(1); }; const Icon = ({ name, size = 20 }) => { const icons = { search: <>, heart: , shoppingBag: <>, menu: <>, x: <>, minus: , plus: <>, trash: <>, user: <>, star: , fileText: <>, whatsapp: , truck: <>, copy: <>, check: , arrowLeft: <>, arrowRight: <>, ticket: <>, mail: <>, phone: <>, users: <>, shield: <>, hanger: <> }; return ( {icons[name] || null} ); }; const AnnouncementBar = ({ text }) => (
{[...Array(6)].map((_, i) => ( {text} ))}
); const Header = ({ cartCount, onCartClick, onMenuToggle, activeCat, onCatSelect, onSearchChange, searchVal, onUserClick, loggedInUser, categories = ["Uniformes", "Treino", "Acessórios"] }) => (
onCatSelect("Tudo")} style={{ display: 'flex', alignItems: 'center', gap: '10px' }}> Genio Imports Logo
GENIOIMPORTS
); const HeroCarousel = ({ onCatSelect, banners: propBanners }) => { const [current, setCurrent] = useState(0); const [fade, setFade] = useState(true); const [slides, setSlides] = useState(HERO_SLIDES); const timerRef = useRef(null); useEffect(() => { if (propBanners && propBanners.length > 0) { setSlides(propBanners.map(b => ({ img: b.image, cat: b.ctaLink || "Tudo", title: b.title, subtitle: b.subtitle, ctaText: b.ctaText }))); } }, [propBanners]); const startTimer = () => { timerRef.current = setInterval(() => { setFade(false); setTimeout(() => { setCurrent(c => (c + 1) % slides.length); setFade(true); }, 400); }, 5500); }; useEffect(() => { startTimer(); return () => clearInterval(timerRef.current); }, [slides.length]); const handleDotClick = (index) => { clearInterval(timerRef.current); setFade(false); setTimeout(() => { setCurrent(index); setFade(true); startTimer(); }, 400); }; return (
{slides.map((slide, i) => (
{slide.title && (

{slide.title}

{slide.subtitle &&

{slide.subtitle}

}
)}
))}
{slides.map((_, i) => (
); }; const ProductCard = ({ product, onAdd, onQuickView, isUserAtacado }) => { const [selectedSize, setSelectedSize] = useState(null); const [wiggle, setWiggle] = useState(false); const discount = product.originalPrice ? Math.round((1 - product.price / product.originalPrice) * 100) : 0; const activePrice = isUserAtacado ? product.atacadoPrice : product.price; const handleAddClick = (e) => { e.stopPropagation(); if (product.sizes && product.sizes.length > 0 && !selectedSize && product.sizes[0] !== "Único") { setWiggle(true); setTimeout(() => setWiggle(false), 500); onAdd(null); // Triggers missing size validation in main return; } onAdd({ ...product, selectedSize }); }; return (
onQuickView(product)}> {product.name} {product.tag && ( {product.tag} )} {discount > 0 && !isUserAtacado && ( -{discount}% )} {isUserAtacado && ( ATACADO )}

{product.cat}

onQuickView(product)}>{product.name}

R$ {activePrice.toFixed(2).replace('.', ',')} {!isUserAtacado && product.originalPrice && ( R$ {product.originalPrice.toFixed(2).replace('.', ',')} )} {isUserAtacado && ( P. Atacado )}
{product.sizes && product.sizes.length > 0 && product.sizes[0] !== "Único" && (
{product.sizes.map(size => ( ))}
)}
); }; const SizeGuideModal = ({ isOpen, onClose }) => { if (!isOpen) return null; return (
e.stopPropagation()}>

Tabela de Medidas

Utilize uma fita métrica para comparar as medidas de uma camisa sua com as medidas da nossa tabela oficial.

Tamanho Largura (cm) Altura (cm) Manga (cm)
P 50 69 22
M 52 71 23
G 54 73 24
GG 57 76 25
XG 60 79 26
); }; const QuickViewModal = ({ product, isOpen, onClose, onAdd, onSizeGuideOpen, isUserAtacado }) => { if (!isOpen || !product) return null; const [selectedSize, setSelectedSize] = useState(null); const [customEnabled, setCustomEnabled] = useState(false); const [customName, setCustomName] = useState(""); const [customNumber, setCustomNumber] = useState(""); const [wiggle, setWiggle] = useState(false); const activePrice = isUserAtacado ? product.atacadoPrice : product.price; const isJersey = product.cat === "Uniformes" || product.cat === "Treino"; const handleAddClick = () => { if (product.sizes && product.sizes.length > 0 && !selectedSize && product.sizes[0] !== "Único") { setWiggle(true); setTimeout(() => setWiggle(false), 500); onAdd(null); // Triggers main toast error return; } onAdd({ ...product, selectedSize: selectedSize || (product.sizes[0] === "Único" ? "Único" : null), personalized: customEnabled && (customName || customNumber), customName: customEnabled ? customName.toUpperCase().slice(0, 12) : "", customNumber: customEnabled ? customNumber.slice(0, 2) : "" }); onClose(); }; return (
e.stopPropagation()}>
{product.name} {product.tag && ( {product.tag} )}

{product.cat}

{product.name}

R$ {activePrice.toFixed(2).replace('.', ',')} {!isUserAtacado && product.originalPrice && ( R$ {product.originalPrice.toFixed(2).replace('.', ',')} )} {isUserAtacado && ( Atacado Ativo )}

{product.desc}

{product.sizes && product.sizes.length > 0 && product.sizes[0] !== "Único" && (
Tamanho
{product.sizes.map(size => ( ))}
)} {isJersey && (
{customEnabled && (
setCustomName(e.target.value.toUpperCase())} />
setCustomNumber(e.target.value.replace(/\D/g, ""))} />
)}
)}
); }; const CartDrawer = ({ isOpen, items, onRemove, onUpdateQty, onClose, onCheckout, couponCode, onApplyCoupon, onRemoveCoupon, appliedCoupon, isUserAtacado }) => { const [couponInput, setCouponInput] = useState(""); const totalItemsCount = items.reduce((acc, item) => acc + item.qty, 0); const isWholesaleActive = isUserAtacado || totalItemsCount >= 6; const baseSubtotal = items.reduce((acc, item) => { const itemUnitPrice = item.price + (item.personalized ? 25.00 : 0); return acc + (itemUnitPrice * item.qty); }, 0); const wholesaleDiscount = (totalItemsCount >= 6 && !isUserAtacado) ? baseSubtotal * 0.2 : 0; const subtotalAfterWholesale = baseSubtotal - wholesaleDiscount; let couponDiscount = 0; if (appliedCoupon) { if (appliedCoupon.code === "IMPORT10") { couponDiscount = subtotalAfterWholesale * 0.1; } else if (appliedCoupon.code === "BEMVINDO") { couponDiscount = subtotalAfterWholesale >= 100 ? 20.00 : 0; } } const finalTotal = subtotalAfterWholesale - couponDiscount; const handleApplyCoupon = () => { if (!couponInput.trim()) return; onApplyCoupon(couponInput.toUpperCase().trim()); setCouponInput(""); }; return (
e.stopPropagation()}>

Sacola de Compras

{items.length === 0 ? (

Sua sacola está vazia

Adicione itens oficiais do Import Atacado e Varejo para começar.

) : ( <>
{items.map(item => { const itemUnitPrice = item.price + (item.personalized ? 25.00 : 0); return (
{item.name}

{item.name}

Tam: {item.selectedSize} {item.personalized && ( Personalizado: {item.customName} ({item.customNumber}) )}
R$ {(itemUnitPrice * item.qty).toFixed(2).replace('.', ',')}
{item.qty}
); })}
{/* Wholesale info */}
{isUserAtacado ? (

🔥 CONTA ATACADO ATIVA: Preços reduzidos de atacado aplicados automaticamente!

) : ( <>
Preço de Atacado (6+ peças) {totalItemsCount}/6

= 6 ? '#25d366' : 'var(--text-muted)', marginTop: 8, fontWeight: 600 }}> {totalItemsCount >= 6 ? "🔥 Desconto de 20% aplicado em todos os produtos!" : `Adicione mais ${6 - totalItemsCount} peças para ativar 20% de desconto.`}

)}
{/* Coupon inputs */} {!appliedCoupon ? (
setCouponInput(e.target.value)} />
) : (
Cupom {appliedCoupon.code} ativo
)} {/* Price Breakdown */}
Subtotal R$ {baseSubtotal.toFixed(2).replace('.', ',')}
{!isUserAtacado && totalItemsCount >= 6 && (
Desconto Atacado (20%) - R$ {wholesaleDiscount.toFixed(2).replace('.', ',')}
)} {appliedCoupon && couponDiscount > 0 && (
Cupom ({appliedCoupon.code}) - R$ {couponDiscount.toFixed(2).replace('.', ',')}
)}
Total R$ {finalTotal.toFixed(2).replace('.', ',')}
)}
); }; const UserModal = ({ isOpen, onClose, loggedInUser, onLogin, onRegister, onLogout, notifications, orders, showToast, loadOrders }) => { const [isLoginView, setIsLoginView] = useState(true); const [activeTab, setActiveTab] = useState("profile"); // profile, notifications, orders useEffect(() => { if (isOpen && loggedInUser) { if (loadOrders) loadOrders(); } }, [isOpen]); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const [phone, setPhone] = useState(""); const [regType, setRegType] = useState("varejo"); // varejo, atacado const handlePhoneInputChange = (val) => { let numbers = val.replace(/\D/g, ""); if (numbers.length > 11) numbers = numbers.slice(0, 11); let formatted = ""; if (numbers.length > 0) { formatted = `(${numbers.slice(0, 2)}`; if (numbers.length > 2) formatted += `) ${numbers.slice(2, 7)}`; if (numbers.length > 7) formatted += `-${numbers.slice(7, 11)}`; } setPhone(formatted); }; const handleLoginSubmit = (e) => { e.preventDefault(); if (!email || !password) { showToast("Preencha todos os campos.", "error"); return; } fetch('api.php?action=login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }) }) .then(r => { const contentType = r.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return r.json(); } throw new Error("API not JSON"); }) .then(data => { if (data.error) { showToast(data.error, "error"); } else { if (data.status === 'Pendente') { showToast("Seu cadastro ainda está pendente de aprovação pelo administrador.", "error"); } else if (data.status === 'Bloqueado') { showToast("Esta conta foi bloqueada pelo administrador.", "error"); } else { onLogin(data); showToast(`Bem-vindo, ${data.name}!`); onClose(); } } }) .catch(() => { showToast("Erro de conexão com o servidor. Tente novamente.", "error"); }); }; const handleRegisterSubmit = (e) => { e.preventDefault(); if (!name || !email || !password || !phone) { showToast("Preencha todos os campos obrigatórios.", "error"); return; } if (phone.length < 14) { showToast("Por favor, insira um WhatsApp válido com DDD.", "error"); return; } fetch('api.php?action=register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, email, password, phone, type: regType }) }) .then(r => { const contentType = r.headers.get("content-type"); if (contentType && contentType.indexOf("application/json") !== -1) { return r.json(); } throw new Error("API not JSON"); }) .then(data => { if (data.error) { showToast(data.error, "error"); } else { if (data.status === 'Aprovado') { showToast("Cadastro realizado com sucesso! Você já pode fazer login."); } else { showToast("Cadastro realizado! Aguarde a aprovação do admin para acessar."); } setIsLoginView(true); setEmail(email); setPassword(""); } }) .catch(() => { showToast("Erro de conexão com o servidor. Tente novamente.", "error"); }); }; const [pushSupported, setPushSupported] = useState(false); const [pushSubscribed, setPushSubscribed] = useState(false); const [installAvailable, setInstallAvailable] = useState(false); const [deferredPrompt, setDeferredPrompt] = useState(null); const [selectedOrder, setSelectedOrder] = useState(null); useEffect(() => { if ('Notification' in window && 'serviceWorker' in navigator) { setPushSupported(true); navigator.serviceWorker.ready.then(reg => { reg.pushManager.getSubscription().then(sub => { if (sub) setPushSubscribed(true); }); }).catch(() => {}); } const handler = (e) => { e.preventDefault(); setDeferredPrompt(e); setInstallAvailable(true); }; window.addEventListener('beforeinstallprompt', handler); if (window.matchMedia('(display-mode: standalone)').matches) { setInstallAvailable(false); } window.addEventListener('appinstalled', () => { setDeferredPrompt(null); setInstallAvailable(false); }); return () => window.removeEventListener('beforeinstallprompt', handler); }, []); const handleInstallPwa = async () => { if (!deferredPrompt) return; deferredPrompt.prompt(); await deferredPrompt.userChoice; setDeferredPrompt(null); setInstallAvailable(false); }; const handleRequestPush = async () => { try { const permission = await Notification.requestPermission(); if (permission === 'granted') { const reg = await navigator.serviceWorker.ready; const settingsRes = await fetch('api.php?action=settings').then(r => r.json()).catch(() => ({})); let vapidKey = null; if (settingsRes.vapid && settingsRes.vapid.publicKey) { try { vapidKey = Uint8Array.from(atob(settingsRes.vapid.publicKey.replace(/-/g,'+').replace(/_/g,'/')), c => c.charCodeAt(0)); } catch(e) {} } const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidKey }).catch(() => null); if (sub) { setPushSubscribed(true); fetch('api.php?action=save_push_subscription', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: loggedInUser?.email || 'guest', subscription: JSON.stringify(sub) }) }).catch(() => {}); showToast("Notificações ativadas! ✅"); } else { showToast("Notificações ativadas! (sem push server)", "success"); } } else { showToast("Permissão de notificações negada.", "error"); } } catch(e) { showToast("Erro ao ativar notificações.", "error"); } }; const userNotifs = loggedInUser ? notifications.filter(n => n.target === "all" || n.target === loggedInUser.type || n.target === loggedInUser.email) : []; const userOrders = loggedInUser ? orders.filter(o => { const cId = (o.customerId || '').toString(); const uId = (loggedInUser.id || '').toString(); const uEmail = (loggedInUser.email || '').toLowerCase(); return cId === uId || cId === uEmail; }) : []; if (!isOpen) return null; return (
e.stopPropagation()}> {loggedInUser ? (
{/* User Header */}
{loggedInUser.name.charAt(0).toUpperCase()}

{loggedInUser.name}

{loggedInUser.email}

{/* Tabs */}
{/* PROFILE TAB */} {activeTab === "profile" && (
{/* Instalar App PWA */} {installAvailable && (
📲
Instalar App

Adicione à tela inicial para acesso rápido

)} {/* Push notification toggle diretamente no Perfil */} {pushSupported && (
🔔
Notificações Push

Receba alertas de pedidos e promoções

)}
{userOrders.length}
Pedidos
{userNotifs.length}
Notificações

Dados Pessoais

Nome {loggedInUser.name}
E-mail {loggedInUser.email}
WhatsApp {loggedInUser.phone || 'Não informado'}
Tipo de Conta {loggedInUser.type === 'atacado' ? 'Parceiro Atacado' : 'Varejo'}
)} {/* NOTIFICATIONS TAB */} {activeTab === "notifications" && (
{/* PWA Install banner */} {installAvailable && (
Instalar App

📲 Adicione à tela inicial para acesso rápido

)} {/* Push notification toggle */} {/* Push notification banner - destaque */} {pushSupported && (
Notificações Push

{pushSubscribed ? '✅ Ativadas — você receberá alertas mesmo fora do site' : '🔔 Ative para receber avisos de pedidos e promoções'}

)} {userNotifs.length === 0 ? (

Nenhuma notificação recebida.

) : (
{userNotifs.map(notif => (
{notif.title} {notif.date}

{notif.message}

))}
)}
)} {/* ORDERS TAB */} {activeTab === "orders" && (
{userOrders.length === 0 ? (

Nenhum pedido realizado ainda.

Seus pedidos aparecerão aqui após a compra.

) : (
{userOrders.map(order => ( ))}
)}
)}
) : (
{isLoginView ? (

Acessar Conta

setEmail(e.target.value)} />
setPassword(e.target.value)} />

Não tem uma conta?

) : (

Criar Conta

setName(e.target.value)} />
setEmail(e.target.value)} />
setPassword(e.target.value)} />
handlePhoneInputChange(e.target.value)} />

Já tem conta?

)}
)}
{/* Order Detail Modal */} {selectedOrder && (
setSelectedOrder(null)} style={{ position: 'fixed', inset: 0, zIndex: 9999, display: 'flex', alignItems: 'center', justifyContent: 'center' }} >
e.stopPropagation()} style={{ background: '#1e293b', borderRadius: 16, maxWidth: 480, width: '92%', maxHeight: '85vh', overflowY: 'auto', padding: '28px 24px', boxShadow: '0 20px 60px rgba(0,0,0,0.5)', border: '1px solid rgba(255,255,255,0.08)' }} >

📦 {selectedOrder.id}

{selectedOrder.status === 'Pendente' ? 'Aguardando' : selectedOrder.status === 'Processando' ? 'Pago / Processando' : selectedOrder.status} {selectedOrder.date ? selectedOrder.date.substring(0, 19).replace('T', ' ') : selectedOrder.date}

👤 Cliente

E-mail / ID {selectedOrder.customerId || '-'}
Entrega {selectedOrder.shipping?.address || selectedOrder.shipping?.method || '-'}

💳 Pagamento

Método {selectedOrder.payment?.method || '-'}
{selectedOrder.payment?.couponCode && (
🎟️ Cupom {selectedOrder.payment.couponCode}
)} {selectedOrder.payment?.payment_id && selectedOrder.payment?.payment_id !== 'Cupom 100%' && (
ID Transa\u00e7\u00e3o {selectedOrder.payment.payment_id}
)}

🛒 Itens

{(selectedOrder.items || []).map((it, idx) => { const itemName = typeof it === 'string' ? it : (it.name || 'Item'); const itemQty = it.qty || 1; const itemSize = it.size ? '(' + it.size + ')' : ''; const itemPrice = it.price || 0; return (
{itemName} {itemSize} x{itemQty} R$ {(itemPrice * itemQty).toFixed(2).replace('.', ',')}
); })}

💰 Resumo Financeiro

Subtotal R$ {(selectedOrder.pricing?.subtotal || 0).toFixed(2).replace('.', ',')}
{selectedOrder.pricing?.discount > 0 && (
Desconto - R$ {(selectedOrder.pricing?.discount || 0).toFixed(2).replace('.', ',')}
)}
Total R$ {(selectedOrder.pricing?.total || 0).toFixed(2).replace('.', ',')}
{(selectedOrder.history || []).length > 0 && (

📋 Rastreador do Pedido

{(selectedOrder.history || []).map((h, idx) => { const statusText = h.status === 'Pendente' ? '⏳ Aguardando' : h.status === 'Processando' ? '✅ Pago / Processando' : h.status === 'Enviado' ? '🚚 Enviado' : h.status === 'Entregue' ? '📦 Entregue' : h.status === 'Cancelado' ? '❌ Cancelado' : h.status; return (
{idx < (selectedOrder.history || []).length - 1 && (
)}
{statusText} {h.date ? h.date.substring(0, 19).replace('T', ' ') : h.date}
); })}
)}
)}
); }; const CheckoutModal = ({ isOpen, onClose, cartItems, appliedCoupon, onClearCart, showToast, loggedInUser, settings }) => { if (!isOpen) return null; const [step, setStep] = useState(1); const [formData, setFormData] = useState({ name: loggedInUser ? loggedInUser.name : "", phone: loggedInUser ? loggedInUser.phone : "", email: loggedInUser ? loggedInUser.email : "", deliveryMethod: "pickup", zipCode: "", street: "", number: "", neighborhood: "", complement: "", cityState: "", paymentMethod: "pix" }); const [copiedKey, setCopiedKey] = useState(false); const [mpPayment, setMpPayment] = useState(null); // { payment_id, qr_code_base64, ticket_url, status } const [mpLoading, setMpLoading] = useState(false); const [mpChecking, setMpChecking] = useState(false); const [paymentSuccess, setPaymentSuccess] = useState(false); const [orderId, setOrderId] = useState(null); const [shippingOptions, setShippingOptions] = useState([]); const [shippingLoading, setShippingLoading] = useState(false); const [selectedShippingOption, setSelectedShippingOption] = useState(null); const [shippingError, setShippingError] = useState(""); useEffect(() => { if (loggedInUser) { setFormData(prev => ({ ...prev, name: loggedInUser.name, phone: loggedInUser.phone, email: loggedInUser.email })); } }, [loggedInUser]); console.log("CheckoutModal settings:", settings); const settingsLoading = settings === null; const siteSettings = settings || {}; const pixKey = siteSettings.pixKey || "0536412589000185"; const mpToken = siteSettings.mercadopagoToken || ""; const totalItemsCount = cartItems.reduce((acc, item) => acc + item.qty, 0); const isUserAtacado = loggedInUser && loggedInUser.type === "atacado"; const baseSubtotal = cartItems.reduce((acc, item) => { const itemUnitPrice = item.price + (item.personalized ? 25.00 : 0); return acc + (itemUnitPrice * item.qty); }, 0); const wholesaleDiscount = (totalItemsCount >= 6 && !isUserAtacado) ? baseSubtotal * 0.2 : 0; const subtotalAfterWholesale = baseSubtotal - wholesaleDiscount; let couponDiscount = 0; if (appliedCoupon) { if (appliedCoupon.type === 'percent') { couponDiscount = subtotalAfterWholesale * (appliedCoupon.value / 100); } else if (appliedCoupon.type === 'fixed') { couponDiscount = Math.min(appliedCoupon.value, subtotalAfterWholesale); } } const isFreeOrder = subtotalAfterWholesale - couponDiscount <= 0; // Free shipping threshold check const freeThreshold = parseFloat(siteSettings.freeShippingThreshold || 250); const isFreeShippingEligible = (subtotalAfterWholesale - couponDiscount) >= freeThreshold; let deliveryFee = 0; if (formData.deliveryMethod === "delivery" && !isFreeOrder) { if (siteSettings.superfrete?.enabled) { if (selectedShippingOption) { deliveryFee = isFreeShippingEligible ? 0 : selectedShippingOption.price; } else { deliveryFee = isFreeShippingEligible ? 0 : 15.00; // robust fallback to default fee } } else { deliveryFee = isFreeShippingEligible ? 0 : 15.00; } } const finalTotal = subtotalAfterWholesale - couponDiscount + deliveryFee; const calculateSuperFrete = (zip) => { if (!siteSettings.superfrete?.enabled) return; setShippingLoading(true); setShippingError(""); setShippingOptions([]); setSelectedShippingOption(null); fetch('api.php?action=calculate_shipping', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cep: zip, items: cartItems.map(item => ({ id: item.id, qty: item.qty })) }) }) .then(r => r.json()) .then(data => { if (data.success && Array.isArray(data.services)) { const validServices = data.services .filter(s => !s.has_error && s.price !== undefined) .map(s => ({ id: s.id, name: s.name, price: parseFloat(s.price), discount: parseFloat(s.discount || 0), deliveryTime: s.delivery_time, company: s.company?.name || 'Transportadora' })); setShippingOptions(validServices); if (validServices.length > 0) { setSelectedShippingOption(validServices[0]); } } else { setShippingError(data.error || "Erro ao calcular frete."); } }) .catch(() => { setShippingError("Erro de conexão ao calcular frete."); }) .finally(() => { setShippingLoading(false); }); }; const handleInputChange = (field, val) => { setFormData(prev => ({ ...prev, [field]: val })); }; const handlePhoneChange = (val) => { let numbers = val.replace(/\D/g, ""); if (numbers.length > 11) numbers = numbers.slice(0, 11); let formatted = ""; if (numbers.length > 0) { formatted = `(${numbers.slice(0, 2)}`; if (numbers.length > 2) formatted += `) ${numbers.slice(2, 7)}`; if (numbers.length > 7) formatted += `-${numbers.slice(7, 11)}`; } handleInputChange("phone", formatted); }; const handleZipChange = (val) => { let numbers = val.replace(/\D/g, ""); if (numbers.length > 8) numbers = numbers.slice(0, 8); let formatted = numbers; if (numbers.length > 5) formatted = `${numbers.slice(0, 5)}-${numbers.slice(5, 8)}`; handleInputChange("zipCode", formatted); if (numbers.length === 8) { fetch(`api.php?action=viacep&cep=${numbers}`) .then(r => r.json()) .then(data => { if (data.success) { setFormData(prev => ({ ...prev, street: data.logradouro, neighborhood: data.bairro, cityState: `${data.cidade} - ${data.uf}` })); if (siteSettings.superfrete?.enabled) { calculateSuperFrete(numbers); } } }) .catch(() => {}); } }; const handleNext = () => { if (step === 1) { if (!formData.name.trim() || formData.phone.length < 14) { showToast("Preencha Nome e WhatsApp com DDD.", "error"); return; } const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if (!formData.email.trim() || !emailRegex.test(formData.email.trim())) { showToast("Por favor, insira um e-mail válido (obrigatório para pagamento Pix).", "error"); return; } setStep(2); } else if (step === 2) { if (formData.deliveryMethod === "delivery") { if (!formData.zipCode || !formData.street || !formData.number || !formData.neighborhood || !formData.cityState) { showToast("Preencha todos os campos de endereço.", "error"); return; } if (siteSettings.superfrete?.enabled && !selectedShippingOption && !shippingLoading && !shippingError) { showToast("Aguarde o cálculo ou selecione uma opção de frete.", "error"); return; } } if (isFreeOrder) { createOrderInDB('Cupom 100%', 'Cupom 100%').then(() => { setPaymentSuccess(true); showToast("🎉 Pedido realizado com sucesso! Cupom de 100% aplicado."); }); } else { setStep(3); } } else if (step === 3) { setStep(4); } }; const handleBack = () => { if (step > 1) setStep(step - 1); }; const handleCopyPixKey = () => { navigator.clipboard.writeText(pixKey).then(() => { setCopiedKey(true); showToast("Chave Pix copiada!"); setTimeout(() => setCopiedKey(false), 3000); }); }; const createOrderInDB = async (paymentId, paymentMethod) => { const orderData = { customerId: loggedInUser ? (loggedInUser.id || loggedInUser.email) : 'Guest', items: cartItems.map(item => ({ id: item.id, name: item.name, qty: item.qty, size: item.selectedSize, price: item.price })), shipping: { method: formData.deliveryMethod === "delivery" ? (selectedShippingOption ? `${selectedShippingOption.name} (${selectedShippingOption.company})` : 'Correios') : 'Retirada', address: formData.deliveryMethod === "delivery" ? `${formData.street}, Nº ${formData.number}, Bairro ${formData.neighborhood}, CEP ${formData.zipCode}, ${formData.cityState}` : 'Retirada' }, payment: { method: paymentMethod, payment_id: paymentId, couponCode: appliedCoupon?.code || '' }, pricing: { subtotal: baseSubtotal, discount: baseSubtotal - finalTotal, total: finalTotal } }; try { const res = await fetch('api.php?action=create_order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(orderData) }); const data = await res.json(); if (data && data.id) { setOrderId(data.id); if (window.trackPurchase) { window.trackPurchase(data.id, cartItems.map(item => ({ id: item.id, name: item.name, price: item.price, qty: item.qty })), finalTotal); } return data.id; } } catch (e) {} const fallbackId = "ORD-" + Date.now().toString(36).toUpperCase(); setOrderId(fallbackId); return fallbackId; }; const handleGeneratePix = async () => { if (!mpToken) { showToast("Token do Mercado Pago não configurado. Configure no Admin.", "error"); return; } setMpLoading(true); try { const generatedOrderId = await createOrderInDB('Gerando...', 'Mercado Pago Pix'); const res = await fetch('api.php?action=mp_create_payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ amount: finalTotal, description: `Pedido Import FC - ${generatedOrderId}`, payerEmail: formData.email, payerName: formData.name, orderId: generatedOrderId }) }); const data = await res.json(); if (data.success) { setMpPayment({ payment_id: data.payment_id, qr_code_base64: data.qr_code_base64, qr_code: data.qr_code, ticket_url: data.ticket_url, status: data.status }); showToast("QR Code gerado! Pague com Pix."); } else { showToast(data.error || "Erro ao gerar QR Code.", "error"); } } catch (e) { showToast("Erro de conexão com Mercado Pago.", "error"); } setMpLoading(false); }; const handleCheckPayment = async () => { if (!mpPayment || !mpPayment.payment_id) return; setMpChecking(true); try { const res = await fetch('api.php?action=mp_check_payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentId: mpPayment.payment_id }) }); const data = await res.json(); if (data.success) { if (data.status === 'approved') { setPaymentSuccess(true); showToast("Pagamento confirmado! Pedido realizado com sucesso!"); } else if (data.status === 'pending') { showToast("Pagamento ainda pendente. Aguarde a confirmação ou tente novamente.", "error"); } else if (data.status === 'cancelled' || data.status === 'rejected') { showToast("Pagamento não foi realizado. Tente novamente.", "error"); } else { showToast(`Status: ${data.status}. Aguarde a confirmação.`); } } else { showToast(data.error || "Erro ao verificar pagamento.", "error"); } } catch (e) { showToast("Erro ao verificar pagamento.", "error"); } setMpChecking(false); }; if (paymentSuccess) { const isFree = (appliedCoupon && couponDiscount > 0 && (subtotalAfterWholesale - couponDiscount <= 0)) || false; return (
e.stopPropagation()} style={{ maxWidth: 440 }}>
{/* Animated checkmark */}
{isFree ? ( <> ) : ( )}

{isFree ? '🎉 Pedido Confirmado!' : '✅ Pagamento Confirmado!'}

Pedido {orderId}

{isFree ? (

🎟️ Cupom de 100% aplicado!

Seu pedido foi registrado sem custos.

) : (

💰 Pagamento aprovado com sucesso!

)}

Você pode acompanhar o status em Minha Conta {'>'} Pedidos.

); } return (
e.stopPropagation()}>
1 ? 'completed' : ''}`}>1
2 ? 'completed' : ''}`}>2
3
{step === 1 && (

1. Dados de Contato

handleInputChange("name", e.target.value)} />
handlePhoneChange(e.target.value)} />
handleInputChange("email", e.target.value)} />
)} {step === 2 && (

2. Método de Envio

handleInputChange("deliveryMethod", "pickup")}>
Retirar no Ninho do Import
Disponível em 24h úteis
Grátis
handleInputChange("deliveryMethod", "delivery")}>
Entrega via Motoboy ou Correios
Entrega rápida para o seu endereço
{isFreeShippingEligible ? 'Grátis' : ( siteSettings.superfrete?.enabled ? (selectedShippingOption ? `R$ ${selectedShippingOption.price.toFixed(2).replace('.', ',')}` : 'A calcular') : 'R$ 15,00' )}
{formData.deliveryMethod === "delivery" && (
handleZipChange(e.target.value)} />
handleInputChange("number", e.target.value)} />
handleInputChange("street", e.target.value)} />
handleInputChange("neighborhood", e.target.value)} />
handleInputChange("complement", e.target.value)} />
handleInputChange("cityState", e.target.value)} />
{/* SuperFrete Options Select */} {siteSettings.superfrete?.enabled && formData.zipCode.replace(/\D/g, "").length === 8 && (
🚚 Opções de Envio Disponíveis {shippingLoading && (

Calculando frete com a SuperFrete...

)} {shippingError && (

⚠️ Erro ao calcular com SuperFrete: {shippingError}

Utilizando taxa fixa padrão de R$ 15,00 para prosseguir com a entrega.

)} {!shippingLoading && !shippingError && shippingOptions.length === 0 && (

Digite um CEP válido para calcular as opções de frete.

)} {!shippingLoading && shippingOptions.length > 0 && (
{shippingOptions.map(opt => { const isSelected = selectedShippingOption?.id === opt.id; return (
setSelectedShippingOption(opt)} >
{opt.name} ({opt.company}) Prazo estimado: {opt.deliveryTime} {opt.deliveryTime === 1 ? 'dia útil' : 'dias úteis'}
{isFreeShippingEligible ? 'Grátis' : `R$ ${opt.price.toFixed(2).replace('.', ',')}`}
); })}
)}
)}
)}
)} {step === 3 && (

3. Pagamento via Pix

{settingsLoading && (

Carregando dados de pagamento...

)} {!settingsLoading && !mpToken && (

Token do Mercado Pago não configurado

Configure o Access Token do Mercado Pago no painel Admin para gerar QR Codes de pagamento reais.

)} {!settingsLoading && mpToken && !mpPayment && (

Clique abaixo para gerar o QR Code Pix via Mercado Pago.

Total a Pagar R$ {finalTotal.toFixed(2).replace('.', ',')}
)} {mpPayment && (

Escaneie o QR Code abaixo ou copie a chave Pix.

{mpPayment.qr_code_base64 && (
QR Code Pix
)} {mpPayment.qr_code && (
{mpPayment.qr_code}
)} {mpPayment.ticket_url && ( Abrir no Mercado Pago )}
Total a Pagar R$ {finalTotal.toFixed(2).replace('.', ',')}
)}
)}
{step > 1 && ( )} {step < 3 && ( )}
); }; function NovaStore() { const [cat, setCat] = useState("Tudo"); const [cart, setCart] = useState([]); const [searchVal, setSearchVal] = useState(""); const [sortBy, setSortBy] = useState("default"); const [products, setProducts] = useState([]); const [settings, setSettings] = useState(null); const [notifications, setNotifications] = useState([]); const [orders, setOrders] = useState([]); const [banners, setBanners] = useState([]); const [loggedInUser, setLoggedInUser] = useState(null); const [showCart, setShowCart] = useState(false); const [showMenu, setShowMenu] = useState(false); const [quickViewProduct, setQuickViewProduct] = useState(null); const [showSizeGuide, setShowSizeGuide] = useState(false); const [showCheckout, setShowCheckout] = useState(false); const [showUserModal, setShowUserModal] = useState(false); const [appliedCoupon, setAppliedCoupon] = useState(null); const [toast, setToast] = useState({ show: false, message: '', type: 'success' }); const showToastMsg = (message, type = 'success') => { setToast({ show: true, message, type }); setTimeout(() => { setToast(prev => ({ ...prev, show: false })); }, 3500); }; const syncStoreData = () => { fetch('api.php?action=products') .then(r => r.json()) .then(data => { if (Array.isArray(data) && data.length > 0) { const storeProducts = data.map(p => ({ id: p.id, name: p.name, price: p.price, originalPrice: p.oldPrice, cat: p.category, img: p.images && p.images.length > 0 ? p.images[0] : '', tag: '', sizes: p.sizes || ['P', 'M', 'G', 'GG', 'XG'], type: 'atacado_varejo', atacadoPrice: (p.wholesaleTiers && p.wholesaleTiers.length > 1) ? p.wholesaleTiers[1].price : p.price, desc: p.description || '' })); setProducts(storeProducts); } }) .catch(() => {}); fetch('api.php?action=settings') .then(r => r.json()) .then(data => { if (data && !data.error) { const merged = { accentColor: '#38B6FF', announcementText: '', pixKey: '', phone: '', mercadopagoToken: '' }; if (data.general) Object.assign(merged, data.general); if (data.apiKeys) { if (data.apiKeys.mercadopagoToken) merged.mercadopagoToken = data.apiKeys.mercadopagoToken; } if (data.payments) Object.assign(merged, data.payments); if (data.superfrete) merged.superfrete = data.superfrete; setSettings(merged); if (merged.accentColor) { document.documentElement.style.setProperty('--accent-gold', merged.accentColor); document.documentElement.style.setProperty('--accent-gold-hover', darkenColor(merged.accentColor, -10)); } } }) .catch(() => {}); fetch('api.php?action=notifications') .then(r => r.json()) .then(data => { if (Array.isArray(data)) setNotifications(data); }) .catch(() => {}); fetch('api.php?action=banners') .then(r => r.json()) .then(data => { if (Array.isArray(data) && data.length > 0) setBanners(data); }) .catch(() => {}); }; useEffect(() => { syncStoreData(); loadOrders(); try { const savedCart = sessionStorage.getItem("import_cart"); if (savedCart) setCart(JSON.parse(savedCart)); } catch(e) {} try { const savedCoupon = sessionStorage.getItem("import_coupon"); if (savedCoupon) setAppliedCoupon(JSON.parse(savedCoupon)); } catch(e) {} fetch('api.php?action=session') .then(r => r.json()) .then(user => { if (user) setLoggedInUser(user); }) .catch(() => {}); fetch('api.php?action=products') .then(r => r.json()) .then(data => { if (Array.isArray(data) && data.length > 0) { const storeProducts = data.map(p => ({ id: p.id, name: p.name, price: p.price, originalPrice: p.oldPrice, cat: p.category, img: p.images && p.images.length > 0 ? p.images[0] : '', tag: p.brand || '', sizes: p.sizes || ['P', 'M', 'G', 'GG', 'XG'], type: 'atacado_varejo', atacadoPrice: (p.wholesaleTiers && p.wholesaleTiers.length > 1) ? p.wholesaleTiers[1].price : p.price, desc: p.description || '' })); setProducts(storeProducts); } }) .catch(() => {}); }, []); const saveCartToStorage = (newCart) => { setCart(newCart); sessionStorage.setItem("import_cart", JSON.stringify(newCart)); }; const addToCart = (product) => { if (product === null) { showToastMsg("Selecione um tamanho antes de adicionar!", "error"); return; } const isUserAtacado = loggedInUser && loggedInUser.type === "atacado"; const cartPrice = isUserAtacado ? product.atacadoPrice : product.price; const customKey = `${product.id}_${product.selectedSize}_${product.customName || ''}_${product.customNumber || ''}`; const exists = cart.find(item => item.cartId === customKey); let newCart; if (exists) { newCart = cart.map(item => item.cartId === customKey ? { ...item, qty: item.qty + 1 } : item); showToastMsg(`Quantidade de ${product.name} atualizada na sacola!`); } else { newCart = [...cart, { ...product, price: cartPrice, cartId: customKey, qty: 1 }]; showToastMsg(`${product.name} adicionado à sacola!`); } saveCartToStorage(newCart); setShowCart(true); if (window.trackAddToCart) { window.trackAddToCart({ id: product.id, name: product.name, category: product.cat, price: cartPrice, selectedColor: product.selectedColor || '', selectedSize: product.selectedSize || '' }, 1); } if (window.fbq) { fbq('track', 'AddToCart', { content_name: product.name, content_ids: [product.id], content_type: 'product', value: cartPrice, currency: 'BRL' }); } }; const removeFromCart = (cartId) => { const item = cart.find(i => i.cartId === cartId); if (item) { showToastMsg(`${item.name} removido.`); if (window.trackRemoveFromCart) { window.trackRemoveFromCart({ id: item.id, name: item.name, price: item.price }); } } saveCartToStorage(cart.filter(i => i.cartId !== cartId)); }; const updateQty = (cartId, delta) => { const newCart = cart.map(item => { if (item.cartId !== cartId) return item; const newQty = item.qty + delta; return newQty > 0 ? { ...item, qty: newQty } : item; }).filter(item => item.qty > 0); saveCartToStorage(newCart); }; const checkPendingOrders = (fetchedOrders) => { fetchedOrders.forEach(ord => { if (ord.status === 'Pendente' || ord.status === 'Pending') { let paymentInfo = null; try { paymentInfo = typeof ord.payment === 'string' ? JSON.parse(ord.payment) : ord.payment; } catch(e) {} if (paymentInfo && paymentInfo.payment_id && paymentInfo.payment_id !== 'Cupom 100%' && paymentInfo.payment_id !== 'Gerando...') { fetch('api.php?action=mp_check_payment', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ paymentId: paymentInfo.payment_id }) }) .then(r => r.json()) .then(res => { if (res.status === 'approved') { showToastMsg("🎉 Pagamento aprovado! Seu pedido já está sendo processado."); fetch('api.php?action=my_orders') .then(r => r.json()) .then(updatedData => { if (Array.isArray(updatedData)) setOrders(updatedData); }) .catch(() => {}); } }).catch(() => {}); } } }); }; function loadOrders() { fetch('api.php?action=my_orders') .then(r => r.json()) .then(data => { if (Array.isArray(data)) { setOrders(data); checkPendingOrders(data); } }) .catch(() => {}); } const clearCart = () => { saveCartToStorage([]); setAppliedCoupon(null); sessionStorage.removeItem("import_coupon"); loadOrders(); }; const handleUserLogin = (user) => { setLoggedInUser(user); loadOrders(); if (user.type === "atacado") { const updatedCart = cart.map(item => { const matchingProduct = products.find(p => p.id === item.id); if (matchingProduct) { return { ...item, price: matchingProduct.atacadoPrice }; } return item; }); saveCartToStorage(updatedCart); } }; const handleUserLogout = () => { setLoggedInUser(null); showToastMsg("Você saiu da conta."); setShowUserModal(false); const updatedCart = cart.map(item => { const matchingProduct = products.find(p => p.id === item.id); if (matchingProduct) { return { ...item, price: matchingProduct.price }; } return item; }); saveCartToStorage(updatedCart); }; const applyCoupon = (code) => { const uppercase = code.toUpperCase().trim(); fetch('api.php?action=coupons') .then(r => r.json()) .then(activeCoupons => { if (Array.isArray(activeCoupons)) { const found = activeCoupons.find(c => c.code.toUpperCase() === uppercase); if (found) { if (found.maxUses > 0 && (found.timesUsed || 0) >= found.maxUses) { showToastMsg("Este cupom já atingiu o limite de usos.", "error"); return; } if (found.targetUserType && found.targetUserType !== 'all') { const userType = loggedInUser ? loggedInUser.type : 'varejo'; if (found.targetUserType !== userType) { showToastMsg(`Este cupom é exclusivo para clientes de ${found.targetUserType === 'atacado' ? 'Atacado' : 'Varejo'}.`, "error"); return; } } setAppliedCoupon(found); sessionStorage.setItem("import_coupon", JSON.stringify(found)); showToastMsg(`🎟️ Cupom ${found.code} aplicado!`); } else { showToastMsg("Cupom inválido ou expirado.", "error"); } } else { showToastMsg("Cupom inválido ou expirado.", "error"); } }) .catch(() => { showToastMsg("Erro ao validar cupom.", "error"); }); }; const removeCoupon = () => { setAppliedCoupon(null); showToastMsg("Cupom removido do carrinho."); }; let filtered = cat === "Tudo" ? products : cat === "Promoções" ? products.filter(p => p.tag === "Sale" || p.tag === "Oferta" || p.originalPrice > p.price) : cat === "Lançamentos" ? products.filter(p => p.tag === "Lançamento" || p.tag === "Lançamentos") : products.filter(p => p.cat === cat); if (searchVal.trim() !== "") { const q = searchVal.toLowerCase(); filtered = filtered.filter(p => p.name.toLowerCase().includes(q) || p.cat.toLowerCase().includes(q) || p.desc.toLowerCase().includes(q)); } if (sortBy === "price_asc") { filtered = [...filtered].sort((a, b) => { const pA = loggedInUser && loggedInUser.type === "atacado" ? a.atacadoPrice : a.price; const pB = loggedInUser && loggedInUser.type === "atacado" ? b.atacadoPrice : b.price; return pA - pB; }); } else if (sortBy === "price_desc") { filtered = [...filtered].sort((a, b) => { const pA = loggedInUser && loggedInUser.type === "atacado" ? a.atacadoPrice : a.price; const pB = loggedInUser && loggedInUser.type === "atacado" ? b.atacadoPrice : b.price; return pB - pA; }); } const cartCount = cart.reduce((s, item) => s + item.qty, 0); const sectionTitle = cat === "Tudo" ? "TODOS OS PRODUTOS" : cat === "Promoções" ? "OFERTAS ESPECIAIS" : cat === "Lançamentos" ? "NOVIDADES / LANÇAMENTOS" : cat.toUpperCase(); const announcementText = settings ? settings.announcementText : "🔥 PROMOÇÃO DE LANÇAMENTO: USE O CUPOM IMPORT10 E GANHE 10% OFF!"; const availableCategories = settings && Array.isArray(settings.categories) ? settings.categories : ["Seleções", "Brasileiros", "Internacional", "Kit Completo", "Kit Infantil"]; const catsList = ["Tudo", ...availableCategories, "Lançamentos", "Promoções"]; return (
setShowCart(true)} onMenuToggle={() => setShowMenu(!showMenu)} activeCat={cat} onCatSelect={(category) => { setCat(category); window.scrollTo({ top: 500, behavior: 'smooth' }); }} searchVal={searchVal} onSearchChange={(e) => setSearchVal(e.target.value)} onUserClick={() => setShowUserModal(true)} loggedInUser={loggedInUser} categories={availableCategories} /> {/* Mobile Menu */}
{catsList.map(c => ( ))} {!loggedInUser ? ( ) : ( )}
{ setCat(category); window.scrollTo({ top: 560, behavior: 'smooth' }); }} banners={banners} />

{sectionTitle}

Produtos oficiais do Import Atacado e Varejo com acabamento premium e tecnologia esportiva.

{/* Store Controls */}
{catsList.map(c => ( ))}
{ setSearchVal(e.target.value); if (e.target.value.length > 2 && window.trackSearch) { window.trackSearch(e.target.value); } }} />
{filtered.map(p => ( { setQuickViewProduct(prod); if (window.trackProductView) { window.trackProductView({ id: prod.id, name: prod.name, category: prod.cat, price: prod.price }); } if (window.fbq) { fbq('track', 'ViewContent', { content_name: prod.name, content_ids: [prod.id], content_type: 'product', value: prod.price, currency: 'BRL' }); } }} isUserAtacado={loggedInUser && loggedInUser.type === "atacado"} /> ))}
{filtered.length === 0 && (

Nenhum item oficial encontrado.

Tente pesquisar com outro termo ou selecione outra categoria.

)}
{/* Benefits */}

BENEFÍCIOS EXCLUSIVOS

Envio Rápido

Frete grátis acima de R$ 250 ou taxa fixa de R$ 15 para todo o Brasil.

Qualidade Premium

Escudos bordados de alta definição e tecidos Dry-Fit oficiais.

Satisfação Garantida

Troca facilitada sem burocracia ou suporte dedicado via chat.

{/* Footer */} {/* Cart Drawer */} setShowCart(false)} onCheckout={() => { setShowCart(false); setShowCheckout(true); }} appliedCoupon={appliedCoupon} onApplyCoupon={applyCoupon} onRemoveCoupon={removeCoupon} isUserAtacado={loggedInUser && loggedInUser.type === "atacado"} /> {/* Quick View Modal */} setQuickViewProduct(null)} onAdd={addToCart} onSizeGuideOpen={() => setShowSizeGuide(true)} isUserAtacado={loggedInUser && loggedInUser.type === "atacado"} /> {/* Size Guide Modal */} setShowSizeGuide(false)} /> {/* Checkout Modal */} setShowCheckout(false)} cartItems={cart} appliedCoupon={appliedCoupon} onClearCart={clearCart} showToast={showToastMsg} loggedInUser={loggedInUser} settings={settings} /> {/* User Auth/Dashboard Modal */} setShowUserModal(false)} loggedInUser={loggedInUser} onLogin={handleUserLogin} onRegister={() => {}} onLogout={handleUserLogout} notifications={notifications} orders={orders} showToast={showToastMsg} loadOrders={loadOrders} /> {/* Toast Notification Container */} {toast.show && (
{toast.message}
)} {/* Floating Buttons */} { e.preventDefault(); setShowSizeGuide(true); }}> GUIA DE MEDIDAS
); }