/* Chrome compartilhado + helpers. Carregar ANTES de Vitrine.jsx / Veiculo.jsx. */
const DS = window.ColletDesignSystem_d3f4c1 || {};
const { Button } = DS;
const LOGOS = 'assets/';

/* Se o feed do estoque nao carregar (rede, bloqueio, arquivo fora do ar), o site
   nao pode quebrar em silencio nem mostrar uma grade vazia sem explicacao. */
const ESTOQUE_OK = Array.isArray(window.ESTOQUE) && window.ESTOQUE.length > 0;
if (!ESTOQUE_OK) window.ESTOQUE = [];

function AvisoEstoque({ curto = false }) {
  return (
    <div className="alerta" role="status">
      <div>
        <h3>Não foi possível carregar o estoque agora.</h3>
        <p>Pode ser a conexão. Tente recarregar a página{curto ? '' : ' — ou fale com a gente no WhatsApp, que respondemos com o que temos disponível'}.</p>
      </div>
      <div className="alerta-form">
        <button className="cds-btn cds-btn--primary cds-btn--sm" onClick={() => location.reload()}>Recarregar</button>
        <a className="btn-ghost" href={waLink('Olá! O site não carregou o estoque. Podem me mandar as opções disponíveis?')}
          target="_blank" rel="noopener noreferrer">Falar no WhatsApp</a>
      </div>
    </div>
  );
}

const WA = 'https://wa.me/5511958967088';
const waLink = msg => WA + '?text=' + encodeURIComponent(msg);

const CASAS = {
  europamotors: { label: 'Europamotors', color: 'var(--partner-europa)' },
  collet:       { label: 'Collet',       color: 'var(--partner-collet)' },
};

const precoNum = v => { const d = (v.preco || '').replace(/[^\d]/g, ''); return d ? parseInt(d, 10) : null; };
const kmNum  = v => parseInt((v.km  || '').replace(/[^\d]/g, ''), 10) || 0;
const anoNum = v => parseInt((v.ano || '').slice(0, 4), 10) || 0;
const vhref  = v => 'veiculo.html?id=' + encodeURIComponent(v.id);
/* parcela-teaser: 48x, 30% de entrada, taxa referencial 1,79% a.m. (Price) */
const finMensal = v => {
  const p = precoNum(v);
  if (p == null) return null;
  const t = 0.0179, n = 48, f = p * 0.7;
  return f * (t * Math.pow(1 + t, n)) / (Math.pow(1 + t, n) - 1);
};

const Lockup = DS.CoBrandLockup || function ({ theme = 'ink', scale = 1 }) {
  const dark = theme === 'white';
  // Usa as classes do design system (.lockup/.lk-eu/.lk-bar/.lk-co) em vez de
  // estilo inline: inline vencia o CSS e travava as alturas em 22/29px, o que
  // estourava a largura do cabecalho no celular e empurrava o menu para fora.
  return (
    <div className={'lockup' + (dark ? ' on-dark' : '') + (scale !== 1 ? ' lockup--sm' : '')}>
      <img decoding="async" className="lk-eu" src={LOGOS + (dark ? 'europamotors-white.png' : 'europamotors-ink.png')} alt="Europamotors" />
      <span className="lk-bar" />
      <img decoding="async" className="lk-co" src={LOGOS + (dark ? 'collet-white.svg' : 'collet-ink.svg')} alt="Collet" />
    </div>
  );
};

/* cobrand=true SOMENTE dentro do estoque. Demais rotas: assinatura Collet. */
const LINKS = [
  { href: 'index.html', label: 'Home', key: 'home' },
  { href: 'estoque.html', label: 'Estoque', key: 'estoque' },
  { href: 'blindagem.html', label: 'Blindagem', key: 'blindagem' },
  { href: 'consignacao.html', label: 'Consignação', key: 'consignacao' },
  { href: 'sobre.html', label: 'Sobre', key: 'sobre' },
];

function SiteHeader({ cobrand = false, active = '' }) {
  const [open, setOpen] = React.useState(false);
  const abriuCom = React.useRef(null);
  const painel = React.useRef(null);
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    if (!open) return () => { document.body.style.overflow = ''; };
    // Esc fecha, e o foco volta para o botao que abriu (senao o teclado fica perdido).
    const aoTeclar = e => { if (e.key === 'Escape') setOpen(false); };
    document.addEventListener('keydown', aoTeclar);
    const alvo = painel.current && painel.current.querySelector('a, button');
    if (alvo) alvo.focus();
    return () => {
      document.body.style.overflow = '';
      document.removeEventListener('keydown', aoTeclar);
      if (abriuCom.current && document.contains(abriuCom.current)) abriuCom.current.focus();
    };
  }, [open]);
  return (
    <React.Fragment>
    <a className="skip" href="#main">Pular para o conteúdo</a>
    <header className={'hd' + (cobrand ? '' : ' collet')}>
      <div className="wrap hd-in">
        <a href="index.html" aria-label="Início">
          {cobrand
            ? <Lockup theme="ink" />
            : <img decoding="async" className="mark" src={LOGOS + 'collet-ink.svg'} alt="Collet" />}
        </a>
        <nav className="nav">
          {LINKS.filter(l => l.key !== 'home').map(l => (
            <a key={l.key} href={l.href} className={active === l.key ? 'on' : ''}>{l.label}</a>
          ))}
        </nav>
        <div className="hd-cta">
          {Button
            ? (cobrand
              ? <Button variant="primary" size="sm" onClick={() => window.open(waLink('Olá! Vi o estoque no site e quero falar com um consultor.'), '_blank')}>Falar com consultor</Button>
              : <Button variant="outline" size="sm" onClick={() => { location.href = 'estoque.html'; }}>Ver estoque</Button>)
            : <a className="cds-btn cds-btn--primary cds-btn--sm" href="estoque.html">Ver estoque</a>}
        </div>
        <button className="burger" aria-label="Abrir menu" aria-expanded={open}
          onClick={e => { abriuCom.current = e.currentTarget; setOpen(true); }}>
          <span /><span /><span />
        </button>
      </div>
    </header>
    {open && (
        <div className="drawer-ovl" onClick={() => setOpen(false)}>
          <div className="drawer" ref={painel} role="dialog" aria-modal="true" aria-label="Menu" onClick={e => e.stopPropagation()}>
            <div className="drawer-hd">
              <img loading="lazy" decoding="async" className="mark" style={{ height: 24 }} src={LOGOS + 'collet-ink.svg'} alt="Collet" />
              <button className="drawer-x" aria-label="Fechar" onClick={() => setOpen(false)}>✕</button>
            </div>
            <nav className="drawer-nav">
              {LINKS.map(l => (
                <a key={l.key} href={l.href} className={active === l.key ? 'on' : ''}>{l.label}</a>
              ))}
            </nav>
            <div className="drawer-ft">
              <a className="cds-btn cds-btn--primary" href="estoque.html">Ver estoque</a>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

function SiteFooter({ cobrand = false }) {
  return (
    <footer className="ft">
      <div className="wrap">
        {cobrand
          ? <Lockup theme="white" scale={0.9} />
          : <img loading="lazy" decoding="async" className="mark" style={{ height: 26 }} src={LOGOS + 'collet-white.svg'} alt="Collet" />}
        <div className="ft-cols">
          <div><span className="fk">Navegação</span>
            <nav className="ft-nav">
              {LINKS.map(l => <a key={l.key} href={l.href}>{l.label}</a>)}
            </nav>
          </div>
          {cobrand && <div><span className="fk">Europamotors</span><p>Rede Mercedes-Benz<br />São Paulo · SP</p></div>}
          <div><span className="fk">Collet · Showroom</span><p>Av. Hélio Pellegrino, 15<br />Vila Nova Conceição · SP</p></div>
          <div><span className="fk">Collet · Fábrica</span><p>Estrada Velha de Cotia, 450<br />Cotia · SP</p></div>
          <div><span className="fk">Contato</span><p><a href="tel:+5511958967088">(11) 95896-7088</a><br /><a href="mailto:atendimento@colletblindagens.com.br">atendimento@colletblindagens.com.br</a></p></div>
        </div>
        <p className="fine">CC Blindagens LTDA · CNPJ 46.032.163/0001-57 · Imagens meramente ilustrativas. Preços e disponibilidade sujeitos a alteração sem aviso prévio.</p>
      </div>
    </footer>
  );
}

function Stage({ v, src }) {
  const [failed, setFailed] = React.useState(false);
  const use = src || v.foto;
  if (use && !failed) {
    return <img loading="lazy" decoding="async" className="ph" src={use} alt={v.marca + ' ' + v.modelo} onError={() => setFailed(true)} />;
  }
  return (
    <div className="ghost">
      <img loading="lazy" decoding="async" src={LOGOS + 'collet-ink.svg'} alt="" />
      <span>{use ? 'Foto indisponível' : 'Fotos sob consulta'}</span>
    </div>
  );
}

/* Estrela Mercedes — SVG copiado do código do site original (VeiculoDetalhe.tsx) */
function MBStar({ size = 20 }) {
  return (
    <svg viewBox="0 0 80 80" width={size} height={size} fill="currentColor" aria-hidden="true" style={{ display: 'block', flex: '0 0 auto' }}>
      <path d="M58.6 4.5C53 1.6 46.7 0 40 0c-6.7 0-13 1.6-18.6 4.5C8.7 11.2 0 24.6 0 40c0 15.4 8.7 28.8 21.5 35.5C27 78.3 33.3 80 40 80c6.7 0 12.9-1.7 18.5-4.6C71.3 68.8 80 55.4 80 40c0-15.4-8.7-28.8-21.4-35.5zM4 40c0-13.1 7-24.5 17.5-30.9C26.6 6 32.5 4.2 39 4l-4.5 32.7-13 10.1L8.3 57.1C5.6 52 4 46.2 4 40zm54.6 30.8C53.1 74.1 46.8 76 40 76c-6.8 0-13.2-1.9-18.6-5.2-4.9-2.9-8.9-6.9-11.9-11.7l11.9-4.9L40 46.6l18.6 7.5 12 4.9c-3 4.9-7.2 8.9-12 11.8zm0-24l-12.9-10L41.1 4c6.3.2 12.3 2 17.4 5.1C69 15.4 76 26.9 76 40c0 6.2-1.5 12-4.3 17.1L58.6 46.8z"/>
    </svg>
  );
}

function VehicleCard({ v }) {
  const casa = CASAS[v.casa];
  const tags = v.tags.slice(0, 2);
  const reservado = v.status === 'reservado';
  return (
    <a className="vc" href={vhref(v)}>
      <div className="vc-ph">
        <Stage v={v} />
        {(tags.length > 0 || v.certified || reservado) && (
          <div className="vc-tags">
            {reservado && <span className="vt">Reservado</span>}
            {tags.map(t => <span key={t} className="vt">{t}</span>)}
            {v.certified && <span className="vt vt-cert"><MBStar size={12} />Certified</span>}
          </div>
        )}
      </div>
      <p className="house"><i style={{ background: casa.color }} />{casa.label}</p>
      <h3><span className="mk">{v.marca}</span> {v.modelo}</h3>
      <p className="ver">{v.versao}</p>
      <p className="mtr">{v.ano.slice(-4)} · {v.km} · {v.comb}</p>
      <p className={'price' + (precoNum(v) == null ? ' consult' : '')}>{v.preco}</p>
      {finMensal(v) != null && <p className="vc-fin">ou R$ {Math.round(finMensal(v)).toLocaleString('pt-BR')}/mês em 48x</p>}
    </a>
  );
}

Object.assign(window, { DS, Button, LOGOS, ESTOQUE_OK, AvisoEstoque, CASAS, WA, waLink, Lockup, MBStar, SiteHeader, SiteFooter, Stage, VehicleCard, precoNum, kmNum, anoNum, vhref, finMensal });
