// App.jsx — MinduBier × Copa 2026 — Main app, Nav, Footer, Tweaks, screen routing

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "heroVariant": "celebrativo",
  "theme": "claro",
  "showCountdown": true,
  "ctaText": "Quero a minha"
} /*EDITMODE-END*/;

function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [preVendaModalOpen, setPreVendaModalOpen] = React.useState(true);
  const [screen, setScreen] = React.useState('landing'); // 'landing' | 'obrigado'
  const [pedido, setPedido] = React.useState(() => {
    try {
      const raw = sessionStorage.getItem('mb_pedido');
      return raw ? JSON.parse(raw) : null;
    } catch (e) {return null;}
  });
  const [scrolled, setScrolled] = React.useState(false);

  // Apply theme to body
  React.useEffect(() => {
    document.body.classList.toggle('theme-dark', t.theme === 'dark');
  }, [t.theme]);

  // Track scroll for navbar
  React.useEffect(() => {
    function onScroll() {setScrolled(window.scrollY > 40);}
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Smooth scroll handler for CTA
  function scrollToForm() {
    document.getElementById('formulario')?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }

  function handleSubmitDone(p) {
    try {sessionStorage.setItem('mb_pedido', JSON.stringify(p));} catch (e) {}
    setPedido(p);
    setScreen('obrigado');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  function handleVoltar() {
    try {sessionStorage.removeItem('mb_pedido');} catch (e) {}
    setPedido(null);
    setScreen('landing');
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }

  const isDark = t.theme === 'dark';

  return (
    <ToastProvider>
      {preVendaModalOpen &&
      <PreVendaEncerradaModal isDark={isDark} onClose={() => setPreVendaModalOpen(false)} />
      }
      <Navbar scrolled={scrolled} isDark={isDark} onCtaClick={scrollToForm} onLogoClick={() => screen === 'obrigado' ? handleVoltar() : window.scrollTo({ top: 0, behavior: 'smooth' })} />

      <main style={{
        transition: 'opacity 400ms ease'
      }}>
        {screen === 'landing' &&
        <div key="landing" style={{ animation: `fadeUp 400ms ${MB.ease} both` }}>
            <Hero tweaks={t} onCTAClick={scrollToForm} />
            <Gallery tweaks={t} />
            <SizeTable tweaks={t} />
            <PriceSection tweaks={t} onCTAClick={scrollToForm} />
            <FormSection tweaks={t} onSubmitDone={handleSubmitDone} />
          </div>
        }
        {screen === 'obrigado' &&
        <div key="obrigado" style={{ animation: `fadeUp 500ms ${MB.ease} both` }}>
            <ObrigadoScreen pedido={pedido} onVoltar={handleVoltar} tweaks={t} />
          </div>
        }
      </main>

      <Footer isDark={isDark} />

      <TweaksPanel>
        <TweakSection label="Hero" />
        <TweakRadio
          label="Estilo"
          value={t.heroVariant}
          options={[
          { label: 'Celebrativo', value: 'celebrativo' },
          { label: 'Produto', value: 'produto' }]
          }
          onChange={(v) => setTweak('heroVariant', v)} />
        
        <TweakText
          label="CTA principal"
          value={t.ctaText}
          onChange={(v) => setTweak('ctaText', v)} />
        

        <TweakSection label="Tema" />
        <TweakRadio
          label="Aparência"
          value={t.theme}
          options={[
          { label: 'Claro', value: 'claro' },
          { label: 'Estádio', value: 'dark' }]
          }
          onChange={(v) => setTweak('theme', v)} />
        

        <TweakSection label="Atalhos de demo" />
        <TweakButton
          label="Pular para o formulário"
          onClick={() => {
            if (screen !== 'landing') handleVoltar();
            setTimeout(scrollToForm, 200);
          }} />
        
        <TweakButton
          label="Ver tela de obrigado (demo)"
          onClick={() => {
            const demo = {
              nome: 'Gustavo Martins',
              email: 'gustavo@mindubier.com.br',
              telefone: '71988880000',
              cep: '40150100',
              logradouro: 'Rua Visconde de Itaboraí',
              numero: '255',
              complemento: 'Apto 302',
              bairro: 'Graça',
              cidade: 'Salvador',
              estado: 'BA',
              itens: [
              { tamanho: 'M', quantidade: 2 },
              { tamanho: 'G', quantidade: 1 }],

              tipoEntrega: 'entrega',
              precoUnitarioCentavos: 9900,
              subtotalCentavos: 29700,
              freteCentavos: 3500,
              freteDescricao: 'PAC (Correios) • 4 dias úteis',
              totalCentavos: 33200,
              protocolo: 'MDB-DEMOXX'
            };
            handleSubmitDone(demo);
          }} />
        
        <TweakButton
          label="Resetar (limpar pedido)"
          onClick={() => handleVoltar()} />
        
      </TweaksPanel>
    </ToastProvider>);

}

// ─── PRÉ-VENDA ENCERRADA (overlay) ─────────────────────────────────────
function PreVendaEncerradaModal({ isDark, onClose }) {
  React.useEffect(() => {
    function onKey(e) { if (e.key === 'Escape') onClose(); }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-labelledby="pv-encerrada-title"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
        background: 'rgba(20,22,18,0.62)',
        backdropFilter: 'blur(8px)',
        WebkitBackdropFilter: 'blur(8px)',
        animation: `fadeUp 350ms ${MB.ease} both`
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative',
          width: '100%', maxWidth: 520,
          background: isDark ? MB.bgDarker : '#fffff4',
          borderRadius: 28,
          padding: 'clamp(32px, 5vw, 48px)',
          textAlign: 'center',
          boxShadow: '0 40px 100px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.12)',
          border: '1px solid ' + (isDark ? 'rgba(254,221,0,0.20)' : 'rgba(0,151,57,0.15)')
        }}>
        <button
          type="button"
          onClick={onClose}
          aria-label="Fechar aviso"
          style={{
            position: 'absolute', top: 16, right: 16,
            width: 36, height: 36, borderRadius: 999,
            border: 'none', cursor: 'pointer',
            display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
            background: isDark ? 'rgba(255,255,244,0.08)' : 'rgba(50,50,49,0.06)',
            color: isDark ? 'rgba(255,255,244,0.8)' : MB.bgDarker,
            fontSize: 20, lineHeight: 1
          }}>
          ×
        </button>

        <div className="badge badge-copa" style={{ marginBottom: 20 }}>
          <Icon.Trophy size={14} /> Edição limitada · Copa 2026
        </div>

        <h2 id="pv-encerrada-title" style={{
          fontFamily: MB.display, fontWeight: 800,
          fontSize: 'clamp(28px, 5vw, 42px)',
          lineHeight: 1.04, letterSpacing: '-0.025em',
          margin: 0,
          color: isDark ? '#fffff4' : MB.bgDarker
        }}>
          Pré-venda{' '}
          <span style={{
            background: 'linear-gradient(135deg, var(--copa-green-deep) 0%, var(--copa-green) 45%, var(--copa-yellow) 100%)',
            WebkitBackgroundClip: 'text',
            WebkitTextFillColor: 'transparent',
            backgroundClip: 'text'
          }}>encerrada</span>
        </h2>

        <p style={{
          fontFamily: MB.body,
          fontSize: 'clamp(15px, 1.6vw, 18px)',
          lineHeight: 1.6,
          marginTop: 18,
          color: isDark ? 'rgba(255,255,244,0.78)' : MB.bgDark
        }}>
          Muito obrigado a todos que garantiram a camisa oficial da MinduBier para a Copa 2026! A pré-venda foi um baita sucesso e já estamos preparando tudo com carinho. Em breve entramos em contato com quem fez o cadastro.
        </p>

        <button className="btn btn-primary" onClick={onClose} style={{ marginTop: 28 }}>
          Continuar na página <Icon.ArrowRight size={18} />
        </button>
      </div>
    </div>);

}

// ─── NAVBAR ────────────────────────────────────────────────────────────
function Navbar({ scrolled, isDark, onCtaClick, onLogoClick }) {
  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0,
      zIndex: 100,
      padding: scrolled ? '10px 0' : '16px 0',
      background: scrolled ?
      isDark ? 'rgba(13,27,20,0.85)' : 'rgba(255,255,244,0.85)' :
      'transparent',
      backdropFilter: scrolled ? 'blur(20px) saturate(180%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(20px) saturate(180%)' : 'none',
      borderBottom: scrolled ?
      '1px solid ' + (isDark ? 'rgba(254,221,0,0.10)' : 'rgba(50,50,49,0.06)') :
      '1px solid transparent',
      boxShadow: scrolled
        ? (isDark
            ? '0 8px 24px rgba(0,0,0,0.35), 0 2px 6px rgba(0,0,0,0.20)'
            : '0 8px 24px rgba(50,50,49,0.10), 0 2px 6px rgba(50,50,49,0.06)')
        : 'none',
      transition: `all 300ms ${MB.ease}`
    }}>
      <div className="container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        gap: 16
      }}>
        <button onClick={onLogoClick} aria-label="MinduBier — voltar ao início" style={{
          display: 'flex', alignItems: 'center', gap: 10,
          background: 'transparent', border: 'none', cursor: 'pointer',
          padding: 0
        }}>
          <img
            src={isDark ? R('logoWhite', 'assets/LogoHorizontalWhite.avif') : R('logoColor', 'assets/LogoHorizontalColor.avif')}
            alt="MinduBier"
            style={{ height: 24, width: 'auto' }}
            onError={(e) => {e.target.style.display = 'none';}} />
          
          <span style={{
            fontFamily: MB.display, fontWeight: 800, fontSize: 11,
            color: isDark ? 'var(--copa-yellow)' : MB.copaGreenDeep,
            background: isDark ? 'rgba(254,221,0,0.12)' : 'rgba(0,151,57,0.10)',
            padding: '4px 10px',
            borderRadius: 999,
            textTransform: 'uppercase',
            letterSpacing: '0.08em',
            border: '1px solid ' + (isDark ? 'rgba(254,221,0,0.20)' : 'rgba(0,151,57,0.20)')
          }}>PRÉ-VENDA</span>
        </button>

        <div className="nav-links" style={{
          display: 'flex', alignItems: 'center', gap: 24
        }}>
          <NavLink href="#galeria" isDark={isDark}>Galeria</NavLink>
          <NavLink href="#medidas" isDark={isDark}>Medidas</NavLink>
          <NavLink href="#preco" isDark={isDark}>Preço</NavLink>
          <button onClick={onCtaClick} className="btn btn-primary" style={{
            padding: '10px 18px', fontSize: 14, borderRadius: 12
          }}>
            Quero a minha
          </button>
        </div>
      </div>

      <style>{`
        @media (max-width: 700px) {
          .nav-links a { display: none; }
        }
      `}</style>
    </nav>);

}

function NavLink({ href, children, isDark }) {
  return (
    <a href={href} style={{
      fontFamily: MB.display, fontWeight: 600, fontSize: 14,
      color: isDark ? 'rgba(255,255,244,0.78)' : MB.bgDarker,
      textDecoration: 'none',
      padding: '8px 4px',
      borderBottom: '2px solid transparent',
      transition: 'color 200ms, border-color 200ms'
    }}
    onMouseEnter={(e) => {e.currentTarget.style.color = MB.copper;}}
    onMouseLeave={(e) => {e.currentTarget.style.color = isDark ? 'rgba(255,255,244,0.78)' : MB.bgDarker;}}>
      {children}</a>);

}

// ─── FOOTER ────────────────────────────────────────────────────────────
function Footer({ isDark }) {
  const socials = [
    { label: 'Instagram', href: 'https://www.instagram.com/mindubier', icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="2" width="20" height="20" rx="5" ry="5" />
        <path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z" />
        <line x1="17.5" y1="6.5" x2="17.51" y2="6.5" />
      </svg>
    ) },
    { label: 'Facebook', href: 'https://www.facebook.com/mindubier', icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
        <path d="M22 12a10 10 0 1 0-11.56 9.88v-6.99H7.9V12h2.54V9.8c0-2.5 1.49-3.89 3.78-3.89 1.09 0 2.24.2 2.24.2v2.46H15.2c-1.24 0-1.63.77-1.63 1.56V12h2.77l-.44 2.89h-2.33v6.99A10 10 0 0 0 22 12z" />
      </svg>
    ) },
    { label: 'YouTube', href: 'https://www.youtube.com/@mindubier', icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
        <path d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.5 3.5 12 3.5 12 3.5s-7.5 0-9.4.6A3 3 0 0 0 .5 6.2 31 31 0 0 0 0 12a31 31 0 0 0 .5 5.8 3 3 0 0 0 2.1 2.1c1.9.6 9.4.6 9.4.6s7.5 0 9.4-.6a3 3 0 0 0 2.1-2.1A31 31 0 0 0 24 12a31 31 0 0 0-.5-5.8zM9.75 15.5v-7l6.5 3.5-6.5 3.5z" />
      </svg>
    ) },
    { label: 'Untappd', href: 'https://untappd.com/MinduBier', icon: (
      <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
        <path d="M9.7 7.8 4.2 16.6c-.55.86-.4 2.02.35 2.72l.86.79c.75.7 1.93.78 2.78.2L17 14.1c.45-.3.84-.7 1.14-1.18l1.5-2.4-3.7-3.4-2.1 2.84a4 4 0 0 1-1.2 1.08l-1.95.86c-.4-.55-.6-1-.99-1.6zm10.93-3.7-1.85-1.7c-.4-.36-.97-.32-1.32.1l-.97 1.18c-.21.26-.27.6-.16.91l.66 1.74 3.45 3.16 1.7-.97c.3-.17.5-.47.51-.81l.06-1.53c.02-.43-.2-.84-.55-1.08zM7.8 5.8a.5.5 0 0 1 .58.07L9.5 7.05c.2.18.23.48.07.7l-.6.84c-.13.18-.36.27-.58.22a.5.5 0 0 1-.34-.28L7.5 6.3a.5.5 0 0 1 .3-.5z" />
      </svg>
    ) },
    { label: 'WhatsApp', href: 'https://wa.me/5571981069026', icon: <Icon.Whatsapp size={20} /> },
  ];

  return (
    <footer style={{
      background: 'var(--bg-footer)',
      color: 'rgba(255,255,244,0.7)',
      padding: 'clamp(56px, 8vw, 96px) 0 36px',
      marginTop: 60,
    }}>
      <div className="container" style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 28,
        textAlign: 'center',
      }}>
        <img
          src={R('logoColor', 'assets/LogoHorizontalColor.avif')}
          alt="MinduBier · Salvador · Bahia · Brasil"
          style={{ height: 'clamp(30px, 4vw, 42px)', width: 'auto', display: 'block' }}
          onError={(e) => { e.target.style.display = 'none'; }}
        />

        <div style={{
          display: 'flex',
          flexWrap: 'wrap',
          justifyContent: 'center',
          gap: 14,
          marginTop: 8,
        }}>
          {socials.map((s) => (
            <a
              key={s.label}
              href={s.href}
              target="_blank"
              rel="noopener noreferrer"
              aria-label={s.label}
              title={s.label}
              style={{
                width: 46, height: 46,
                borderRadius: 12,
                background: 'rgba(255,255,244,0.06)',
                border: '1px solid rgba(255,255,244,0.08)',
                color: 'rgba(255,255,244,0.85)',
                display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                textDecoration: 'none',
                transition: `background 200ms ${MB.ease}, color 200ms ${MB.ease}, transform 200ms ${MB.ease}, border-color 200ms ${MB.ease}`,
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = 'rgba(254,221,0,0.14)';
                e.currentTarget.style.color = 'var(--copa-yellow)';
                e.currentTarget.style.borderColor = 'rgba(254,221,0,0.30)';
                e.currentTarget.style.transform = 'translateY(-2px)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = 'rgba(255,255,244,0.06)';
                e.currentTarget.style.color = 'rgba(255,255,244,0.85)';
                e.currentTarget.style.borderColor = 'rgba(255,255,244,0.08)';
                e.currentTarget.style.transform = 'translateY(0)';
              }}
            >
              {s.icon}
            </a>
          ))}
        </div>

        <div style={{
          marginTop: 18,
          display: 'flex', flexDirection: 'column', gap: 10,
          fontFamily: MB.body, fontSize: 14,
          color: 'rgba(255,255,244,0.55)',
          lineHeight: 1.6,
        }}>
          <span>Beba com moderação. Venda proibida para menores de 18 anos.</span>
          <span>© 2016–2026 Cervejaria MinduBier. Todos os direitos reservados.</span>
          <span style={{ color: 'rgba(255,255,244,0.40)' }}>Salvador, Bahia, Brasil</span>
        </div>
      </div>
    </footer>
  );
}

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