/* MIL GRAU RP — Checkout, PIX, Profile pages */

const { useState: uS2, useEffect: uE2, useMemo: uM2 } = React;

// ===== CHECKOUT =====
function CheckoutPage({ items, onNav, onPay, onAddItem }) {
  const [pay, setPay] = uS2('pix');
  const [terms, setTerms] = uS2(false);
  const [coupon, setCoupon] = uS2('');
  const [appliedCoupon, setAppliedCoupon] = uS2(null);
  const [form, setForm] = uS2({ nome: '', email: '', cpf: '', tel: '', idCidade: '' });
  const [discordLinked, setDiscordLinked] = uS2(false);

  const subtotal = items.reduce((s, i) => s + i.price * i.qty, 0);
  const discount = appliedCoupon ? subtotal * 0.1 : 0;
  const total = subtotal - discount;

  const applyCoupon = () => {
    if (coupon.toUpperCase() === 'BEMVINDOMG') {
      setAppliedCoupon('BEMVINDOMG');
    } else {
      setAppliedCoupon('invalid');
    }
  };

  return (
    <div className="page">
      <div className="container">
        <div className="breadcrumb">
          <a onClick={() => onNav('home')}>Início</a>
          <span className="sep">/</span>
          <span className="current">Checkout</span>
        </div>
        <h1 style={{fontSize:'32px', fontWeight:900, letterSpacing:'-0.02em', margin:'16px 0 32px'}}>
          Finalizar <span style={{color:'var(--primary)'}}>compra</span>
        </h1>

        <div className="checkout-layout">
          <div>
            {/* Discord */}
            <div className="checkout-section">
              <h3><span className="num">1</span> Sua conta</h3>
              {discordLinked ? (
                <div style={{display:'flex', alignItems:'center', gap:'12px', padding:'12px 14px', background:'rgba(88,101,242,0.1)', border:'1px solid rgba(88,101,242,0.3)', borderRadius:'10px'}}>
                  <div style={{width:'40px', height:'40px', borderRadius:'10px', background:'#5865F2', display:'flex', alignItems:'center', justifyContent:'center'}}>
                    <Icon name="discord" size={20}/>
                  </div>
                  <div style={{flex:1}}>
                    <div style={{fontSize:'13px', fontWeight:700}}>Diego Martins#4892</div>
                    <div style={{fontSize:'12px', color:'var(--text-muted)'}}>Conectado via Discord</div>
                  </div>
                  <Icon name="check" size={18} style={{color:'var(--green-pix)'}}/>
                </div>
              ) : (
                <button className="discord-btn" onClick={() => setDiscordLinked(true)}>
                  <Icon name="discord" size={18}/> Entrar com Discord
                </button>
              )}
            </div>

            {/* Forma de pagamento */}
            <div className="checkout-section">
              <h3><span className="num">2</span> Forma de pagamento</h3>
              <div className="payment-grid">
                <div className={`payment-opt ${pay === 'pix' ? 'active' : ''}`} onClick={() => setPay('pix')}>
                  <div className="check"/>
                  <div style={{display:'flex', alignItems:'center', gap:'8px'}}>
                    <Icon name="pix" size={20} style={{color:'var(--green-pix)'}}/>
                    <span className="ttl">PIX</span>
                  </div>
                  <span className="sub">Aprovação imediata</span>
                </div>
                <div className={`payment-opt ${pay === 'mp' ? 'active' : ''}`} onClick={() => setPay('mp')}>
                  <div className="check"/>
                  <span className="ttl">Mercado Pago</span>
                  <span className="sub">Cartão de crédito</span>
                </div>
                <div className={`payment-opt ${pay === 'pp' ? 'active' : ''}`} onClick={() => setPay('pp')}>
                  <div className="check"/>
                  <span className="ttl">PayPal</span>
                  <span className="sub">Internacional</span>
                </div>
              </div>
            </div>

            {/* Dados pessoais */}
            <div className="checkout-section">
              <h3><span className="num">3</span> Dados pessoais</h3>
              <div className="form-grid">
                <div className="field" style={{gridColumn:'1 / -1'}}>
                  <label>Nome completo</label>
                  <input value={form.nome} onChange={e => setForm({...form, nome: e.target.value})} placeholder="Seu nome completo"/>
                </div>
                <div className="field">
                  <label>E-mail</label>
                  <input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} placeholder="seu@email.com"/>
                </div>
                <div className="field">
                  <label>CPF</label>
                  <input value={form.cpf} onChange={e => setForm({...form, cpf: e.target.value})} placeholder="000.000.000-00"/>
                </div>
                <div className="field">
                  <label>Telefone</label>
                  <input value={form.tel} onChange={e => setForm({...form, tel: e.target.value})} placeholder="(00) 00000-0000"/>
                </div>
                <div className="field">
                  <label>ID na cidade</label>
                  <input value={form.idCidade} onChange={e => setForm({...form, idCidade: e.target.value})} placeholder="#00000"/>
                </div>
              </div>
            </div>
          </div>

          {/* Resumo */}
          <div className="summary">
            <div className="checkout-section">
              <h3>Resumo do pedido</h3>
              <div style={{display:'flex', flexDirection:'column', gap:'12px', marginBottom:'16px'}}>
                {items.map(item => (
                  <div key={item.id} style={{display:'flex', gap:'10px', alignItems:'center'}}>
                    <div className="cart-item-thumb" style={{width:'44px', height:'44px', background:`linear-gradient(135deg, ${item.color}, #050505)`, color: item.accent}}>
                      <Icon name={item.icon} size={20}/>
                    </div>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontSize:'13px', fontWeight:600}}>{item.name}</div>
                      <div style={{fontSize:'11px', color:'var(--text-muted)'}}>Qtd: {item.qty}</div>
                    </div>
                    <div style={{fontSize:'13px', fontWeight:700, fontFeatureSettings:'"tnum"'}}>{window.MGRP_DATA.fmtBRL(item.price * item.qty)}</div>
                  </div>
                ))}
              </div>

              <div style={{borderTop:'1px solid var(--border)', paddingTop:'14px'}}>
                <div style={{fontSize:'12px', fontWeight:600, color:'var(--text-muted)', marginBottom:'8px'}}>CUPOM DE DESCONTO</div>
                <div className="coupon">
                  <input value={coupon} onChange={e => setCoupon(e.target.value)} placeholder="Digite o cupom"/>
                  <button onClick={applyCoupon}>Aplicar</button>
                </div>
                {appliedCoupon === 'BEMVINDOMG' && (
                  <div style={{fontSize:'12px', color:'var(--green-pix)', marginBottom:'12px', display:'flex', alignItems:'center', gap:'6px'}}>
                    <Icon name="check" size={12}/> Cupom <b>BEMVINDOMG</b> aplicado: -10%
                  </div>
                )}
                {appliedCoupon === 'invalid' && (
                  <div style={{fontSize:'12px', color:'var(--primary)', marginBottom:'12px'}}>Cupom inválido. Tente "BEMVINDOMG".</div>
                )}
              </div>

              <div className="summary-row muted"><span>Subtotal</span><span>{window.MGRP_DATA.fmtBRL(subtotal)}</span></div>
              {discount > 0 && <div className="summary-row discount"><span>Desconto (10%)</span><span>-{window.MGRP_DATA.fmtBRL(discount)}</span></div>}
              <div className="summary-row muted"><span>Taxa de processamento</span><span>Grátis</span></div>
              <div className="summary-row total"><span>Total</span><span className="val">{window.MGRP_DATA.fmtBRL(total)}</span></div>

              <div className="upsell">
                <div className="upsell-icon"><Icon name="bolt" size={18}/></div>
                <div className="upsell-info">
                  <div className="ttl">Adicione Cartão 100k</div>
                  <div className="sub">+ R$ 47,90 e leve dinheiro extra</div>
                </div>
                <button onClick={() => {
                  const card = window.MGRP_DATA.PRODUCTS.find(p => p.id === 'cartao-100k');
                  if (card && onAddItem) onAddItem(card);
                }}>+ Adicionar</button>
              </div>

              <label className="terms">
                <input type="checkbox" checked={terms} onChange={e => setTerms(e.target.checked)}/>
                <span>Eu aceito os <a style={{color:'var(--primary)'}}>termos e condições</a> e a <a style={{color:'var(--primary)'}}>política de privacidade</a> da MIL GRAU RP.</span>
              </label>

              <button className="btn btn-primary btn-lg btn-block" disabled={!terms} style={{opacity: terms ? 1 : 0.5, marginTop:'8px'}} onClick={() => onPay(total)}>
                Pagar {window.MGRP_DATA.fmtBRL(total)}
              </button>

              <div style={{textAlign:'center', fontSize:'11px', color:'var(--text-dim)', marginTop:'12px', display:'flex', alignItems:'center', justifyContent:'center', gap:'6px'}}>
                <Icon name="shield" size={12}/> Pagamento 100% seguro
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ===== PIX PAYMENT =====
function PixPage({ amount, onNav }) {
  const [copied, setCopied] = uS2(false);
  const code = '00020126360014BR.GOV.BCB.PIX0114+5511999990000520400005303986540' + (amount || 0).toFixed(2) + '5802BR5919MILGRAURP STORE LTDA6009SAO PAULO62070503***6304ABCD';

  const copy = () => {
    navigator.clipboard?.writeText(code);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <div className="page">
      <div className="container">
        <div className="breadcrumb">
          <a onClick={() => onNav('home')}>Início</a>
          <span className="sep">/</span>
          <a onClick={() => onNav('checkout')}>Checkout</a>
          <span className="sep">/</span>
          <span className="current">Pagamento PIX</span>
        </div>
        <div className="pix-layout">
          <div className="pix-card">
            <div style={{width:'56px', height:'56px', margin:'0 auto 16px', borderRadius:'14px', background:'rgba(0,200,150,0.15)', color:'var(--green-pix)', display:'flex', alignItems:'center', justifyContent:'center'}}>
              <Icon name="pix" size={28}/>
            </div>
            <h2>Concluir pagamento</h2>
            <p className="sub">Escaneie o QR Code ou copie o código PIX para pagar</p>
            <div className="pix-amount">{window.MGRP_DATA.fmtBRL(amount || 247.90)}</div>
            <div className="qr-wrap">
              <QRPlaceholder/>
            </div>
            <div className="pix-copy">
              <input value={code} readOnly/>
              <button onClick={copy}>
                {copied ? <><Icon name="check" size={12} style={{display:'inline', marginRight:4, verticalAlign:'middle'}}/>Copiado!</> : <><Icon name="copy" size={12} style={{display:'inline', marginRight:4, verticalAlign:'middle'}}/>Copiar</>}
              </button>
            </div>
            <div style={{fontSize:'12px', color:'var(--text-muted)', display:'flex', alignItems:'center', justifyContent:'center', gap:'6px'}}>
              <span style={{width:'8px', height:'8px', borderRadius:999, background:'var(--gold)', animation:'pulse 1.5s infinite'}}/>
              Aguardando pagamento... expira em 14:32
            </div>
          </div>

          <div className="pix-steps">
            <h3>📱 Como pagar com PIX?</h3>
            <div className="pix-step">
              <div className="num">1</div>
              <div className="txt">Abra o <b>app do seu banco</b> e acesse a área PIX.</div>
            </div>
            <div className="pix-step">
              <div className="num">2</div>
              <div className="txt">Escolha <b>"Pagar com QR Code"</b> ou <b>"PIX Copia e Cola"</b> e cole o código.</div>
            </div>
            <div className="pix-step">
              <div className="num">3</div>
              <div className="txt">Confirme o pagamento. Seu produto será liberado <b>automaticamente</b> em segundos.</div>
            </div>
          </div>

          <div style={{textAlign:'center', marginTop:'24px'}}>
            <button className="btn btn-ghost" onClick={() => onNav('profile')}>Ir para Meus Pedidos <Icon name="arrow-right" size={14}/></button>
          </div>
        </div>
      </div>
    </div>
  );
}

// QR placeholder (SVG modules)
function QRPlaceholder() {
  const size = 21;
  const cells = [];
  // pseudo-random pattern with finder squares
  for (let y = 0; y < size; y++) {
    for (let x = 0; x < size; x++) {
      const isFinder = (x < 7 && y < 7) || (x >= size - 7 && y < 7) || (x < 7 && y >= size - 7);
      let on = false;
      if (isFinder) {
        const fx = x < 7 ? x : x - (size - 7);
        const fy = y < 7 ? y : y - (size - 7);
        on = (fx === 0 || fx === 6 || fy === 0 || fy === 6 || (fx >= 2 && fx <= 4 && fy >= 2 && fy <= 4));
      } else {
        on = ((x * 31 + y * 17 + x * y) % 3 === 0);
      }
      if (on) cells.push(<rect key={`${x}-${y}`} x={x*8} y={y*8} width="8" height="8" fill="black"/>);
    }
  }
  return (
    <svg width="200" height="200" viewBox={`0 0 ${size*8} ${size*8}`} style={{display:'block'}}>
      <rect width={size*8} height={size*8} fill="white"/>
      {cells}
      {/* Logo center */}
      <rect x="68" y="68" width="32" height="32" rx="6" fill="white"/>
      <rect x="72" y="72" width="24" height="24" rx="4" fill="#E63946"/>
      <text x="84" y="89" textAnchor="middle" fontFamily="Inter, sans-serif" fontWeight="900" fontSize="11" fill="white">MG</text>
    </svg>
  );
}

// ===== PROFILE =====
function ProfilePage({ onNav, products }) {
  const [tab, setTab] = uS2('orders');
  const orders = [
    { id: 'MG-2026-04829', date: '02 Mai 2026', status: 'Concluído', items: [products.find(p => p.id === 'passe-premium'), products.find(p => p.id === 'sistema-tvs')], total: 309.80 },
    { id: 'MG-2026-04612', date: '28 Abr 2026', status: 'Concluído', items: [products.find(p => p.id === 'cartao-100k')], total: 47.90 },
    { id: 'MG-2026-04501', date: '15 Abr 2026', status: 'Pendente', items: [products.find(p => p.id === 'passe-lendario')], total: 247.90 },
  ].filter(o => o.items.every(Boolean));

  return (
    <div className="page">
      <div className="container">
        <div className="breadcrumb">
          <a onClick={() => onNav('home')}>Início</a>
          <span className="sep">/</span>
          <span className="current">Meu Perfil</span>
        </div>
        <h1 style={{fontSize:'32px', fontWeight:900, letterSpacing:'-0.02em', margin:'16px 0 32px'}}>
          Meu <span style={{color:'var(--primary)'}}>perfil</span>
        </h1>

        <div className="profile-layout">
          <aside className="profile-card">
            <div className="user-avatar">DM</div>
            <h3>Diego Martins</h3>
            <div className="id">ID na cidade #4892</div>
            <div style={{display:'flex', gap:'8px', flexWrap:'wrap', marginTop:'12px'}}>
              <span className="meta-pill stock">● Online</span>
              <span className="meta-pill" style={{background:'rgba(212,175,55,0.15)', color:'var(--gold)', border:'1px solid rgba(212,175,55,0.3)'}}>
                <Icon name="crown" size={11}/> LENDÁRIO
              </span>
            </div>
            <div className="profile-tabs">
              <button className={`profile-tab ${tab === 'orders' ? 'active' : ''}`} onClick={() => setTab('orders')}>
                <Icon name="package" size={16}/> Meus pedidos
              </button>
              <button className={`profile-tab ${tab === 'data' ? 'active' : ''}`} onClick={() => setTab('data')}>
                <Icon name="user" size={16}/> Dados pessoais
              </button>
              <button className={`profile-tab ${tab === 'settings' ? 'active' : ''}`} onClick={() => setTab('settings')}>
                <Icon name="settings" size={16}/> Configurações
              </button>
              <button className="profile-tab">
                <Icon name="logout" size={16}/> Sair
              </button>
            </div>
          </aside>
          <div>
            {tab === 'orders' && (
              <>
                <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:'16px'}}>
                  <h2 style={{fontSize:'20px', fontWeight:800}}>Histórico de pedidos</h2>
                  <span style={{color:'var(--text-muted)', fontSize:'13px'}}>{orders.length} pedidos</span>
                </div>
                {orders.map(o => (
                  <div key={o.id} className="order-card">
                    <div className="order-head">
                      <div>
                        <div style={{fontSize:'13px', fontWeight:700, marginBottom:'4px'}}>Pedido <b style={{fontFamily:'monospace'}}>{o.id}</b></div>
                        <div className="order-id" style={{fontSize:'12px', color:'var(--text-muted)'}}>{o.date}</div>
                      </div>
                      <span className={`order-status ${o.status === 'Pendente' ? 'pending' : ''}`}>● {o.status}</span>
                    </div>
                    <div className="order-items">
                      {o.items.map(it => (
                        <div key={it.id} className="order-item-row">
                          <div className="cart-item-thumb" style={{background:`linear-gradient(135deg, ${it.color}, #050505)`, color: it.accent}}>
                            <Icon name={it.icon} size={20}/>
                          </div>
                          <div className="name">{it.name}</div>
                          <div className="qty-x">x1</div>
                          <div className="price">{window.MGRP_DATA.fmtBRL(it.price)}</div>
                        </div>
                      ))}
                    </div>
                    <div className="order-foot">
                      <div className="order-total">Total: <b>{window.MGRP_DATA.fmtBRL(o.total)}</b></div>
                      <div style={{display:'flex', gap:'8px'}}>
                        <button className="btn btn-outline" style={{padding:'8px 14px', fontSize:'12px'}}>Ver detalhes</button>
                        <button className="btn btn-ghost" style={{padding:'8px 14px', fontSize:'12px'}}>Comprar de novo</button>
                      </div>
                    </div>
                  </div>
                ))}
              </>
            )}
            {tab === 'data' && (
              <div className="checkout-section">
                <h3>Dados pessoais</h3>
                <div className="form-grid">
                  <div className="field" style={{gridColumn:'1 / -1'}}>
                    <label>Nome completo</label>
                    <input defaultValue="Diego Martins"/>
                  </div>
                  <div className="field"><label>E-mail</label><input defaultValue="diego.martins@email.com"/></div>
                  <div className="field"><label>CPF</label><input defaultValue="123.456.789-00"/></div>
                  <div className="field"><label>Telefone</label><input defaultValue="(11) 98888-7777"/></div>
                  <div className="field"><label>ID na cidade</label><input defaultValue="#4892"/></div>
                </div>
                <button className="btn btn-primary" style={{marginTop:'16px'}}>Salvar alterações</button>
              </div>
            )}
            {tab === 'settings' && (
              <div className="checkout-section">
                <h3>Configurações</h3>
                <p style={{color:'var(--text-muted)', fontSize:'14px'}}>Preferências de notificação, segurança e privacidade da sua conta.</p>
                <div style={{display:'flex', flexDirection:'column', gap:'12px', marginTop:'16px'}}>
                  {['Receber e-mails de promoções', 'Notificações de pedidos', 'Mensagens da comunidade', 'Autenticação 2FA'].map((s, i) => (
                    <label key={i} className="filter-opt" style={{padding:'12px 14px', background:'var(--bg-2)', borderRadius:10, border:'1px solid var(--border)'}}>
                      <input type="checkbox" defaultChecked={i < 2}/> {s}
                    </label>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.CheckoutPage = CheckoutPage;
window.PixPage = PixPage;
window.ProfilePage = ProfilePage;
