/* global React, Icon, AmperLogo, fmtBRL, fmtBRLShort, FIPE, YEARS, CONDITIONS, estimatePrice, amperOffer, sampleListings, isMarcaNacional, ANO_MAXIMO */

const SimulatorNav = ({ onExit, step, totalSteps, onStepClick, completedSteps }) => {
  const stepLabels = ['Marca', 'Modelo', 'Ano', 'Versão', 'Detalhes', 'Seus dados'];
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 30,
      background: 'var(--paper)', borderBottom: '1px solid var(--ink-100)',
    }}>
      <div className="simnav-inner" style={{ maxWidth: 1360, margin: '0 auto', padding: '16px 40px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 24 }}>
        <AmperLogo height={16}/>

        <div className="simnav-progress" style={{ flex: 1, maxWidth: 560, margin: '0 40px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-500)', marginBottom: 10, fontWeight: 600 }}>
            <span>Avaliação</span>
            <span className="mono">Passo {step} / {totalSteps}</span>
          </div>

          {/* Clickable step dots */}
          <div className="simnav-steps" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            {Array.from({ length: totalSteps }, (_, i) => {
              const n = i + 1;
              const isCurrent = n === step;
              const isCompleted = completedSteps ? completedSteps[n] : n < step;
              const isClickable = !!onStepClick && (isCompleted || isCurrent || n < step);

              return (
                <React.Fragment key={n}>
                  <button
                    onClick={() => isClickable && onStepClick && onStepClick(n)}
                    disabled={!isClickable}
                    title={stepLabels[i]}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 8,
                      padding: '6px 10px',
                      borderRadius: 99,
                      background: isCurrent ? 'var(--ink-900)' : isCompleted ? 'var(--amper-yellow-soft)' : 'transparent',
                      color: isCurrent ? 'white' : isCompleted ? 'var(--ink-900)' : 'var(--ink-400)',
                      border: 'none',
                      cursor: isClickable ? 'pointer' : 'not-allowed',
                      fontSize: 12.5, fontWeight: 600,
                      transition: 'all 160ms',
                      whiteSpace: 'nowrap',
                    }}>
                    <span style={{
                      width: 20, height: 20, borderRadius: '50%',
                      background: isCurrent ? 'var(--amper-yellow)' : isCompleted ? 'var(--ink-900)' : 'var(--ink-100)',
                      color: isCurrent ? 'var(--ink-900)' : isCompleted ? 'white' : 'var(--ink-500)',
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 11, fontWeight: 700, fontFamily: 'var(--font-mono)',
                      flexShrink: 0,
                    }}>
                      {isCompleted && !isCurrent
                        ? <Icon.Check width={11} height={11}/>
                        : n
                      }
                    </span>
                    <span className="simnav-label">{stepLabels[i]}</span>
                  </button>
                  {n < totalSteps && (
                    <div style={{
                      flex: '0 0 auto', width: 12, height: 2,
                      background: n < step ? 'var(--ink-900)' : 'var(--ink-100)',
                      transition: 'background 160ms',
                    }}/>
                  )}
                </React.Fragment>
              );
            })}
          </div>
        </div>

        <button onClick={onExit} className="btn btn-ghost btn-sm">
          <Icon.Close width={16} height={16}/> Sair
        </button>
      </div>
    </header>
  );
};

const StepShell = ({ title, subtitle, children, onBack, onNext, nextLabel = 'Continuar', nextDisabled, aside, onForward }) => (
  <div className="step-shell" style={{
    maxWidth: 1100, margin: '0 auto',
    padding: '40px 40px 100px',
    display: 'grid',
    gridTemplateColumns: aside ? '1fr 380px' : '1fr',
    gap: 48,
  }}>
    <div>
      {(onBack || onForward) && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 28 }}>
          {onBack && (
            <button onClick={onBack} aria-label="Voltar" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 16px 9px 12px', borderRadius: 99, border: '1px solid var(--ink-200)', background: 'var(--paper)', fontSize: 13.5, fontWeight: 600, color: 'var(--ink-700)', cursor: 'pointer', transition: 'all 140ms' }}>
              <Icon.Arrow width={16} height={16} style={{ transform: 'rotate(180deg)' }}/> Voltar
            </button>
          )}
          {onForward && (
            <button onClick={onForward} aria-label="Avançar" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '9px 12px 9px 16px', borderRadius: 99, border: '1px solid var(--ink-200)', background: 'var(--paper)', fontSize: 13.5, fontWeight: 600, color: 'var(--ink-700)', cursor: 'pointer', transition: 'all 140ms' }}>
              Avançar <Icon.Arrow width={16} height={16}/>
            </button>
          )}
        </div>
      )}
      <h1 style={{ fontSize: 44, lineHeight: 1.05, letterSpacing: '-0.03em', fontWeight: 700, marginBottom: 12 }}>{title}</h1>
      {subtitle && <p style={{ fontSize: 17, color: 'var(--ink-600)', marginBottom: 40, lineHeight: 1.5 }}>{subtitle}</p>}
      {children}
      <div style={{ display: 'flex', gap: 12, marginTop: 40 }}>
        {onBack && onNext && <button onClick={onBack} className="btn btn-ghost btn-lg">Voltar</button>}
        {onNext && (
          <button onClick={onNext} disabled={nextDisabled} className="btn btn-primary btn-lg" style={{ opacity: nextDisabled ? 0.4 : 1, cursor: nextDisabled ? 'not-allowed' : 'pointer' }}>
            {nextLabel} <Icon.Arrow width={18} height={18}/>
          </button>
        )}
      </div>
    </div>
    {aside && <aside>{aside}</aside>}
  </div>
);

// --- Shared: loading spinner (usado enquanto busca dados reais) ---
const LoadSpinner = ({ msg = 'Carregando…' }) => {
  React.useEffect(() => {
    if (!document.getElementById('amper-spin-kf')) {
      const s = document.createElement('style');
      s.id = 'amper-spin-kf';
      s.textContent = '@keyframes amper-spin{to{transform:rotate(360deg)}}';
      document.head.appendChild(s);
    }
  }, []);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: 60, gap: 14 }}>
      <div style={{ width: 36, height: 36, borderRadius: '50%', border: '3px solid var(--ink-100)', borderTopColor: 'var(--ink-900)', animation: 'amper-spin 0.7s linear infinite' }}/>
      <span style={{ fontSize: 13, color: 'var(--ink-500)' }}>{msg}</span>
    </div>
  );
};

// Dropdown padrão dos passos em página cheia — mesma receita visual do
// selStyle usado no popup/Hero (window.selStyle), só que num tamanho maior
// (mais respiro pro toque em tela cheia em vez de dentro de um card apertado).
const stepSelectStyle = {
  width: '100%', height: 56, padding: '0 18px',
  border: '1px solid var(--ink-200)', borderRadius: 12,
  background: 'var(--paper)', color: 'var(--ink-900)', fontSize: 16, 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 18px center',
};

// --- Step: Brand picker (dados reais via window.AmperAPI) ---
// Lista suspensa em vez de grade de botões — padronizado com o popup/Hero
// (pedido do Rian 2026-09-10: consistência entre todo ponto de entrada).
const BrandStep = ({ value, onSelect }) => {
  const [brands, setBrands] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    window.AmperAPI.getMarcas()
      .then(data => { setBrands(Array.isArray(data) ? data : []); setLoading(false); })
      .catch(() => {
        setBrands(FIPE.brands.map(b => ({ codigo: b.id, nome: b.name })));
        setLoading(false);
      });
  }, []);

  // Só marcas comuns no Brasil — corta as exóticas/raras do catálogo real.
  const nacionais = brands.filter(b => isMarcaNacional(b.nome));

  return (
    <div>
      <div className="label" style={{ marginBottom: 8 }}>Marca</div>
      <select
        value={value || ''}
        disabled={loading}
        onChange={(e) => {
          const b = nacionais.find(x => String(x.codigo) === e.target.value);
          if (b) onSelect({ codigo: String(b.codigo), nome: b.nome });
        }}
        style={stepSelectStyle}
      >
        <option value="">{loading ? 'Carregando marcas…' : 'Selecione a marca'}</option>
        {nacionais.map(b => <option key={b.codigo} value={String(b.codigo)}>{b.nome}</option>)}
      </select>
    </div>
  );
};

// --- Step: Model (dados reais da marca selecionada) ---
const ModelStep = ({ codigoMarca, value, onSelect }) => {
  const [q, setQ] = React.useState('');
  const [models, setModels] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

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

  // Só o nome-base (ex: "A3") — a versão específica (ex: "A3 Sedan 1.4 TFSI")
  // é escolhida depois do ano, na etapa de Características (cada versão só
  // existe em determinados anos, então faz mais sentido nessa ordem).
  const groups = React.useMemo(() => window.groupModelos(models), [models]);
  const list = q
    ? groups.filter(g => g.nome.toLowerCase().includes(q.toLowerCase()))
    : groups;

  if (loading) return <LoadSpinner msg="Carregando modelos…"/>;

  return (
    <div>
      <div style={{ position: 'relative', marginBottom: 24 }}>
        <Icon.Search width={18} height={18} style={{ position: 'absolute', left: 16, top: 17, color: 'var(--ink-400)' }}/>
        <input
          value={q} onChange={(e) => setQ(e.target.value)}
          placeholder="Buscar modelo"
          style={{
            width: '100%', height: 52, padding: '0 16px 0 44px',
            border: '1px solid var(--ink-200)', borderRadius: 12,
            fontSize: 15, background: 'var(--paper)',
          }}
        />
      </div>
      <div className="grid-models" style={{ display: 'flex', flexDirection: 'column', gap: 8, maxHeight: 440, overflowY: 'auto', paddingRight: 4 }}>
        {list.map(g => {
          const active = value === g.key;
          return (
            <button key={g.key} onClick={() => onSelect({ codigo: g.key, nome: g.nome, variants: g.variants })} style={{
              padding: '14px 18px', borderRadius: 12,
              border: active ? '2px solid var(--ink-900)' : '1px solid var(--ink-200)',
              background: active ? 'var(--amper-yellow-soft)' : 'var(--paper)',
              textAlign: 'left', transition: 'all 120ms',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
            }}>
              <span style={{ fontSize: 15, fontWeight: 600 }}>{g.nome}</span>
              {active && <Icon.Check width={16} height={16} style={{ flexShrink: 0 }}/>}
            </button>
          );
        })}
      </div>
    </div>
  );
};

// --- Step: Year — soma os anos disponíveis em TODAS as versões do modelo ---
// (uma versão pode só existir em alguns anos; o ano deste passo ainda não
// escolhe a versão, só filtra o que aparece na etapa seguinte).
const YearStep = ({ codigoMarca, variants, value, onSelect }) => {
  const [porVariante, setPorVariante] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!codigoMarca || !variants || variants.length === 0) return;
    setLoading(true);
    window.anosPorVariante(codigoMarca, variants)
      .then(r => { setPorVariante(r); setLoading(false); })
      .catch(() => setLoading(false));
  }, [codigoMarca, variants]);

  const uniqueYears = [...new Set(
    porVariante.flatMap(r => r.anos.map(a => a.codigo.split('-')[0] === '32000' ? '0 km' : a.codigo.split('-')[0]))
  )]
    .filter(y => y === '0 km' || Number(y) <= ANO_MAXIMO) // não mostra ano além do catálogo atual
    .sort((a, b) => a === '0 km' ? -1 : b === '0 km' ? 1 : Number(b) - Number(a));

  if (loading) return <LoadSpinner msg="Carregando anos…"/>;

  return (
    <div className="grid-years" style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 10 }}>
      {uniqueYears.map(y => {
        const active = value === y;
        return (
          <button key={y} onClick={() => onSelect(y)} style={{
            height: 64, borderRadius: 12,
            border: active ? '2px solid var(--ink-900)' : '1px solid var(--ink-200)',
            background: active ? 'var(--amper-yellow-soft)' : 'var(--paper)',
            fontSize: y.length > 4 ? 14 : 20, fontWeight: 700, fontFamily: 'var(--font-mono)',
            letterSpacing: '0.02em',
          }}>{y}</button>
        );
      })}
    </div>
  );
};

// --- Step: Características — versão específica (motor/carroceria/combustível)
// que realmente existe no ano escolhido. Ex: escolheu "A3" no modelo e "2020"
// no ano → aqui mostra só as versões de A3 que existiram em 2020.
const VersionStep = ({ codigoMarca, variants, year, value, modelValue, onSelect }) => {
  const [porVariante, setPorVariante] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    if (!codigoMarca || !variants || variants.length === 0) return;
    setLoading(true);
    window.anosPorVariante(codigoMarca, variants)
      .then(r => { setPorVariante(r); setLoading(false); })
      .catch(() => setLoading(false));
  }, [codigoMarca, variants]);

  const yearKey = year === '0 km' ? '32000' : year;
  // Cada variante pode ter mais de uma entrada no mesmo ano (combustíveis
  // diferentes) — junta variante + entrada-ano num só item selecionável.
  const opcoes = porVariante.flatMap(({ variant, anos }) =>
    anos
      .filter(a => a.codigo.split('-')[0] === yearKey)
      .map(a => ({ variantCodigo: variant.codigo, variantNome: variant.nome, anoCodigo: a.codigo, anoNome: a.nome }))
  );

  React.useEffect(() => {
    if (!loading && opcoes.length === 1) {
      const o = opcoes[0];
      onSelect({ codigo: o.variantCodigo, nome: o.variantNome, anoCodigo: o.anoCodigo, anoNome: o.anoNome });
    }
  }, [loading, opcoes.length]);

  if (loading) return <LoadSpinner msg="Carregando características…"/>;

  return (
    <div>
      <div className="grid-models" style={{ display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 440, overflowY: 'auto', paddingRight: 4 }}>
        {opcoes.map(o => {
          // anoCodigo (ex: "2014-1") não é único entre variantes — cada
          // versão tem sua própria lista de anos, então duas versões
          // diferentes podem ter o mesmo código. Sem checar a variante junto,
          // duas linhas diferentes acendiam como "ativa" ao mesmo tempo.
          const active = value === o.anoCodigo && String(modelValue) === String(o.variantCodigo);
          return (
            <button key={`${o.variantCodigo}-${o.anoCodigo}`} onClick={() => onSelect({ codigo: o.variantCodigo, nome: o.variantNome, anoCodigo: o.anoCodigo, anoNome: o.anoNome })} style={{
              padding: '18px 20px', borderRadius: 14, flexShrink: 0,
              border: active ? '2px solid var(--ink-900)' : '1px solid var(--ink-200)',
              background: active ? 'var(--amper-yellow-soft)' : 'var(--paper)',
              textAlign: 'left', transition: 'all 140ms',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 16,
            }}>
              <div style={{ minWidth: 0, flex: 1 }}>
                <div style={{ fontSize: 16, fontWeight: 700, letterSpacing: '-0.01em', marginBottom: 4 }}>{o.variantNome}</div>
                <div style={{ fontSize: 12.5, color: 'var(--ink-500)', lineHeight: 1.45 }}>Tabela FIPE · {o.anoNome}</div>
              </div>
              {active && <Icon.Check width={20} height={20} style={{ flexShrink: 0 }}/>}
            </button>
          );
        })}
      </div>
      <div style={{ marginTop: 18, padding: '12px 16px', background: 'var(--surface)', borderRadius: 10, display: 'flex', gap: 10, fontSize: 12.5, color: 'var(--ink-600)' }}>
        <Icon.Shield width={16} height={16} style={{ flexShrink: 0, marginTop: 1 }}/>
        <div>Dados da Tabela FIPE oficial, atualizada mensalmente.</div>
      </div>
    </div>
  );
};

// --- Step: KM & Condition ---
const DetailsStep = ({ km, setKm, condition, setCondition }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 40 }}>
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
        <div className="label">Quilometragem</div>
        <div className="mono" style={{ fontSize: 14, fontWeight: 700 }}>{km.toLocaleString('pt-BR')} km</div>
      </div>
      <input type="range" min="0" max="250000" step="1000" value={km} onChange={(e) => setKm(+e.target.value)}
        style={{ width: '100%', accentColor: '#0A0A0A' }}/>
      <div className="mono" style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--ink-400)', marginTop: 6 }}>
        <span>0</span><span>125k</span><span>250k+</span>
      </div>
    </div>
    <div>
      <div className="label" style={{ marginBottom: 12 }}>Estado de conservação</div>
      <div className="grid-cond" style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
        {CONDITIONS.map(c => {
          const active = condition === c.id;
          return (
            <button key={c.id} onClick={() => setCondition(c.id)} style={{
              padding: 18, borderRadius: 14,
              border: active ? '2px solid var(--ink-900)' : '1px solid var(--ink-200)',
              background: active ? 'var(--amper-yellow-soft)' : 'var(--paper)',
              textAlign: 'left', transition: 'all 140ms',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                <span style={{ fontSize: 16, fontWeight: 600 }}>{c.label}</span>
                {active && <Icon.Check width={18} height={18}/>}
              </div>
              <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>{c.desc}</div>
            </button>
          );
        })}
      </div>
    </div>
  </div>
);

// --- Step: Contact (nome/WhatsApp/CEP/CPF/endereço) — antes de mostrar a
// oferta, pra não perder o lead se a pessoa sair depois de ver o valor, e
// já com tudo que precisa pra agendar a vistoria sem pedir de novo depois. ---
const contactInputStyle = {
  width: '100%', height: 52, padding: '0 16px',
  border: '1px solid var(--ink-200)', borderRadius: 12,
  fontSize: 15, background: 'var(--paper)',
  fontFamily: 'var(--font-body)',
};
const contactInputErrorStyle = { ...contactInputStyle, border: '1px solid var(--danger)' };

const formatPhone = (v) => {
  const d = v.replace(/\D/g, '').slice(0, 11);
  if (d.length <= 2) return d;
  if (d.length <= 7) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
  return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
};
// Formato válido (10 ou 11 dígitos, DDD real, celular com 9 na frente) — não
// confirma que a linha existe de verdade, só que não foi digitada errado.
const isValidPhone = (v) => {
  const d = v.replace(/\D/g, '');
  if (d.length !== 10 && d.length !== 11) return false;
  const ddd = Number(d.slice(0, 2));
  if (ddd < 11 || ddd > 99) return false;
  if (d.length === 11 && d[2] !== '9') return false;
  return true;
};

const formatCep = (v) => {
  const d = v.replace(/\D/g, '').slice(0, 8);
  return d.length > 5 ? `${d.slice(0, 5)}-${d.slice(5)}` : d;
};

const formatCpf = (v) => {
  const d = v.replace(/\D/g, '').slice(0, 11);
  if (d.length <= 3) return d;
  if (d.length <= 6) return `${d.slice(0, 3)}.${d.slice(3)}`;
  if (d.length <= 9) return `${d.slice(0, 3)}.${d.slice(3, 6)}.${d.slice(6)}`;
  return `${d.slice(0, 3)}.${d.slice(3, 6)}.${d.slice(6, 9)}-${d.slice(9)}`;
};
// Validação real do dígito verificador do CPF (algoritmo oficial da Receita)
// — pega erro de digitação e os clássicos CPF de mentira tipo 111.111.111-11.
const isValidCpf = (v) => {
  const d = v.replace(/\D/g, '');
  if (d.length !== 11 || /^(\d)\1{10}$/.test(d)) return false;
  const calc = (len) => {
    let sum = 0;
    for (let i = 0; i < len; i++) sum += Number(d[i]) * (len + 1 - i);
    const r = (sum * 10) % 11;
    return r === 10 ? 0 : r;
  };
  return calc(9) === Number(d[9]) && calc(10) === Number(d[10]);
};

// Formato válido, não confirma que a caixa existe — mesmo padrão do telefone/CPF.
const isValidEmail = (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim());

const ContactStep = ({
  nome, telefone, email, cep, cpf, cupom, rua, numero, complemento, bairro, cidade, uf,
  setNome, setTelefone, setEmail, setCep, setCpf, setCupom, setRua, setNumero, setComplemento, setBairro, setCidade, setUf,
}) => {
  // idle | loading | ok | error — dispara sozinho quando o CEP chega a 8
  // dígitos, busca no ViaCEP (gratuito, sem chave) e preenche o resto do
  // endereço. O número/complemento continuam manuais — o ViaCEP não sabe isso.
  const [cepStatus, setCepStatus] = React.useState('idle');
  const cepDigits = cep.replace(/\D/g, '');
  const phoneTouched = telefone.length > 0;
  const emailTouched = email.length > 0;
  const cpfTouched = cpf.length > 0;

  React.useEffect(() => {
    if (cepDigits.length !== 8) { setCepStatus('idle'); return; }
    let cancelled = false;
    setCepStatus('loading');
    fetch(`https://viacep.com.br/ws/${cepDigits}/json/`)
      .then(r => r.json())
      .then(data => {
        if (cancelled) return;
        if (data.erro) { setCepStatus('error'); return; }
        setCepStatus('ok');
        setRua(data.logradouro || '');
        setBairro(data.bairro || '');
        setCidade(data.localidade || '');
        setUf(data.uf || '');
      })
      .catch(() => { if (!cancelled) setCepStatus('error'); });
    return () => { cancelled = true; };
  }, [cepDigits]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20, maxWidth: 460 }}>
      <div>
        <div className="label" style={{ marginBottom: 8 }}>Nome completo</div>
        <input value={nome} onChange={(e) => setNome(e.target.value)} placeholder="Seu nome" style={contactInputStyle}/>
      </div>
      <div>
        <div className="label" style={{ marginBottom: 8 }}>WhatsApp</div>
        <input
          inputMode="tel" value={telefone} onChange={(e) => setTelefone(formatPhone(e.target.value))}
          placeholder="(11) 99999-9999"
          style={phoneTouched && !isValidPhone(telefone) ? contactInputErrorStyle : contactInputStyle}
        />
        {phoneTouched && !isValidPhone(telefone) && (
          <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 6 }}>Confere o número — parece incompleto ou com DDD inválido.</div>
        )}
      </div>
      <div>
        <div className="label" style={{ marginBottom: 8 }}>E-mail</div>
        <input
          type="email" inputMode="email" value={email} onChange={(e) => setEmail(e.target.value)}
          placeholder="seu@email.com"
          style={emailTouched && !isValidEmail(email) ? contactInputErrorStyle : contactInputStyle}
        />
        {emailTouched && !isValidEmail(email) && (
          <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 6 }}>Confere o e-mail — parece incompleto.</div>
        )}
      </div>
      <div>
        <div className="label" style={{ marginBottom: 8 }}>CPF</div>
        <input
          inputMode="numeric" value={cpf} onChange={(e) => setCpf(formatCpf(e.target.value))}
          placeholder="000.000.000-00"
          style={cpfTouched && cpf.replace(/\D/g, '').length === 11 && !isValidCpf(cpf) ? contactInputErrorStyle : contactInputStyle}
        />
        {cpfTouched && cpf.replace(/\D/g, '').length === 11 && !isValidCpf(cpf) && (
          <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 6 }}>Esse CPF não parece válido — confere os números.</div>
        )}
      </div>
      <div>
        <div className="label" style={{ marginBottom: 8 }}>CEP</div>
        <div style={{ position: 'relative' }}>
          <input
            inputMode="numeric" value={cep} onChange={(e) => setCep(formatCep(e.target.value))}
            placeholder="00000-000"
            style={cepStatus === 'error' ? contactInputErrorStyle : contactInputStyle}
          />
          {cepStatus === 'loading' && (
            <div style={{ position: 'absolute', right: 16, top: '50%', transform: 'translateY(-50%)', fontSize: 12, color: 'var(--ink-500)' }}>Buscando…</div>
          )}
        </div>
        {cepStatus === 'error' && (
          <div style={{ fontSize: 12, color: 'var(--danger)', marginTop: 6 }}>CEP não encontrado — confere os números ou preenche o endereço manualmente abaixo.</div>
        )}
      </div>

      {/* Endereço só aparece depois que o CEP resolveu (ou deu erro — nesse
          caso a pessoa preenche tudo na mão). Antes disso não faz sentido
          mostrar campos vazios que vão ser sobrescritos em 1 segundo. */}
      {(cepStatus === 'ok' || cepStatus === 'error') && (
        <>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 120px', gap: 12 }}>
            <div>
              <div className="label" style={{ marginBottom: 8 }}>Rua</div>
              <input value={rua} onChange={(e) => setRua(e.target.value)} placeholder="Rua / Avenida" style={contactInputStyle}/>
            </div>
            <div>
              <div className="label" style={{ marginBottom: 8 }}>Número</div>
              <input inputMode="numeric" value={numero} onChange={(e) => setNumero(e.target.value)} placeholder="123" style={contactInputStyle}/>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <div className="label" style={{ marginBottom: 8 }}>Complemento <span style={{ fontWeight: 400, textTransform: 'none', color: 'var(--ink-400)' }}>(opcional)</span></div>
              <input value={complemento} onChange={(e) => setComplemento(e.target.value)} placeholder="Apto, bloco…" style={contactInputStyle}/>
            </div>
            <div>
              <div className="label" style={{ marginBottom: 8 }}>Bairro</div>
              <input value={bairro} onChange={(e) => setBairro(e.target.value)} placeholder="Bairro" style={contactInputStyle}/>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 90px', gap: 12 }}>
            <div>
              <div className="label" style={{ marginBottom: 8 }}>Cidade</div>
              <input value={cidade} onChange={(e) => setCidade(e.target.value)} placeholder="Cidade" style={contactInputStyle}/>
            </div>
            <div>
              <div className="label" style={{ marginBottom: 8 }}>UF</div>
              <input value={uf} onChange={(e) => setUf(e.target.value.toUpperCase().slice(0, 2))} placeholder="SP" style={contactInputStyle}/>
            </div>
          </div>
        </>
      )}

      <div>
        <div className="label" style={{ marginBottom: 8 }}>Cupom promocional <span style={{ fontWeight: 400, textTransform: 'none', color: 'var(--ink-400)' }}>(opcional)</span></div>
        <input value={cupom} onChange={(e) => setCupom(e.target.value.toUpperCase())} placeholder="Se você tiver um" style={contactInputStyle}/>
      </div>

      <div style={{ display: 'flex', gap: 10, fontSize: 12.5, color: 'var(--ink-600)', padding: '12px 16px', background: 'var(--surface)', borderRadius: 10 }}>
        <Icon.Shield width={16} height={16} style={{ flexShrink: 0, marginTop: 1 }}/>
        <div>Usamos só pra agendar sua vistoria e preparar o contrato. Nunca compartilhamos com terceiros.</div>
      </div>
    </div>
  );
};

// --- Step: AI Analyzing ---
const AnalyzingStep = () => {
  const [phase, setPhase] = React.useState(0);
  const phases = [
    'Identificando versão e especificações…',
    'Analisando histórico de vendas do modelo…',
    'Calculando valor de mercado…',
    'Aplicando margem e elegibilidade de garantia…',
    'Finalizando sua oferta firme…',
  ];
  React.useEffect(() => {
    if (phase < phases.length - 1) {
      const t = setTimeout(() => setPhase(phase + 1), 700);
      return () => clearTimeout(t);
    }
  }, [phase]);
  return (
    <div className="analyzing-wrap" style={{ padding: '80px 0', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
      <div className="analyzing-ring" style={{ position: 'relative', width: 120, height: 120, marginBottom: 40 }}>
        <svg viewBox="0 0 120 120" style={{ position: 'absolute', inset: 0 }}>
          <circle cx="60" cy="60" r="52" stroke="var(--ink-100)" strokeWidth="8" fill="none"/>
          <circle cx="60" cy="60" r="52" stroke="var(--amper-yellow)" strokeWidth="8" fill="none" strokeLinecap="round"
            strokeDasharray={`${((phase + 1) / phases.length) * 326.7} 326.7`}
            transform="rotate(-90 60 60)" style={{ transition: 'stroke-dasharray 600ms ease' }}/>
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon.Sparkle width={40} height={40}/>
        </div>
      </div>
      <h2 className="analyzing-title" style={{ fontSize: 36, fontWeight: 700, letterSpacing: '-0.025em', marginBottom: 32 }}>
        Analisando o mercado para você…
      </h2>
      <div style={{ width: '100%', maxWidth: 460 }}>
        {phases.map((p, i) => (
          <div key={i} className="analyzing-phase" style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '12px 18px', borderRadius: 10,
            background: i === phase ? 'var(--amper-yellow-soft)' : 'transparent',
            opacity: i <= phase ? 1 : 0.35,
            marginBottom: 4,
            transition: 'all 300ms',
          }}>
            <div style={{
              width: 22, height: 22, borderRadius: '50%',
              background: i < phase ? 'var(--success)' : i === phase ? 'var(--amper-yellow)' : 'var(--ink-200)',
              color: i < phase ? 'white' : 'var(--ink-900)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              {i < phase ? <Icon.Check width={14} height={14}/> : <span className="mono" style={{ fontSize: 11, fontWeight: 700 }}>{i + 1}</span>}
            </div>
            <span style={{ fontSize: 14.5, fontWeight: 500, textAlign: 'left' }}>{p}</span>
          </div>
        ))}
      </div>
    </div>
  );
};

// Aside: live summary
const Summary = ({ brand, brandName, model, modelName, year, version, versionName, km, condition }) => {
  const cond = CONDITIONS.find(x => x.id === condition);
  const displayBrand = brandName || brand || '—';
  const displayModel = modelName || model || '—';
  const displayVersion = versionName || (version && !version.includes('-') ? version : '') || '—';
  return (
    <div className="card" style={{ padding: 24, position: 'sticky', top: 120, border: '1px solid var(--ink-100)' }}>
      <div className="label" style={{ marginBottom: 12 }}>Resumo</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {[
          { k: 'Marca', v: displayBrand },
          { k: 'Modelo', v: displayModel },
          { k: 'Ano', v: year || '—' },
          { k: 'Versão', v: displayVersion },
          { k: 'KM', v: km ? `${km.toLocaleString('pt-BR')} km` : '—' },
          { k: 'Estado', v: cond?.label || '—' },
        ].map((r, i) => (
          <div key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 14 }}>
            <span style={{ color: 'var(--ink-500)' }}>{r.k}</span>
            <span style={{ fontWeight: 600 }}>{r.v}</span>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 24, paddingTop: 18, borderTop: '1px solid var(--ink-100)', display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, color: 'var(--ink-500)' }}>
        <Icon.Shield width={14} height={14}/> Dados protegidos · LGPD
      </div>
    </div>
  );
};

Object.assign(window, { SimulatorNav, StepShell, BrandStep, ModelStep, YearStep, VersionStep, DetailsStep, ContactStep, AnalyzingStep, Summary, isValidPhone, isValidCpf, isValidEmail });
