/* MIL GRAU RP — Shared UI Components */

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

// ===== HEADER =====
function Header({ cartCount, onCartClick, onNav, currentPage, onSupport, searchQuery, onSearchChange, onSearchSubmit }) {
  return (
    <header className="header">
      <div className="top-banner">
        🎁 PRIMEIRA COMPRA: Use o cupom <b>BEMVINDOMG</b> e ganhe 10% OFF
      </div>
      <div className="container">
        <div className="header-main">
          <a className="logo" onClick={() => onNav('home')} style={{cursor:'pointer'}}>
            <span className="mil">MIL</span>
            <span className="grau">GRAU</span>
            <span className="rp">RP</span>
          </a>
          <form className="search" onSubmit={(e) => { e.preventDefault(); if ((searchQuery || '').trim()) onSearchSubmit(searchQuery); }}>
            <Icon name="search" size={18}/>
            <input
              placeholder="Buscar produto..."
              value={searchQuery || ''}
              onChange={(e) => onSearchChange(e.target.value)}
            />
            {searchQuery ? (
              <button type="button" className="search-clear" onClick={() => { onSearchChange(''); if (currentPage === 'search') onNav('home'); }} title="Limpar">
                <Icon name="close" size={14}/>
              </button>
            ) : null}
          </form>
          <div className="header-actions">
            <button className="icon-btn" onClick={onSupport} title="Atendimento"><Icon name="headset"/></button>
            <button className="cart-btn" onClick={onCartClick}>
              <Icon name="cart" size={16}/>
              Carrinho
              {cartCount > 0 && <span className="cart-badge">{cartCount}</span>}
            </button>
          </div>
        </div>
        <nav className="cat-nav">
          <button
            className={`cat-pill cat-pill-home ${currentPage === 'home' ? 'active' : ''}`}
            onClick={() => onNav('home')}>
            INÍCIO
          </button>
          {window.MGRP_DATA.CATEGORIES.map(c => (
            <button key={c.slug}
              className={`cat-pill ${currentPage === 'category-' + c.slug ? 'active' : ''}`}
              onClick={() => onNav('category-' + c.slug)}>
              {c.label}
            </button>
          ))}
        </nav>
      </div>
    </header>
  );
}

// ===== FOOTER =====
function Footer({ onNav }) {
  return (
    <footer className="footer">
      <div className="container">
        <div className="footer-grid">
          <div>
            <div className="logo" style={{fontSize:'24px', marginBottom:'12px'}}>
              <span className="mil">MIL</span>
              <span className="grau">GRAU</span>
              <span className="rp">RP</span>
            </div>
            <p className="desc">O MIL GRAU RP foi criado em <b>2020</b> com o intuito de entreter as pessoas, simulando a vida real dentro de um jogo. Nosso diferencial é o foco no estilo <b>"grau"</b> — temos motos, carros e roupas <b>totalmente exclusivas</b> para o nosso servidor. 🏍️🚗👕</p>
            <div className="socials">
              <a className="social" title="Instagram" href="https://www.instagram.com/milgraurp/" target="_blank" rel="noopener noreferrer"><Icon name="instagram" size={18}/></a>
              <a className="social" title="Discord" href="https://discord.gg/milgrau" target="_blank" rel="noopener noreferrer"><Icon name="discord" size={18}/></a>
              <a className="social" title="TikTok" href="https://www.tiktok.com/@1000graurp" target="_blank" rel="noopener noreferrer"><Icon name="tiktok" size={18}/></a>
              <a className="social" title="WhatsApp" href="https://wa.me/5547991360760" target="_blank" rel="noopener noreferrer"><Icon name="whatsapp" size={18}/></a>
            </div>
          </div>
          <div>
            <h4>Loja</h4>
            <ul>
              <li><a onClick={() => onNav && onNav('category-passe-livre')} style={{cursor:'pointer'}}>Passe Livre</a></li>
              <li><a onClick={() => onNav && onNav('category-vips')} style={{cursor:'pointer'}}>VIPs</a></li>
              <li><a onClick={() => onNav && onNav('category-combos')} style={{cursor:'pointer'}}>Combos</a></li>
              <li><a onClick={() => onNav && onNav('category-promocoes')} style={{cursor:'pointer'}}>Promoções</a></li>
              <li><a onClick={() => onNav && onNav('category-lancamentos')} style={{cursor:'pointer'}}>Lançamentos</a></li>
            </ul>
          </div>
          <div>
            <h4>Suporte</h4>
            <ul>
              <li><a>Central de Ajuda</a></li>
              <li><a>Como pagar</a></li>
              <li><a onClick={() => onNav && onNav('terms')} style={{cursor:'pointer'}}>Política de Reembolso</a></li>
              <li><a onClick={() => onNav && onNav('terms')} style={{cursor:'pointer'}}>Termos de Uso</a></li>
              <li><a onClick={() => onNav && onNav('terms')} style={{cursor:'pointer'}}>Privacidade</a></li>
            </ul>
          </div>
          <div>
            <h4>Contato</h4>
            <ul>
              <li><a>atendimento@milgraurp.com.br</a></li>
              <li><a>Discord oficial</a></li>
              <li><a>Atendimento 24/7</a></li>
            </ul>
          </div>
        </div>
        <div className="footer-bottom">
          <span>© 2026 MIL GRAU RP. Todos os direitos reservados.</span>
          <a onClick={() => onNav && onNav('terms')} style={{cursor:'pointer', color:'var(--text-muted)', transition:'color 200ms'}}
             onMouseEnter={e => e.currentTarget.style.color = 'var(--primary)'}
             onMouseLeave={e => e.currentTarget.style.color = 'var(--text-muted)'}>Termos e condições</a>
        </div>
      </div>
    </footer>
  );
}

// ===== PRODUCT THUMB =====
function ProductThumb({ p, big = false }) {
  return (
    <div className="product-thumb-bg" style={{
      background: `linear-gradient(135deg, ${p.color} 0%, ${p.color}55 50%, #050505 100%)`
    }}>
      <div style={{position:'absolute', inset:0, display:'flex', alignItems:'center', justifyContent:'center'}}>
        <div className="product-thumb-icon" style={{color: p.accent}}>
          <Icon name={p.icon} size={big ? 70 : 44}/>
        </div>
      </div>
      {/* Decorative pattern overlay */}
      <div style={{position:'absolute', inset:0, opacity:0.15,
        backgroundImage: `radial-gradient(circle at 20% 80%, ${p.accent}33 0%, transparent 40%), radial-gradient(circle at 80% 20%, ${p.accent}22 0%, transparent 40%)`,
        pointerEvents:'none'}}/>
    </div>
  );
}

// ===== PRODUCT CARD =====
function ProductCard({ p, idx = 0, onClick, onAdd }) {
  return (
    <div className="product-card" style={{animationDelay: (idx * 60) + 'ms'}} onClick={onClick}>
      {p.bestseller && <div className="bestseller">MAIS VENDIDO</div>}
      <div className="product-thumb">
        <ProductThumb p={p}/>
        <div className="product-badges">
          {p.discount && <span className="product-badge badge-discount">-{p.discount}%</span>}
          <span className="product-badge badge-stock">{p.stock} em estoque</span>
          {p.popular && !p.bestseller && <span className="product-badge badge-hot"><Icon name="fire" size={10}/> POPULAR</span>}
        </div>
      </div>
      <div className="product-info">
        <div className="product-cat">{p.cat}</div>
        <div className="product-name">{p.name}</div>
        <div className="product-price">
          {p.oldPrice && <span className="price-old">{window.MGRP_DATA.fmtBRL(p.oldPrice)}</span>}
          <span className="price-now">{window.MGRP_DATA.fmtBRL(p.price)}</span>
        </div>
        <div className="price-pix product-pix"><Icon name="pix" size={12}/> À vista no Pix</div>
        <div className="product-actions">
          <button className="btn btn-primary" onClick={(e) => { e.stopPropagation(); onAdd(p); }}>
            Comprar
          </button>
          <button className="icon-cart-btn" onClick={(e) => { e.stopPropagation(); onAdd(p); }} title="Adicionar ao carrinho">
            <Icon name="cart" size={16}/>
          </button>
        </div>
      </div>
    </div>
  );
}

// ===== TOAST SYSTEM =====
function ToastStack({ toasts }) {
  return (
    <div className="toast-stack">
      {toasts.map(t => (
        <div key={t.id} className={`toast ${t.exiting ? 'exit' : ''}`}>
          <div className="toast-icon"><Icon name="check" size={16}/></div>
          <div className="toast-content">
            <div className="toast-title">{t.title}</div>
            <div className="toast-msg">{t.msg}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ===== CART DRAWER =====
function CartDrawer({ open, items, onClose, onQty, onRemove, onCheckout }) {
  if (!open) return null;
  const total = items.reduce((s, i) => s + i.price * i.qty, 0);
  return (
    <>
      <div className="drawer-overlay" onClick={onClose}/>
      <div className="drawer">
        <div className="drawer-head">
          <h3>Seu carrinho ({items.length})</h3>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={18}/></button>
        </div>
        <div className="drawer-body">
          {items.length === 0 ? (
            <div className="empty-cart">
              <Icon name="cart" size={64}/>
              <h4>Seu carrinho está vazio</h4>
              <p>Adicione produtos da loja para continuar.</p>
            </div>
          ) : items.map(item => (
            <div key={item.id} className="cart-item">
              <div className="cart-item-thumb" style={{background: `linear-gradient(135deg, ${item.color} 0%, #050505 100%)`, color: item.accent}}>
                <Icon name={item.icon} size={26}/>
              </div>
              <div className="cart-item-info">
                <div className="cart-item-name" title={item.name}>{item.name}</div>
                <div className="cart-item-price">{window.MGRP_DATA.fmtBRL(item.price * item.qty)}</div>
              </div>
              <div className="cart-item-controls">
                <div className="qty qty-inline">
                  <button onClick={() => onQty(item.id, -1)} aria-label="Diminuir"><Icon name="minus" size={12}/></button>
                  <span className="qty-val">{item.qty}</span>
                  <button onClick={() => onQty(item.id, 1)} aria-label="Aumentar"><Icon name="plus" size={12}/></button>
                </div>
                <button className="cart-remove" onClick={() => onRemove(item.id)} aria-label="Remover">
                  <Icon name="close" size={14}/>
                </button>
              </div>
            </div>
          ))}
        </div>
        {items.length > 0 && (
          <div className="drawer-foot">
            <div className="cart-total">
              <span className="label">Valor total</span>
              <span className="val">{window.MGRP_DATA.fmtBRL(total)}</span>
            </div>
            <button className="btn btn-primary btn-lg btn-block" onClick={onCheckout}>
              Ir para a compra <Icon name="arrow-right" size={16}/>
            </button>
          </div>
        )}
      </div>
    </>
  );
}

// ===== SUPPORT MODAL (channels picker) =====
function SupportModal({ open, onClose }) {
  if (!open) return null;
  const channels = [
    { name: 'Discord', sub: 'Comunidade oficial · 100k+ membros', icon: 'discord', color: '#5865F2', href: 'https://discord.gg/milgrau' },
    { name: 'Instagram', sub: '@milgraurp', icon: 'instagram', color: '#E1306C', href: 'https://www.instagram.com/milgraurp/' },
    { name: 'WhatsApp', sub: '(47) 99136-0760 · Resposta em até 1h', icon: 'whatsapp', color: '#25D366', href: 'https://wa.me/5547991360760' },
    { name: 'TikTok', sub: '@1000graurp', icon: 'tiktok', color: '#000', href: 'https://www.tiktok.com/@1000graurp' },
  ];
  return (
    <div className="modal-overlay" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3>Canais de atendimento</h3>
          <button className="icon-btn" onClick={onClose}><Icon name="close" size={18}/></button>
        </div>
        <div className="modal-body">
          <p style={{color:'var(--text-muted)', fontSize:'14px', marginBottom:'20px'}}>
            Escolha o canal mais conveniente. Nosso time responde em minutos.
          </p>
          <div style={{display:'flex', flexDirection:'column', gap:'8px'}}>
            {channels.map(c => (
              <a key={c.name} href={c.href} target="_blank" rel="noopener noreferrer"
                 className="payment-opt" style={{flexDirection:'row', alignItems:'center', gap:'14px', cursor:'pointer', textDecoration:'none'}}>
                <div style={{width:'40px', height:'40px', borderRadius:'10px', background: c.color + '22', color: c.color, display:'flex', alignItems:'center', justifyContent:'center'}}>
                  <Icon name={c.icon} size={20}/>
                </div>
                <div style={{flex:1, textAlign:'left'}}>
                  <div className="ttl">{c.name}</div>
                  <div className="sub">{c.sub}</div>
                </div>
                <Icon name="chevron" size={16}/>
              </a>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ===== CHAT WIDGET (Crisp-style live chat) =====
function ChatWidget({ open, onClose, onOpen }) {
  const [messages, setMessages] = useState([
    { from: 'bot', text: 'Olá! Como posso ajudar você? 😊', t: Date.now() }
  ]);
  const [input, setInput] = useState('');
  const [showPhone, setShowPhone] = useState(true);
  const [phoneCollected, setPhoneCollected] = useState(false);
  const [phone, setPhone] = useState('');
  const [phoneInputOpen, setPhoneInputOpen] = useState(false);
  const [typing, setTyping] = useState(false);
  const [unread, setUnread] = useState(0);
  const bodyRef = useRef();

  useEffect(() => {
    if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight;
  }, [messages, typing]);

  useEffect(() => {
    if (open) setUnread(0);
  }, [open]);

  const send = async (text) => {
    if (!text || !text.trim()) return;
    const userMsg = { from: 'user', text: text.trim(), t: Date.now() };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setTyping(true);

    // Pseudo-random delay then reply
    let reply = '';
    try {
      const claude = window.claude;
      if (claude && claude.complete) {
        const sys = `Você é o atendente da loja virtual MIL GRAU RP, servidor brasileiro de FiveM Roleplay. Responda em português, curto (máximo 2 frases), simpático e direto. Conhecimentos: temos passes (Inicial R$47,90, Premium R$77,90, Lendário R$247,90), pacotes de dinheiro (50k/100k/250k/500k), VIPs (Bronze/Prata/Ouro/Diamante/Mensal), MG Coins, combos, especiais. Cupom BEMVINDOMG dá 10% OFF na primeira compra. Pagamentos via PIX, MercadoPago e PayPal. Entrega imediata após pagamento. Suporte 24/7 no Discord (discord.gg/milgrau) e WhatsApp (47 99136-0760). Para dúvidas técnicas detalhadas, recomende canais como Discord ou WhatsApp.`;
        reply = await claude.complete({
          messages: [
            { role: 'user', content: sys + '\n\nUsuário: ' + text.trim() }
          ]
        });
        reply = (reply || '').trim();
      }
    } catch (e) { reply = ''; }

    if (!reply) {
      // Fallback canned response
      const t = text.toLowerCase();
      if (t.match(/cupom|desconto|primeira/)) reply = 'Sim! Use o cupom BEMVINDOMG no checkout e ganhe 10% OFF na sua primeira compra. 🎁';
      else if (t.match(/entrega|prazo|demora/)) reply = 'A entrega é imediata após a confirmação do pagamento. Os benefícios caem na sua conta da cidade em segundos. ⚡';
      else if (t.match(/pix|pagamento|cart[ãa]o|pagar/)) reply = 'Aceitamos PIX (com aprovação imediata), MercadoPago e PayPal. Recomendamos PIX por ser o mais rápido. 💳';
      else if (t.match(/preço|valor|quanto/)) reply = 'Temos opções pra todos os bolsos! Passe Inicial sai por R$47,90, Premium R$77,90 e o Lendário R$247,90. Dá uma olhada na loja! 💰';
      else if (t.match(/passe|vip/)) reply = 'Os passes liberam combos exclusivos e prioridade no servidor. O Lendário é nosso mais vendido! Posso te indicar qual escolher?';
      else reply = 'Recebi sua mensagem! Para um atendimento personalizado, entre em contato pelo nosso Discord (discord.gg/milgrau) ou WhatsApp (47 99136-0760). 💬';
    }

    setTimeout(() => {
      setTyping(false);
      setMessages(prev => [...prev, { from: 'bot', text: reply, t: Date.now() }]);
      if (!open) setUnread(u => u + 1);
    }, 700 + Math.random() * 800);
  };

  const submitPhone = () => {
    if (!phone || phone.replace(/\D/g, '').length < 10) return;
    setPhoneCollected(true);
    setShowPhone(false);
    setPhoneInputOpen(false);
    setMessages(prev => [...prev,
      { from: 'user', text: `📱 Telefone para retorno: ${phone}`, t: Date.now() },
      { from: 'bot', text: 'Perfeito! Anotamos seu telefone. Caso a conversa se encerre, retornamos por aí. ✅', t: Date.now() + 1 }
    ]);
  };

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send(input);
    }
  };

  const today = new Date();
  const day = today.toLocaleDateString('pt-BR', { weekday: 'long', day: 'numeric', month: 'long' });
  const dayCap = day.charAt(0).toUpperCase() + day.slice(1);

  return (
    <>
      {!open && (
        <button className="chat-fab-bubble" onClick={onOpen} title="Atendimento">
          <Icon name="chat" size={26}/>
          {unread > 0 && <span className="chat-unread">{unread}</span>}
        </button>
      )}
      {open && (
        <div className="chat-widget">
          <div className="chat-header">
            <button className="chat-collapse" onClick={onClose} title="Minimizar">
              <Icon name="chevron" size={18} style={{transform:'rotate(90deg)'}}/>
            </button>
            <div className="chat-tabbar">
              <div className="chat-tab active"><Icon name="chat" size={14}/> Conversação</div>
            </div>
            <div className="chat-avatars">
              {[0,1,2].map(i => (
                <div key={i} className="chat-avatar-circle" style={{background: i === 0 ? '#7c1d1d' : i === 1 ? '#581c87' : '#1e3a8a'}}>
                  <Icon name="user" size={16}/>
                </div>
              ))}
            </div>
            <div className="chat-headline">Dúvidas? Fale conosco!</div>
            <div className="chat-status">
              <span className="chat-online-dot"/> Time online · responde em minutos
            </div>
          </div>

          <div className="chat-body" ref={bodyRef}>
            {messages.slice(0, 1).map((m, i) => (
              <ChatBubble key={i} m={m}/>
            ))}
            <div className="chat-day-divider"><span>{dayCap}</span></div>
            {messages.slice(1).map((m, i) => (
              <ChatBubble key={i+1} m={m}/>
            ))}

            {showPhone && !phoneCollected && (
              <div className="chat-bot-row">
                <div className="chat-bot-avatar"><Icon name="user" size={14}/></div>
                <div style={{flex:1}}>
                  <div className="chat-bubble bot">
                    <b>Se você sair ou demorarmos:</b><br/>
                    Como você gostaria de receber a resposta?
                  </div>
                  <div className="chat-quickreplies">
                    <button className="chat-chip" onClick={() => setPhoneInputOpen(true)}>
                      <Icon name="phone" size={14}/> Telefone
                    </button>
                  </div>
                  {phoneInputOpen && (
                    <div className="chat-phone-form">
                      <input
                        type="tel"
                        placeholder="(00) 00000-0000"
                        value={phone}
                        onChange={e => setPhone(e.target.value)}
                        autoFocus
                      />
                      <button onClick={submitPhone}>Enviar</button>
                    </div>
                  )}
                </div>
              </div>
            )}

            {typing && (
              <div className="chat-bot-row">
                <div className="chat-bot-avatar"><Icon name="user" size={14}/></div>
                <div className="chat-bubble bot chat-typing">
                  <span/><span/><span/>
                </div>
              </div>
            )}
          </div>

          <div className="chat-foot">
            <textarea
              placeholder="Escreva sua mensagem..."
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKey}
              rows={1}
            />
            <button className="chat-send" onClick={() => send(input)} disabled={!input.trim()}>
              <Icon name="send" size={18}/>
            </button>
          </div>
          <div className="chat-brand">
            Atendimento <b style={{color:'var(--primary)'}}>MIL GRAU RP</b>
          </div>
        </div>
      )}
    </>
  );
}

function ChatBubble({ m }) {
  if (m.from === 'user') {
    return (
      <div className="chat-user-row">
        <div className="chat-bubble user">{m.text}</div>
      </div>
    );
  }
  return (
    <div className="chat-bot-row">
      <div className="chat-bot-avatar"><Icon name="user" size={14}/></div>
      <div className="chat-bubble bot" dangerouslySetInnerHTML={{__html: m.text}}/>
    </div>
  );
}

// ===== CHAT FAB (legacy bubble - now folded into ChatWidget) =====
function ChatFab({ onClick }) {
  return null;
}

// ===== COUNTDOWN =====
function Countdown() {
  const [time, setTime] = useState({ h: 23, m: 47, s: 12 });
  useEffect(() => {
    const t = setInterval(() => {
      setTime(prev => {
        let { h, m, s } = prev;
        s--;
        if (s < 0) { s = 59; m--; }
        if (m < 0) { m = 59; h--; }
        if (h < 0) { h = 23; }
        return { h, m, s };
      });
    }, 1000);
    return () => clearInterval(t);
  }, []);
  const pad = n => String(n).padStart(2, '0');
  return (
    <div className="countdown-banner">
      <div style={{width:'48px', height:'48px', borderRadius:'12px', background:'rgba(230,57,70,0.2)', color:'var(--primary)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
        <Icon name="bolt" size={24}/>
      </div>
      <div className="countdown-info">
        <div className="ttl">⚡ Promoção relâmpago: -26% em todos os Combos</div>
        <div className="sub">Termina em breve. Aproveite enquanto dura.</div>
      </div>
      <div className="countdown-clock">
        <div className="cd-cell"><div className="num">{pad(time.h)}</div><div className="lbl">HORAS</div></div>
        <div className="cd-cell"><div className="num">{pad(time.m)}</div><div className="lbl">MIN</div></div>
        <div className="cd-cell"><div className="num">{pad(time.s)}</div><div className="lbl">SEG</div></div>
      </div>
    </div>
  );
}

Object.assign(window, {
  Header, Footer, ProductThumb, ProductCard, ToastStack, CartDrawer, SupportModal, ChatFab, ChatWidget, Countdown
});
