// HM Veículos — Homepage v2

const { useState: useStateH, useEffect: useEffectH, useRef: useRefH, useCallback: useCallbackH } = React;

// ----- Hero -----
function Hero({ onCTA }) {
  const heroRef = useRefH(null);
  const glowRef = useRefH(null);
  const mediaRef = useRefH(null);

  useEffectH(() => {
    const heroEl = heroRef.current;
    if (!heroEl) return;

    const onMove = (e) => {
      const r = heroEl.getBoundingClientRect();
      const x = e.clientX - r.left;
      const y = e.clientY - r.top;
      if (glowRef.current) {
        glowRef.current.style.transform = `translate(${x - 360}px, ${y - 360}px)`;
      }
    };
    heroEl.addEventListener("mousemove", onMove);

    const onScroll = () => {
      const y = window.scrollY;
      if (mediaRef.current && y < window.innerHeight) {
        mediaRef.current.style.transform = `scale(1.08) translateY(${y * 0.18}px)`;
      }
    };
    window.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      heroEl.removeEventListener("mousemove", onMove);
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  // Apply magnetic effect to CTA
  const ctaRef = useRefH(null);
  useEffectH(() => { if (ctaRef.current) magnetize(ctaRef.current, 0.25); }, []);

  const get = (k, fb) => (window.getSetting ? window.getSetting(k, fb) : fb);
  const heroBg = get("hero.imagem_url", "") || "https://images.unsplash.com/photo-1492144534655-ae79c964c9d7?auto=format&fit=crop&w=2200&q=85";
  const eyebrow = get("hero.eyebrow", "Divinópolis-MG · desde 2003");
  const heroSub = get("hero.subtitulo", "Mais de 20 anos vendendo seminovos com procedência em Divinópolis. Cada carro inspecionado, com 3 meses de garantia, e atendimento humano de quem entende do assunto.");
  const ctaTexto = get("hero.cta_texto", "Ver estoque");

  return (
    <section className="hero" id="top" ref={heroRef}>
      <div className="hero-media" ref={mediaRef}>
        <img src={heroBg} alt="" />
      </div>
      <div className="hero-shade"></div>
      <div className="hero-stripes"></div>
      <div className="hero-glow" ref={glowRef}></div>
      <div className="grain"></div>

      <div className="container hero-inner">
        <div className="eyebrow hero-eyebrow">{eyebrow}</div>
        <h1 className="hero-title">
          <span className="row"><span>Quer fazer</span></span>
          <span className="row"><span>o melhor</span></span>
          <span className="row"><span><em>negócio?</em></span></span>
        </h1>
        <p className="hero-sub">{heroSub}</p>
        <div className="hero-actions">
          <WAPicker className="btn btn-primary btn-lg" ariaLabel="Falar pelo WhatsApp">
            <Icon.Whatsapp size={18} /> Falar pelo WhatsApp
          </WAPicker>
          <a className="btn btn-ghost-light btn-lg" href="#estoque"
            onClick={(e) => { e.preventDefault(); onCTA(); }}>
            Explorar o estoque <Icon.ArrowUpRight size={16} />
          </a>
        </div>
      </div>
    </section>
  );
}

// ----- Marquee de marcas -----
function BrandMarquee() {
  const brands = ["Toyota", "Honda", "Hyundai", "Volkswagen", "Chevrolet", "Jeep", "Renault", "Fiat", "Ford", "Nissan"];
  const seq = [...brands, ...brands]; // duplicar para loop infinito
  return (
    <div className="marquee">
      <div className="marquee-track">
        {seq.map((b, i) => (
          <span key={i} className="marquee-item">
            {b} <span className="sep" aria-hidden="true"></span>
          </span>
        ))}
      </div>
    </div>
  );
}

// ----- Stats strip -----
function StatsStrip() {
  const ref = useRefH(null);
  const [trigger, setTrigger] = useStateH(false);
  useEffectH(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => { if (e.isIntersecting) { setTrigger(true); io.disconnect(); } });
    }, { threshold: 0.4 });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);

  return (
    <section className="stats" ref={ref}>
      <div className="container">
        <div className="stats-inner">
          {window.HM_DATA.STATS.map((s, i) => (
            <Stat key={i} item={s} trigger={trigger} />
          ))}
        </div>
      </div>
    </section>
  );
}

function Stat({ item, trigger }) {
  const match = item.num.match(/^([+]?)(\d+(?:[.,]\d+)?)([%]?)$/);
  const isNumeric = !!match;
  const v = useCountUp(isNumeric ? match[2] : 0, trigger);
  const display = isNumeric ? `${match[1]}${Math.round(v)}${match[3]}` : item.num;
  return (
    <div className="stat">
      <div className="stat-num"><span className="accent">/</span><span>{display}</span></div>
      <div className="stat-label">{item.label}</div>
    </div>
  );
}

// ----- Featured Vehicles (estoque com filtros) -----
function FeaturedVehicles({ vehicles, onSelect }) {
  const [filtered, setFiltered] = useStateH(vehicles);
  // Quando a lista de origem muda (depois de fetch async), reseta o filtrado
  useEffectH(() => { setFiltered(vehicles); }, [vehicles]);
  return (
    <section className="section" id="estoque">
      <div className="container">
        <div className="section-head reveal">
          <div className="title-block">
            <div className="eyebrow">Estoque</div>
            <h2 className="section-title">Veículos em <em>destaque</em></h2>
            <p className="section-sub">Cada um deles passou por inspeção, preparação cautelosa e está pronto pra rodar com você.</p>
          </div>
          {window.FilterBar && <FilterBar vehicles={vehicles} onChange={setFiltered} />}
        </div>
        {filtered.length > 0 ? (
          (() => {
            // Até 2 carros em destaque numa faixa maior em cima (2 colunas);
            // o resto na grade normal de 4 colunas embaixo.
            const featuredList = filtered.filter((v) => v.destaque).slice(0, 2);
            const featuredIds = new Set(featuredList.map((v) => v.id));
            const rest = filtered.filter((v) => !featuredIds.has(v.id));
            return (
              <React.Fragment>
                {featuredList.length > 0 && (
                  <div className="vehicles-featured-row">
                    {featuredList.map((v) => (
                      <VehicleCard key={v.id} vehicle={v} onClick={onSelect} featured />
                    ))}
                  </div>
                )}
                {rest.length > 0 && (
                  <div className="vehicles-grid">
                    {rest.map((v) => (
                      <VehicleCard key={v.id} vehicle={v} onClick={onSelect} />
                    ))}
                  </div>
                )}
              </React.Fragment>
            );
          })()
        ) : (
          <div className="empty-state">
            <div className="empty-state-icon" aria-hidden="true">
              <svg width="40" height="40" viewBox="0 0 24 24" fill="none">
                <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.6" />
                <path d="M16 16l4 4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />
              </svg>
            </div>
            <h3>Nenhum carro encontrado</h3>
            <p>Tente ajustar ou limpar os filtros para ver mais opções.</p>
          </div>
        )}
      </div>
    </section>
  );
}

// ----- Trust -----
function TrustSection() {
  const items = window.HM_DATA.TRUST_ITEMS;
  const trustSub = window.getSetting ? window.getSetting("textos.trust_sub", "Mais de duas décadas comprando, vendendo e cuidando de carros em Divinópolis. Não é sorte, é método.") : "Mais de duas décadas comprando, vendendo e cuidando de carros em Divinópolis. Não é sorte, é método.";
  const iconFor = (i) => {
    const Icons = [Icon.Shield, Icon.Search, Icon.Hand, Icon.Sparkle, Icon.ChevDouble, Icon.Whatsapp];
    const C = Icons[i % Icons.length];
    return <C size={28} />;
  };
  return (
    <section className="section section-bg" id="sobre">
      <div className="container">
        <div className="section-head reveal">
          <div className="title-block">
            <div className="eyebrow">Por que a HM</div>
            <h2 className="section-title">Por que confiar <em>na HM</em></h2>
            <p className="section-sub">{trustSub}</p>
          </div>
        </div>
        <div className="trust-grid">
          {items.map((t, i) => (
            <div className={"trust-card reveal reveal-delay-" + (i % 3)} key={i}>
              <h3>{t.title}</h3>
              <p>{t.desc}</p>
              <div className="trust-card-icon">{iconFor(i)}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// ----- Testimonials carousel -----
function TestimonialsSection() {
  const items = window.HM_DATA.TESTIMONIALS;
  const [idx, setIdx] = useStateH(0);
  const [perView, setPerView] = useStateH(typeof window !== "undefined" && window.innerWidth < 880 ? 1 : 3);

  useEffectH(() => {
    const onResize = () => setPerView(window.innerWidth < 880 ? 1 : 3);
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);

  const maxIdx = Math.max(0, items.length - perView);
  const visible = items.slice(idx, idx + perView);
  const prev = () => setIdx((i) => Math.max(0, i - 1));
  const next = () => setIdx((i) => Math.min(maxIdx, i + 1));

  return (
    <section className="section">
      <div className="container">
        <div className="section-head reveal">
          <div className="title-block">
            <div className="eyebrow">Quem comprou conta</div>
            <h2 className="section-title">A confiança de <em>quem passou</em> por aqui</h2>
          </div>
          <div style={{ display: "flex", gap: 8 }}>
            <button className="btn-icon" onClick={prev} aria-label="Anterior" disabled={idx === 0} style={{ opacity: idx === 0 ? 0.4 : 1 }}>
              <Icon.ArrowLeft size={18} />
            </button>
            <button className="btn-icon" onClick={next} aria-label="Próximo" disabled={idx === maxIdx} style={{ opacity: idx === maxIdx ? 0.4 : 1 }}>
              <Icon.ArrowRight size={18} />
            </button>
          </div>
        </div>
        <div className="testi-track" key={perView}>
          {visible.map((t, i) => (
            <div className="testi-card" key={idx + "-" + i}>
              <div className="testi-stars">{"★".repeat(t.estrelas)}</div>
              <p className="testi-text">{t.texto}</p>
              <div className="testi-meta">
                <div>
                  <div className="testi-name">{t.nome}</div>
                  <div className="testi-city">{t.cidade}</div>
                  <div className="testi-bought">{t.comprou}</div>
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className="testi-controls">
          <div className="testi-dots">
            {Array.from({ length: maxIdx + 1 }).map((_, i) => (
              <button
                key={i}
                className={"testi-dot" + (i === idx ? " active" : "")}
                onClick={() => setIdx(i)}
                aria-label={`Ir para ${i + 1}`}
              />
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

// ----- Sell banner -----
// Converte URLs do YouTube em URL embed. Aceita formatos:
//   https://youtu.be/VIDEOID
//   https://www.youtube.com/watch?v=VIDEOID
//   https://youtube.com/shorts/VIDEOID
function ytEmbed(url) {
  if (!url) return null;
  const m = String(url).match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);
  return m ? `https://www.youtube.com/embed/${m[1]}` : null;
}

function SellBanner() {
  // Plasma/flow-field de brilhos sutis (vermelho + branco) no fundo da seção
  const waveRef = useRefH(null);
  useEffectH(() => {
    const canvas = waveRef.current;
    if (!canvas || !canvas.getContext) return;
    const ctx = canvas.getContext("2d");
    const SCALE = 5; // baixa resolução pra performance (suavizada por blur no CSS)
    let width, height, imageData, data, raf = 0, stopped = false, visible = true, frame = 0;
    const parent = canvas.parentElement;
    const resize = () => {
      const w = (parent && parent.clientWidth) || window.innerWidth;
      const h = (parent && parent.clientHeight) || 400;
      canvas.width = w; canvas.height = h;
      width = Math.max(1, Math.floor(w / SCALE));
      height = Math.max(1, Math.floor(h / SCALE));
      imageData = ctx.createImageData(width, height); data = imageData.data;
    };
    resize();
    window.addEventListener("resize", resize);
    const TAU = Math.PI * 2;
    const SIN = new Float32Array(1024), COS = new Float32Array(1024);
    for (let k = 0; k < 1024; k++) { const ang = (k / 1024) * TAU; SIN[k] = Math.sin(ang); COS[k] = Math.cos(ang); }
    const fsin = (x) => SIN[Math.floor(((x % TAU) / TAU) * 1024) & 1023];
    const fcos = (x) => COS[Math.floor(((x % TAU) / TAU) * 1024) & 1023];
    const start = Date.now();
    const render = () => {
      if (stopped) return;
      raf = requestAnimationFrame(render);
      if (!visible) return;
      frame++; if (frame % 2) return; // ~30fps
      const time = (Date.now() - start) * 0.001;
      for (let y = 0; y < height; y++) {
        for (let x = 0; x < width; x++) {
          const u_x = ((2 * x - width) / height) * 1.8, u_y = ((2 * y - height) / height) * 1.8; // freq maior → brilhos menores e mais finos
          let a = 0, d = 0;
          for (let i = 0; i < 4; i++) { a += fcos(i - d + time * 0.32 - a * u_x); d += fsin(i * u_y + a); }
          const wv = (fsin(a) + fcos(d)) * 0.5;
          let v = 0.5 + 0.5 * wv; if (v < 0) v = 0; else if (v > 1) v = 1;
          v = v * v * v; // base bem mais escura → só os fios finos brilham (suave e delicado)
          let cr, cg, cb;
          const t1 = 0.8;
          if (v < t1) { const f = v / t1; cr = 200 * f; cg = 16 * f; cb = 46 * f; } // preto → vermelho do site
          else { const f = (v - t1) / (1 - t1); cr = 200 + 55 * f; cg = 16 + 239 * f; cb = 46 + 209 * f; } // vermelho → branco nos picos
          const idx = (y * width + x) * 4;
          data[idx] = cr; data[idx + 1] = cg; data[idx + 2] = cb; data[idx + 3] = 255;
        }
      }
      ctx.putImageData(imageData, 0, 0);
      if (SCALE > 1) { ctx.imageSmoothingEnabled = false; ctx.drawImage(canvas, 0, 0, width, height, 0, 0, canvas.width, canvas.height); }
    };
    let io;
    if (parent && "IntersectionObserver" in window) {
      io = new IntersectionObserver((ents) => { visible = ents[0].isIntersecting; }, { threshold: 0 });
      io.observe(parent);
    }
    const onVis = () => { visible = !document.hidden; };
    document.addEventListener("visibilitychange", onVis);
    render();
    return () => {
      stopped = true; if (raf) cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
      document.removeEventListener("visibilitychange", onVis);
      if (io) io.disconnect();
    };
  }, []);
  const anoMin = window.getSetting ? window.getSetting("venda.ano_minimo", "2014") : "2014";
  const videoUrl = window.getSetting ? window.getSetting("video.consignacao_url", "") : "";
  const compraSub = window.getSetting ? window.getSetting("textos.compra_sub", "Avaliamos o seu carro com transparência e rapidez. Estando no perfil da loja, te fazemos duas propostas: de compra, com valor justo e de consignação, onde cuidamos de toda a burocracia. Sem pressão, sem enrolação.") : "Avaliamos o seu carro com transparência e rapidez. Estando no perfil da loja, te fazemos duas propostas: de compra, com valor justo e de consignação, onde cuidamos de toda a burocracia. Sem pressão, sem enrolação.";
  const embed = ytEmbed(videoUrl);
  return (
    <section className="sell-banner" id="consignacao">
      <canvas className="sell-wave" ref={waveRef} aria-hidden="true"></canvas>
      <div className="sell-stripes"></div>
      <div className="grain"></div>
      <div className="container sell-inner">
        <div className="reveal">
          <div className="eyebrow" style={{ color: "var(--hm-red-2)", marginBottom: 20 }}>Compra e Consignação</div>
          <h2>
            compra e <em>consignação</em>
          </h2>
          <p>{compraSub}</p>
          <ul className="sell-features">
            <li><span className="hl">Carro revisado</span></li>
            <li><span className="hl">Km condizente com o ano</span></li>
            <li><span className="hl">A partir de {anoMin}</span></li>
          </ul>
          <div className="sell-actions">
            <WAPicker className="btn btn-primary btn-lg" message="Olá! Quero vender meu carro" ariaLabel="Falar pelo WhatsApp">
              <Icon.Whatsapp size={18} /> Quero vender meu carro
            </WAPicker>
            {(() => {
              const fixo = window.getSetting ? window.getSetting("contato.fixo", "3730151575") : "3730151575";
              const d = String(fixo || "").replace(/[^0-9]/g, "");
              const display = d.length === 10
                ? `(${d.slice(0,2)}) ${d.slice(2,6)}-${d.slice(6)}`
                : d.length === 11 ? `(${d.slice(0,2)}) ${d.slice(2,7)}-${d.slice(7)}` : fixo;
              return (
                <a className="btn btn-ghost-light" href={`tel:+55${d}`}>
                  <Icon.Phone size={16} /> {display}
                </a>
              );
            })()}
          </div>
        </div>
        <div className="reveal reveal-delay-2 sell-media">
          {embed ? (
            <div className="sell-video">
              <iframe
                src={embed}
                title="Moisés explica a consignação"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                allowFullScreen
              />
            </div>
          ) : (
            <div className="sell-video sell-video--placeholder" aria-hidden="true">
              <div className="sell-video-empty">
                <Icon.ChevDouble size={24} />
                <span>Vídeo da consignação chega em breve</span>
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}

// ----- Final CTA -----
function FinalCTA() {
  return (
    <section className="final-cta">
      <div className="final-cta-bg"></div>
      <div className="container reveal">
        <div className="eyebrow" style={{ color: "var(--hm-red)", justifyContent: "center", display: "inline-flex", marginBottom: 24 }}>
          Vamos conversar
        </div>
        <h2>Não achou o que <em>procura?</em></h2>
        <p>Fale com a gente. Temos novidades chegando toda semana e podemos buscar o carro que você quer.</p>
        <WAPicker className="btn btn-whatsapp btn-lg" ariaLabel="Falar pelo WhatsApp">
          <Icon.Whatsapp size={20} /> Falar pelo WhatsApp
        </WAPicker>
      </div>
    </section>
  );
}

// ----- Home Page composition -----
function HomePage({ vehicles, onSelectVehicle }) {
  useReveal();

  const goToEstoque = () => {
    const el = document.getElementById("estoque");
    if (el) {
      const top = el.getBoundingClientRect().top + window.scrollY - 80;
      window.scrollTo({ top, behavior: "smooth" });
    }
  };

  return (
    <main data-screen-label="01 Homepage">
      <Hero onCTA={goToEstoque} />
      <BrandMarquee />
      <StatsStrip />
      <FeaturedVehicles vehicles={vehicles} onSelect={onSelectVehicle} />
      <TrustSection />
      <TestimonialsSection />
      <SellBanner />
      <FinalCTA />
    </main>
  );
}

window.HomePage = HomePage;
