// HM Veículos — Página do Veículo (detalhe) v2

const { useState: useStateV, useEffect: useEffectV } = React;

function VehiclePage({ vehicle, vehicles, onBack, onSelectVehicle }) {
  useReveal();
  const [photoIdx, setPhotoIdx] = useStateV(0);
  const fotos = vehicle.fotos;
  const optimizeImg = window.optimizeImg || ((u) => u);

  useEffectV(() => {
    setPhotoIdx(0);
    window.scrollTo({ top: 0, behavior: "instant" in document.documentElement.style ? "instant" : "auto" });
    if (vehicle && vehicle.db_id && typeof window.trackEvent === "function") {
      window.trackEvent("view", vehicle.db_id);
    }
  }, [vehicle.id]);

  const prev = () => setPhotoIdx((i) => (i - 1 + fotos.length) % fotos.length);
  const next = () => setPhotoIdx((i) => (i + 1) % fotos.length);

  const waMsg = `Olá! Tenho interesse no ${vehicle.marca} ${vehicle.modelo} ${vehicle.versao} ${vehicle.ano} (R$ ${vehicle.preco.toLocaleString("pt-BR")}). Está disponível?`;
  const onWAClick = () => {
    if (vehicle && vehicle.db_id && typeof window.trackEvent === "function") {
      window.trackEvent("whatsapp_click", vehicle.db_id);
    }
  };
  const fixo = window.getSetting ? window.getSetting("contato.fixo", "3730151575") : "3730151575";
  const fixoDigits = String(fixo || "").replace(/[^0-9]/g, "");
  const fixoDisplay = fixoDigits.length === 10
    ? `(${fixoDigits.slice(0,2)}) ${fixoDigits.slice(2,6)}-${fixoDigits.slice(6)}`
    : fixoDigits.length === 11 ? `(${fixoDigits.slice(0,2)}) ${fixoDigits.slice(2,7)}-${fixoDigits.slice(7)}` : fixo;

  const similares = vehicles.filter((v) => v.id !== vehicle.id).slice(0, 3);

  return (
    <main data-screen-label={`02 Detalhe — ${vehicle.marca} ${vehicle.modelo}`}>
      <div className="breadcrumb">
        <div className="container">
          <a href="#" onClick={(e) => { e.preventDefault(); onBack(); }}>
            <Icon.ArrowLeft size={16} /> Voltar à lista
          </a>
        </div>
      </div>

      <div className="container">
        <div className="detail-head reveal">
          <div>
            <div className="detail-eyebrow">{vehicle.marca} · {vehicle.ano}/{vehicle.anoModelo}</div>
            <h1 className="detail-title">{vehicle.modelo}</h1>
            <p className="detail-version">{vehicle.versao}</p>
          </div>
        </div>

        <div className="detail-grid">
          {/* Galeria */}
          <div className="gallery reveal">
            <div className="gallery-main">
              <img src={optimizeImg(fotos[photoIdx], 1600, 80)} alt={`${vehicle.marca} ${vehicle.modelo} - foto ${photoIdx + 1}`} key={photoIdx} onError={window.handleImgError} />
              <div className="gallery-counter tabular">{photoIdx + 1} / {fotos.length}</div>
              {fotos.length > 1 && (
                <React.Fragment>
                  <button className="gallery-arrow left" onClick={prev} aria-label="Foto anterior"><Icon.ArrowLeft /></button>
                  <button className="gallery-arrow right" onClick={next} aria-label="Próxima foto"><Icon.ArrowRight /></button>
                </React.Fragment>
              )}
            </div>
            <div className="gallery-thumbs">
              {fotos.map((src, i) => (
                <button
                  key={i}
                  className={"thumb" + (i === photoIdx ? " active" : "")}
                  onClick={() => setPhotoIdx(i)}
                  aria-label={`Foto ${i + 1}`}
                >
                  <img src={optimizeImg(src, 240, 70)} alt="" loading="lazy" onError={window.handleImgError} />
                </button>
              ))}
            </div>
          </div>

          {/* Info */}
          <div className="detail-info">
            <div className={"detail-price-block" + (vehicle.precoPromocional && vehicle.precoPromocional > 0 && vehicle.precoPromocional < vehicle.preco ? " has-promo" : "")}>
              <PriceBlock vehicle={vehicle} variant="detail" />
              <div className="detail-actions">
                <WAPicker className="btn btn-whatsapp btn-block" message={waMsg} onSelect={onWAClick} ariaLabel="Tenho interesse">
                  <Icon.Whatsapp /> Tenho interesse
                </WAPicker>
                <a className="btn btn-ghost-light btn-block" href={`tel:+55${fixoDigits}`}>
                  <Icon.Phone size={16} /> {fixoDisplay}
                </a>
              </div>
            </div>

            <div className="specs-block">
              <SpecItem label="Ano" value={`${vehicle.ano}/${vehicle.anoModelo}`} />
              <SpecItem label="KM" value={fmtKM(vehicle.km)} />
              <SpecItem label="Câmbio" value={vehicle.cambio} />
              <SpecItem label="Combustível" value={vehicle.combustivel} />
              <SpecItem label="Cor" value={vehicle.cor} />
              <SpecItem label="Portas" value={vehicle.portas} />
            </div>

            <div className="badges-row">
              {vehicle.badges.map((b) => <span className="badge-pill" key={b}>{b}</span>)}
            </div>
          </div>
        </div>

        <div className="detail-section reveal">
          <h3 className="detail-h3">Opcionais</h3>
          <div className="optionals-grid">
            {vehicle.opcionais.map((o) => <div className="optional-item" key={o}>{o}</div>)}
          </div>
        </div>

        <div className="detail-section reveal" style={{ maxWidth: 820 }}>
          <h3 className="detail-h3">Descrição</h3>
          <div className="detail-desc">
            {vehicle.descricao.split(/\n\n+/).map((p, i) => <p key={i}>{p}</p>)}
          </div>
        </div>
      </div>

      {/* Similares */}
      <section className="related-section">
        <div className="container">
          <div className="section-head reveal">
            <div className="title-block">
              <div className="eyebrow">Veja também</div>
              <h2 className="section-title">Outros veículos que <em>você pode gostar</em></h2>
            </div>
          </div>
          <div className="vehicles-grid vehicles-grid--related">
            {similares.map((v) => (
              <VehicleCard key={v.id} vehicle={v} onClick={onSelectVehicle} />
            ))}
          </div>
        </div>
      </section>
    </main>
  );
}

function SpecItem({ label, value }) {
  return (
    <div className="spec-item">
      <div className="label">{label}</div>
      <div className="value">{value}</div>
    </div>
  );
}

window.VehiclePage = VehiclePage;
