// HM Veículos — App root + roteamento simples

const { useState: useStateA, useEffect: useEffectA } = React;

function App() {
  const [route, setRoute] = useStateA({ name: "home", vehicleId: null });

  // permite voltar via histórico (botão back do navegador)
  useEffectA(() => {
    const onPop = () => {
      const hash = window.location.hash;
      if (hash.startsWith("#veiculo/")) {
        setRoute({ name: "vehicle", vehicleId: hash.replace("#veiculo/", "") });
      } else {
        setRoute({ name: "home", vehicleId: null });
      }
    };
    window.addEventListener("popstate", onPop);
    onPop();
    return () => window.removeEventListener("popstate", onPop);
  }, []);

  const navigateHome = (anchor) => {
    if (window.location.hash.startsWith("#veiculo/")) {
      window.history.pushState({}, "", "#" + (anchor || "top"));
    }
    setRoute({ name: "home", vehicleId: null });
    setTimeout(() => {
      if (anchor) {
        const el = document.getElementById(anchor);
        if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
      } else {
        window.scrollTo({ top: 0, behavior: "smooth" });
      }
    }, 30);
  };

  const selectVehicle = (v) => {
    window.history.pushState({}, "", "#veiculo/" + v.id);
    setRoute({ name: "vehicle", vehicleId: v.id });
    setTimeout(() => window.scrollTo({ top: 0, behavior: "auto" }), 30);
  };

  const handleNav = (name, anchor) => {
    if (name === "home") navigateHome(anchor);
  };

  const vehicles = window.HM_DATA.VEHICLES;
  const current = vehicles.find((v) => v.id === route.vehicleId) || vehicles[0];

  // Atualiza título da aba + meta tags Open Graph quando rota muda
  useEffectA(() => {
    if (typeof window.setMetaTags !== "function") return;
    if (route.name === "vehicle" && current) {
      const fotos = current.fotos || [];
      const photoRaw = fotos[0];
      const photo = photoRaw && window.optimizeImg ? window.optimizeImg(photoRaw, 1200, 85) : photoRaw;
      const promoOk = current.precoPromocional && current.precoPromocional > 0 && current.precoPromocional < current.preco;
      const precoDisp = promoOk ? current.precoPromocional : current.preco;
      const hasC = (Math.round(precoDisp * 100)) % 100 !== 0;
      const precoFmt = precoDisp.toLocaleString("pt-BR", {
        minimumFractionDigits: hasC ? 2 : 0,
        maximumFractionDigits: 2,
      });
      const tagPromo = promoOk ? " (oferta!)" : "";
      const title = `${current.marca} ${current.modelo} ${current.anoModelo}${tagPromo} · R$ ${precoFmt} · HM Veículos`;
      const desc = (current.descricao && current.descricao.replace(/\s+/g, " ").trim().slice(0, 200))
        || `${current.marca} ${current.modelo} ${current.versao || ""} ${current.anoModelo}, ${(current.km || 0).toLocaleString("pt-BR")} km, ${current.cambio}, ${current.combustivel}.`;
      window.setMetaTags({
        title, description: desc, image: photo,
        url: window.location.origin + window.location.pathname + "#veiculo/" + current.id,
      });
    } else {
      window.setMetaTags({
        title: "HM Veículos",
        description: "+20 anos vendendo seminovos com procedência em Divinópolis-MG. Garantia, atendimento humano, WhatsApp direto com a Mariana.",
        url: window.location.origin + window.location.pathname,
      });
    }
  }, [route.name, route.vehicleId, current && current.id]);

  if (!vehicles.length) {
    return (
      <React.Fragment>
        <ScrollProgress />
        <Header onNav={handleNav} route={route.name} />
        <main style={{ minHeight: "60vh", display: "grid", placeItems: "center", padding: "120px 24px", textAlign: "center" }}>
          <div>
            <div className="eyebrow" style={{ justifyContent: "center", marginBottom: 16 }}>Estoque</div>
            <h2 style={{ fontFamily: "Archivo, sans-serif", fontSize: 32, marginBottom: 12 }}>
              {window.HM_DATA._error ? "Não conseguimos carregar o estoque agora" : "Carregando estoque…"}
            </h2>
            <p style={{ color: "rgba(0,0,0,0.6)", maxWidth: 480, margin: "0 auto" }}>
              {window.HM_DATA._error
                ? "Tente recarregar a página em alguns instantes ou fale conosco pelo WhatsApp."
                : "Estamos buscando os veículos disponíveis."}
            </p>
            {window.HM_DATA._error && (
              <a className="btn btn-primary" style={{ marginTop: 24 }} href="https://wa.me/5537999074004?text=Ol%C3%A1!%20Vim%20atrav%C3%A9s%20do%20site%20da%20HM%20Ve%C3%ADculos%20e%20gostaria%20de%20atendimento." target="_blank" rel="noopener">
                <Icon.Whatsapp size={18} /> Falar pelo WhatsApp
              </a>
            )}
          </div>
        </main>
        <Footer />
        <WhatsAppFloat />
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      <ScrollProgress />
      <Header onNav={handleNav} route={route.name} />
      {route.name === "home" ? (
        <HomePage vehicles={vehicles} onSelectVehicle={selectVehicle} />
      ) : (
        <VehiclePage
          vehicle={current}
          vehicles={vehicles}
          onBack={() => navigateHome("estoque")}
          onSelectVehicle={selectVehicle}
        />
      )}
      <Footer />
      <WhatsAppFloat />
    </React.Fragment>
  );
}

window.bootHMApp = function () {
  if (window.__HM_BOOTED__) return;
  window.__HM_BOOTED__ = true;
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
};

if (window.HM_DATA && window.HM_DATA._ready) {
  window.bootHMApp();
}
