/* global React, Icon, AmperLogo, fmtBRL, fmtBRLShort, isMarcaNacional, ANO_MAXIMO */
/* selStyle usado também por simulator-steps.jsx (BrandStep), via window.selStyle. */

// #depoimentos removido do menu — a seção Testimonials já não é renderizada
// (tirada a pedido do Rian em 2026-08-30, ver app.jsx), o link ficou morto.
const NAV_LINKS = [['#como-funciona','Como funciona'],['#faq','Dúvidas']];
const Nav = ({ onStart }) => {
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);
  return (
    <header style={{ position: 'sticky', top: 0, zIndex: 40, backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)', background: 'rgba(247,246,243,0.92)', borderBottom: '1px solid var(--ink-100)' }}>
      <div className="nav-inner" style={{ maxWidth: 1360, margin: '0 auto', padding: '18px 40px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
        <AmperLogo height={17} />
        <nav className="nav-links" style={{ display: 'flex', gap: 32, fontSize: 14, fontWeight: 500, color: 'var(--ink-700)' }}>
          {NAV_LINKS.map(([href, label]) => <a key={href} href={href}>{label}</a>)}
        </nav>
        <div className="nav-actions" style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <button className="btn btn-primary btn-sm" onClick={onStart}>Avaliar meu carro <Icon.Arrow width={16} height={16} /></button>
        </div>
        <button className="nav-burger" aria-label={open ? 'Fechar menu' : 'Abrir menu'} aria-expanded={open} onClick={() => setOpen(!open)} style={{ display: 'none', width: 44, height: 44, alignItems: 'center', justifyContent: 'center', borderRadius: 10, flexShrink: 0 }}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none" stroke="var(--ink-900)" strokeWidth="2" strokeLinecap="round">
            {open ? <><path d="M4 4L18 18"/><path d="M18 4L4 18"/></> : <><path d="M3 6h16"/><path d="M3 11h16"/><path d="M3 16h16"/></>}
          </svg>
        </button>
      </div>
      {open && (
        <div className="nav-drawer" style={{ position: 'fixed', top: 73, left: 0, right: 0, bottom: 0, background: 'var(--paper)', zIndex: 39, display: 'flex', flexDirection: 'column', padding: '12px 20px 32px' }}>
          <nav style={{ display: 'flex', flexDirection: 'column' }}>
            {NAV_LINKS.map(([href, label]) => (
              <a key={href} href={href} onClick={() => setOpen(false)} style={{ padding: '18px 4px', fontSize: 22, fontWeight: 600, color: 'var(--ink-900)', borderBottom: '1px solid var(--ink-100)' }}>{label}</a>
            ))}
          </nav>
          <div style={{ marginTop: 'auto', display: 'flex', flexDirection: 'column', gap: 10, paddingBottom: 'env(safe-area-inset-bottom)' }}>
            <button className="btn btn-primary btn-lg" style={{ width: '100%' }} onClick={() => { setOpen(false); onStart(); }}>Avaliar meu carro <Icon.Arrow width={18} height={18} /></button>
          </div>
        </div>
      )}
    </header>
  );
};

/* ---------- QUICK EVAL: form compartilhado (Hero inline + popup) ----------
   Extraído do Hero pra ser reaproveitado tal e qual dentro do QuickEvalModal
   — qualquer botão da HOME que não seja o card do Hero abre o popup com essa
   MESMA experiência, em vez de mandar direto pro assistente passo-a-passo. */
const QuickEvalHeader = () => (
  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
    <div>
      <div className="label" style={{ marginBottom: 4 }}>Avaliação instantânea</div>
      <div style={{ fontSize: 20, fontWeight: 600, letterSpacing: '-0.015em' }}>Quanto vale o seu carro?</div>
    </div>
    <span className="chip chip-yellow"><Icon.Bolt width={12} height={12}/> 60s</span>
  </div>
);

const QuickEvalForm = ({ onStart }) => {
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const h = () => force();
    window.addEventListener('amper-tweaks-changed', h);
    return () => window.removeEventListener('amper-tweaks-changed', h);
  }, []);
  const copy = (window.__AMPER_COPY) || {};
  const ctaLabel = copy.ctaLabel || 'Ver quanto vale';

  const [tab, setTab] = React.useState('placa');
  const [plate, setPlate] = React.useState('');

  // Marca/modelo/ano do fluxo manual — dados reais via window.AmperAPI
  // (Parallelum), carregados em cascata conforme o usuário escolhe.
  const [brands, setBrands] = React.useState([]);
  const [brandsLoading, setBrandsLoading] = React.useState(true);
  const [brand, setBrand] = React.useState(''); // codigoMarca
  const [models, setModels] = React.useState([]);
  const [modelsLoading, setModelsLoading] = React.useState(false);
  const [modelGroupKey, setModelGroupKey] = React.useState(''); // modelo-base escolhido (ex: "A3")
  const [years, setYears] = React.useState([]);
  const [yearsLoading, setYearsLoading] = React.useState(false);
  const [year, setYear] = React.useState('');

  React.useEffect(() => {
    window.AmperAPI.getMarcas()
      .then(data => {
        // Só marcas comuns no Brasil — corta as exóticas/raras do catálogo real.
        const nacionais = (Array.isArray(data) ? data : []).filter(b => isMarcaNacional(b.nome));
        setBrands(nacionais);
        setBrandsLoading(false);
      })
      .catch(() => setBrandsLoading(false));
  }, []);

  React.useEffect(() => {
    if (!brand) { setModels([]); return; }
    setModelsLoading(true);
    window.AmperAPI.getModelos(brand)
      .then(data => { setModels(Array.isArray(data) ? data : []); setModelsLoading(false); })
      .catch(() => setModelsLoading(false));
  }, [brand]);

  // Agrupa por modelo-base (ex: "A3") — a FIPE trata cada versão/motorização
  // como um modelo à parte, sem isso o select vira uma lista de 50+ nomes
  // técnicos. A versão específica (característica) é escolhida depois, já no
  // simulador (etapa 4) — o form só precisa achar o modelo e o ano.
  // Ver data/fipe.jsx (groupModelos) pro porquê.
  const modelGroups = React.useMemo(() => window.groupModelos(models), [models]);
  const selectedGroup = modelGroups.find(g => g.key === modelGroupKey);

  React.useEffect(() => {
    if (!brand || !selectedGroup) { setYears([]); return; }
    setYearsLoading(true);
    // Soma os anos disponíveis em TODAS as versões do modelo-base escolhido.
    window.anosPorVariante(brand, selectedGroup.variants)
      .then(r => {
        const unique = [...new Set(
          r.flatMap(x => x.anos.map(a => a.codigo.split('-')[0] === '32000' ? '0 km' : a.codigo.split('-')[0]))
        )]
          .filter(y => y === '0 km' || Number(y) <= ANO_MAXIMO)
          .sort((a, b) => a === '0 km' ? -1 : b === '0 km' ? 1 : Number(b) - Number(a));
        setYears(unique);
        setYearsLoading(false);
      })
      .catch(() => setYearsLoading(false));
  }, [brand, selectedGroup]);

  const canStartPlate = plate.replace(/[^A-Z0-9]/gi, '').length >= 7;
  const canStartManual = brand && selectedGroup && year;

  const handlePlate = (e) => {
    let v = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 7);
    if (v.length > 3) v = v.slice(0, 3) + '-' + v.slice(3);
    setPlate(v);
  };

  const startPlate = () => {
    if (!canStartPlate) return;
    onStart({ mode: 'placa', plate });
  };
  const startManual = () => {
    if (!canStartManual) return;
    const brandName = brands.find(b => String(b.codigo) === brand)?.nome || '';
    // model/modelName ainda são o grupo (ex: "A3") — a etapa Características
    // do simulador (step 4) resolve pra versão real usando modelVariants.
    onStart({
      mode: 'manual', brand, brandName,
      model: selectedGroup.key, modelName: selectedGroup.nome, modelVariants: selectedGroup.variants,
      year,
    });
  };

  return (
    <>
      {/* Tabs */}
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr',
        background: 'rgba(255,255,255,0.1)', borderRadius: 12, padding: 4, marginBottom: 20, gap: 2,
      }}>
        {[
          { id: 'placa', label: 'Pela placa', icon: <Icon.Plate/> },
          { id: 'manual', label: 'Marca e modelo', icon: <Icon.Car/> },
        ].map((t) => (
          <button
            key={t.id}
            onClick={() => setTab(t.id)}
            style={{
              height: 44, borderRadius: 9,
              background: tab === t.id ? 'white' : 'transparent',
              color: tab === t.id ? 'var(--ink-900)' : 'rgba(255,255,255,0.65)',
              fontWeight: 600, fontSize: 14,
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              boxShadow: tab === t.id ? '0 1px 0 rgba(10,10,10,.08), 0 2px 6px rgba(10,10,10,.04)' : 'none',
              transition: 'all 180ms',
            }}>
            {React.cloneElement(t.icon, { width: 18, height: 18 })}
            {t.label}
          </button>
        ))}
      </div>

      {tab === 'placa' ? (
        <div>
          <div className="label" style={{ marginBottom: 8 }}>Placa</div>
          <div style={{
            background: 'linear-gradient(180deg, #fff 0%, #fafaf7 100%)',
            border: '2px solid var(--ink-900)',
            borderRadius: 10,
            padding: '14px 18px',
            marginBottom: 6,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <div style={{
              background: 'var(--ink-900)', color: 'white',
              fontSize: 11, fontWeight: 700, letterSpacing: 2,
              padding: '2px 6px', borderRadius: 3,
            }}>BR</div>
            <input
              className="plate-input"
              value={plate}
              onChange={handlePlate}
              placeholder="ABC-1D23"
              autoCapitalize="characters" autoCorrect="off" spellCheck={false} enterKeyHint="go"
              style={{
                border: 0, outline: 0, background: 'transparent',
                fontFamily: 'var(--font-mono)',
                fontSize: 30, fontWeight: 700, letterSpacing: '0.12em',
                flex: 1, textAlign: 'center',
              }}
            />
          </div>
          <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.55)', marginBottom: 20 }}>
            Vamos identificar a marca, modelo e ano automaticamente.
          </div>

          <button
            className="btn btn-primary btn-lg"
            onClick={startPlate}
            disabled={!canStartPlate}
            style={{
              width: '100%',
              opacity: canStartPlate ? 1 : 0.5,
              cursor: canStartPlate ? 'pointer' : 'not-allowed',
            }}>
            {ctaLabel} <Icon.Arrow width={18} height={18}/>
          </button>

          <div style={{ textAlign: 'center', marginTop: 14 }}>
            <button
              onClick={() => setTab('manual')}
              style={{ fontSize: 13, color: 'rgba(255,255,255,0.75)', textDecoration: 'underline' }}>
              Não sei a placa
            </button>
          </div>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          <Field label="Marca">
            <select value={brand} onChange={(e) => { setBrand(e.target.value); setModelGroupKey(''); setYear(''); }} disabled={brandsLoading} style={selStyle}>
              <option value="">{brandsLoading ? 'Carregando…' : 'Selecione'}</option>
              {brands.map(b => <option key={b.codigo} value={String(b.codigo)}>{b.nome}</option>)}
            </select>
          </Field>
          <Field label="Modelo">
            <select value={modelGroupKey} onChange={(e) => { setModelGroupKey(e.target.value); setYear(''); }} disabled={!brand || modelsLoading} style={selStyle}>
              <option value="">{!brand ? 'Escolha a marca' : modelsLoading ? 'Carregando…' : 'Selecione'}</option>
              {modelGroups.map(g => <option key={g.key} value={g.key}>{g.nome}</option>)}
            </select>
          </Field>
          <Field label="Ano">
            <select value={year} onChange={(e) => setYear(e.target.value)} disabled={!selectedGroup || yearsLoading} style={selStyle}>
              <option value="">{!selectedGroup ? 'Escolha o modelo' : yearsLoading ? 'Carregando…' : 'Selecione'}</option>
              {years.map(y => <option key={y} value={y}>{y}</option>)}
            </select>
          </Field>
          <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,0.55)', marginTop: -4 }}>
            A versão exata (motor, câmbio, combustível) você escolhe no próximo passo.
          </div>
          <button
            className="btn btn-primary btn-lg"
            onClick={startManual}
            disabled={!canStartManual}
            style={{
              width: '100%', marginTop: 8,
              opacity: canStartManual ? 1 : 0.5,
              cursor: canStartManual ? 'pointer' : 'not-allowed',
            }}>
            {ctaLabel} <Icon.Arrow width={18} height={18}/>
          </button>
        </div>
      )}

      <div style={{
        marginTop: 20, paddingTop: 18,
        borderTop: '1px solid rgba(255,255,255,0.16)',
        display: 'flex', alignItems: 'center', gap: 10,
        fontSize: 13, color: 'rgba(255,255,255,0.6)',
      }}>
        <Icon.Shield width={16} height={16} />
        Seus dados são protegidos pela LGPD. Não enviamos spam.
      </div>
    </>
  );
};

/* ---------- QUICK EVAL MODAL: popup do form acima, usado por qualquer botão
   "Avaliar meu carro" fora do card do Hero — Nav, "Como funciona", Turbo,
   Footer, sticky CTA. Fecha no X, no clique fora, ou no Esc. ---------- */
const QuickEvalModal = ({ open, onClose, onStart }) => {
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div
      role="dialog" aria-modal="true" aria-label="Avaliação instantânea"
      onClick={onClose}
      style={{
        position: 'fixed', inset: 0, zIndex: 100,
        background: 'rgba(8,8,8,0.72)',
        backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20,
      }}>
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          position: 'relative',
          width: '100%', maxWidth: 460,
          maxHeight: '90vh', overflowY: 'auto',
          padding: 30, borderRadius: 26,
          boxShadow: '0 40px 90px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.14)',
          border: '1px solid rgba(255,255,255,0.16)',
          background: 'var(--ink-900)',
          color: 'white',
        }}>
        <button onClick={onClose} aria-label="Fechar" style={{
          position: 'absolute', top: 16, right: 16,
          width: 32, height: 32, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'rgba(255,255,255,0.6)', background: 'rgba(255,255,255,0.08)',
        }}>
          <Icon.Close width={15} height={15}/>
        </button>
        <QuickEvalHeader/>
        <QuickEvalForm onStart={onStart}/>
      </div>
    </div>
  );
};

/* ---------- HERO ---------- */
const Hero = ({ onStart }) => {
  return (
    <section className="hero-pin" style={{ position: 'relative', background: 'var(--ink-900)' }}>
      <HeroParallaxBg />
      <div className="hero-section" style={{ position: 'relative', zIndex: 2, padding: '128px 40px 72px', minHeight: '100svh', display: 'flex', alignItems: 'center' }}>
      <div className="hero-grid" style={{ maxWidth: 1300, margin: '0 auto', width: '100%', display: 'grid', gridTemplateColumns: '1.05fr 0.95fr', gap: 56, alignItems: 'center' }}>
        <div className="hero-parallax-text">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
            <span className="chip chip-yellow"><Icon.Sparkle width={12} height={12}/> Amper</span>
            <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)' }}>Venda sem sair de casa</span>
          </div>
          <h1 style={{ fontSize: 'clamp(44px, 5vw, 80px)', lineHeight: 0.95, letterSpacing: '-0.035em', fontWeight: 700, marginBottom: 22, color: 'white' }}>
            {/* Destaque em amarelo puro (sem fundo) — escolha do Rian 2026-08-30;
                o marca-texto chapado incomodava. Só vale em fundo escuro: em
                fundo claro amarelo puro fere a regra da marca (usar --gold-deep). */}
            Venda por mais. <span style={{ color: 'var(--amper-yellow)' }}>Sem pressa</span>,<br/>sem dor de cabeça.
          </h1>
          <p style={{ fontSize: 18, lineHeight: 1.5, color: 'rgba(255,255,255,0.7)', maxWidth: 560, margin: '0 0 28px' }}>
            A Amper cuida de tudo: certificado de garantia 1 ano, fotos profissionais, polimento, financiamento aprovado pro comprador. Você continua usando o carro até a venda — e recebe acima de loja e concessionária.
          </p>
          <div className="hero-trust" style={{ display: 'flex', gap: 24, flexWrap: 'wrap', alignItems: 'center' }}>
            {[
              { icon: <Icon.CheckCircle/>, text: 'Use o carro até a venda' },
              { icon: <Icon.CheckCircle/>, text: 'Só paga se vender' },
              { icon: <Icon.CheckCircle/>, text: 'Garantia + fotos + polimento grátis' },
            ].map((t, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 14, color: 'rgba(255,255,255,0.8)' }}>
                <span style={{ color: 'var(--amper-yellow)' }}>{t.icon}</span>
                {t.text}
              </div>
            ))}
          </div>
        </div>
        {/* Vidro translúcido escuro — mesma receita do card Turbo (o Rian pediu
            igual àquele, não a versão leitosa): fundo quase transparente + blur,
            texto claro; os campos (placa/selects) seguem brancos e sólidos. */}
        <div className="card hero-sim-card" style={{
          padding: 30,
          borderRadius: 26,
          boxShadow: '0 40px 90px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.14)',
          border: '1px solid rgba(255,255,255,0.16)',
          background: 'rgba(255,255,255,0.06)',
          backdropFilter: 'blur(22px) saturate(140%)', WebkitBackdropFilter: 'blur(22px) saturate(140%)',
          color: 'white',
          width: '100%', maxWidth: 560, justifySelf: 'end',
        }}>
          <QuickEvalHeader/>
          <QuickEvalForm onStart={onStart}/>
        </div>
      </div>
      </div>
    </section>
  );
};

/* ---------- HERO BG: foto estática da fachada, com leve parallax no scroll.
   Volta pro esquema anterior à sequência animada (pin + crossfade escuro) —
   o Carlos (feedback do Rian) notou que o fundo tinha mudado, e a sequência
   animada foi a raiz de vários bugs de mobile essa sessão (pin com altura
   fixa brigando com a viewport real). Imagem clara de dia, por isso o véu
   escuro por baixo — o texto do Hero é branco, precisa de contraste. ---------- */
const HeroParallaxBg = () => {
  const imgRef = React.useRef(null);
  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        if (imgRef.current) imgRef.current.style.transform = `translateY(${Math.min(window.scrollY, window.innerHeight * 2) * 0.15}px) scale(1.08)`;
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);
  const isMobile = window.matchMedia('(max-width: 767px)').matches;
  return (
    <div aria-hidden="true" style={{ position: 'absolute', inset: 0, overflow: 'hidden' }}>
      <img ref={imgRef} src={isMobile ? 'assets/hero/bg-mobile.webp' : 'assets/hero/bg-desktop.webp'} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center', transform: 'scale(1.08)', transformOrigin: 'center top', willChange: 'transform' }} />
      <div style={{ position: 'absolute', inset: 0, background: 'rgba(8,8,8,0.5)' }}></div>
      <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(8,8,8,0.55) 0%, transparent 32%, transparent 60%, rgba(8,8,8,0.7) 100%)' }}></div>
    </div>
  );
};

const selStyle = {
  width: '100%', height: 48, padding: '0 14px',
  border: '1px solid var(--ink-200)', borderRadius: 10,
  // color explícito — sem isso o select herda 'white' do card escuro que o
  // envolve (.hero-sim-card define color:white pro card inteiro), e como o
  // fundo do select é sólido branco, o texto (fechado E as opções da lista)
  // fica branco em cima de branco, invisível.
  background: 'white', color: 'var(--ink-900)', fontSize: 15, fontWeight: 500,
  appearance: 'none',
  backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'12\' height=\'8\' viewBox=\'0 0 12 8\' fill=\'none\'%3E%3Cpath d=\'M1 1.5L6 6.5L11 1.5\' stroke=\'%230A0A0A\' stroke-width=\'1.6\' stroke-linecap=\'round\' stroke-linejoin=\'round\'/%3E%3C/svg%3E")',
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'right 14px center',
};

const Field = ({ label, children }) => (
  <label style={{ display: 'block' }}>
    <div className="label" style={{ marginBottom: 6 }}>{label}</div>
    {children}
  </label>
);

/* ---------- BAR: stats row ---------- */
const StatsBar = () => (
  <div className="stats-bar" style={{
    background: 'var(--ink-900)', color: 'white',
    padding: '28px 40px',
  }}>
    <div className="stats-grid" style={{
      maxWidth: 1360, margin: '0 auto',
      display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 24,
    }}>
      {[
        { k: '+42.000', v: 'veículos vendidos' },
        { k: '4,9 / 5', v: 'avaliação dos clientes' },
        { k: '7 dias', v: 'tempo médio de venda' },
        { k: '+R$ 800M', v: 'transacionados com segurança' },
      ].map((s, i) => (
        <div key={i} style={{ display: 'flex', flexDirection: 'column', borderLeft: i === 0 ? 'none' : '1px solid rgba(255,255,255,0.1)', paddingLeft: i === 0 ? 0 : 24 }}>
          <div style={{ fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em', fontFamily: 'var(--font-display)' }}>{s.k}</div>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.55)', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{s.v}</div>
        </div>
      ))}
    </div>
  </div>
);

/* ---------- HERO BACKDROP: scroll-animated layers ---------- */
const HeroBackdrop = () => {
  const ref = React.useRef(null);
  React.useEffect(() => {
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const y = window.scrollY;
        const el = ref.current;
        if (!el) return;
        el.style.setProperty('--sy', y);
        // parallax text + card handled via CSS calc on --sy
        const text = document.querySelector('.hero-parallax-text');
        if (text) {
          text.style.transform = `translateY(${y * 0.18}px)`;
          text.style.opacity = String(Math.max(0, 1 - y / 520));
        }
        const card = document.querySelector('.hero-sim-card');
        if (card) {
          card.style.transform = `translateY(${y * 0.06}px) scale(${Math.max(0.96, 1 - y / 4000)})`;
        }
      });
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { window.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, []);
  return (
    <div ref={ref} aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
      {/* glow that drifts up on scroll */}
      <div className="hero-glow" style={{
        position: 'absolute', top: '-20%', right: '-10%',
        width: 720, height: 720, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(243, 226, 61,0.16) 0%, transparent 65%)',
        transform: 'translateY(calc(var(--sy, 0) * -0.25px))',
        transition: 'transform 60ms linear',
      }}/>
      <div style={{
        position: 'absolute', bottom: '-30%', left: '-8%',
        width: 560, height: 560, borderRadius: '50%',
        background: 'radial-gradient(circle, rgba(243, 226, 61,0.07) 0%, transparent 60%)',
        transform: 'translateY(calc(var(--sy, 0) * -0.12px))',
        transition: 'transform 60ms linear',
      }}/>
      {/* yellow scribble, drifts sideways */}
      <svg width="520" height="300" viewBox="0 0 420 240" style={{
        position: 'absolute', top: 60, right: -80, opacity: 0.4,
        transform: 'translateX(calc(var(--sy, 0) * 0.15px))',
        transition: 'transform 60ms linear',
      }}>
        <path d="M20 180 C 80 40, 200 220, 260 120 S 400 40, 400 80" stroke="#F3E23D" strokeWidth="36" fill="none" strokeLinecap="round" opacity="0.35"/>
      </svg>
      {/* dotted grid, subtle parallax */}
      <div style={{
        position: 'absolute', inset: 0,
        backgroundImage: 'radial-gradient(rgba(255,255,255,0.07) 1px, transparent 1px)',
        backgroundSize: '26px 26px',
        transform: 'translateY(calc(var(--sy, 0) * -0.06px))',
        transition: 'transform 60ms linear',
      }}/>
    </div>
  );
};

/* ---------- CTA BAND (secondary CTA, Kavak-style mid-page block) ---------- */
const CtaBand = ({ onStart }) => {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const obs = new IntersectionObserver(([e]) => e.isIntersecting && setVisible(true), { threshold: 0.25 });
    if (ref.current) obs.observe(ref.current);
    return () => obs.disconnect();
  }, []);
  const [bgOk, setBgOk] = React.useState(false);
  React.useEffect(() => {
    const im = new Image();
    im.onload = () => setBgOk(true);
    im.src = 'assets/turbo-bg.webp';
  }, []);
  return (
    <section className="turbo-section" style={{ position: 'relative', padding: '150px 40px', background: 'linear-gradient(160deg, #15150f 0%, #0a0a0a 55%, #1c1a0d 100%)', overflow: 'hidden' }}>
      {bgOk ? <img src="assets/turbo-bg.webp" alt="" aria-hidden="true" className="turbo-bg" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center' }} /> : null}
      <div aria-hidden="true" style={{ position: 'absolute', inset: 0, background: bgOk ? 'linear-gradient(180deg, rgba(8,8,8,0.42) 0%, rgba(8,8,8,0.3) 45%, rgba(8,8,8,0.6) 100%)' : 'radial-gradient(120% 90% at 78% 12%, rgba(243,226,61,0.14) 0%, transparent 62%)' }}></div>
      <div ref={ref} className="cta-band" style={{
        maxWidth: 1060, margin: '0 auto',
        background: 'rgba(255,255,255,0.06)', color: 'white',
        backdropFilter: 'blur(22px) saturate(140%)', WebkitBackdropFilter: 'blur(22px) saturate(140%)',
        border: '1px solid rgba(255,255,255,0.16)',
        boxShadow: '0 40px 90px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.14)',
        borderRadius: 28, padding: '48px 44px',
        display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 48, alignItems: 'center',
        opacity: visible ? 1 : 0,
        transform: visible ? 'none' : 'translateY(32px)',
        transition: 'opacity 600ms ease, transform 600ms cubic-bezier(.2,.8,.2,1)',
        position: 'relative', overflow: 'hidden', zIndex: 2,
      }}>
        <div style={{
          position: 'absolute', top: -100, right: -100,
          width: 400, height: 400, borderRadius: '50%',
          background: 'radial-gradient(circle, rgba(243, 226, 61,0.18) 0%, transparent 65%)',
        }}/>
        <div style={{ position: 'relative' }}>
          <span className="chip chip-yellow" style={{ marginBottom: 20 }}><Icon.Bolt width={12} height={12}/> Amper Turbo</span>
          <h2 style={{ fontSize: 48, lineHeight: 1.02, letterSpacing: '-0.03em', fontWeight: 700, marginBottom: 16 }}>
            Pressa? Vendemos seu carro<br/>em até 7 dias.
          </h2>
          <p style={{ fontSize: 16.5, lineHeight: 1.55, color: 'rgba(255,255,255,0.65)', maxWidth: 480 }}>
            No modo Turbo, aceleramos tudo: preparação prioritária, destaque nos anúncios e negociação ativa com compradores pré-aprovados.
          </p>
        </div>
        <div className="cta-band-cta" style={{ textAlign: 'right', position: 'relative' }}>
          <button className="btn btn-primary btn-lg" onClick={onStart}>
            Quero vender rápido <Icon.Arrow width={18} height={18}/>
          </button>
          <div style={{ fontSize: 13, color: 'rgba(255,255,255,0.45)', marginTop: 14 }}>
            Avaliação gratuita · sem compromisso
          </div>
        </div>
      </div>
    </section>
  );
};

const StickyCTA = ({ onStart }) => {
  const [show, setShow] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(false);
  React.useEffect(() => {
    const h = () => setShow(window.scrollY > 520);
    window.addEventListener('scroll', h, { passive: true }); h();
    return () => window.removeEventListener('scroll', h);
  }, []);
  return (
    <>
      {/* Mobile: barra fixa inferior (só <768px via responsive.css). */}
      <div className="sticky-cta" aria-hidden={!show} style={{ position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 35, padding: '10px 16px calc(10px + env(safe-area-inset-bottom))', background: 'rgba(247,246,243,0.94)', backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)', borderTop: '1px solid var(--ink-100)', display: 'none', transform: show ? 'translateY(0)' : 'translateY(110%)', transition: 'transform 260ms cubic-bezier(.2,.8,.2,1)' }}>
        <button className="btn btn-primary btn-lg" style={{ width: '100%' }} onClick={onStart}>Avaliar meu carro <Icon.Arrow width={18} height={18} /></button>
      </div>

      {/* Desktop: mini-card de vidro escuro no canto — substitui o CTA amarelo
          gigante que ficava no rodapé (Rian achou exagerado/poluído). Sobe
          quando o visitante passa do hero; dá pra fechar no X. */}
      <div className="float-cta" aria-hidden={!show || dismissed} style={{
        position: 'fixed', right: 24, bottom: 24, zIndex: 35,
        maxWidth: 320,
        background: 'rgba(12,12,12,0.78)', color: 'white',
        backdropFilter: 'blur(20px) saturate(140%)', WebkitBackdropFilter: 'blur(20px) saturate(140%)',
        border: '1px solid rgba(255,255,255,0.16)',
        boxShadow: '0 24px 60px rgba(0,0,0,0.45), inset 0 1px 0 rgba(255,255,255,0.12)',
        borderRadius: 18, padding: '18px 20px',
        transform: (show && !dismissed) ? 'translateY(0)' : 'translateY(140%)',
        opacity: (show && !dismissed) ? 1 : 0,
        transition: 'transform 300ms cubic-bezier(.2,.8,.2,1), opacity 300ms ease',
        pointerEvents: (show && !dismissed) ? 'auto' : 'none',
      }}>
        <button onClick={() => setDismissed(true)} aria-label="Fechar" style={{
          position: 'absolute', top: 10, right: 10,
          width: 26, height: 26, borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'rgba(255,255,255,0.55)', background: 'rgba(255,255,255,0.08)',
        }}>
          <Icon.Close width={13} height={13}/>
        </button>
        <div style={{ fontSize: 15.5, fontWeight: 700, letterSpacing: '-0.01em', marginBottom: 4, paddingRight: 24 }}>
          Pronto para vender?
        </div>
        <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginBottom: 14, lineHeight: 1.45 }}>
          Avaliação em 60 segundos. Sem cadastro, sem compromisso.
        </div>
        <button className="btn btn-primary" style={{ width: '100%', height: 44, fontSize: 14 }} onClick={onStart}>
          Avaliar meu carro <Icon.Arrow width={16} height={16}/>
        </button>
      </div>
    </>
  );
};

Object.assign(window, { Nav, Hero, StatsBar, HeroBackdrop, HeroParallaxBg, CtaBand, StickyCTA, QuickEvalModal, selStyle });
