/* =========================================================
   07b · Planta — Figma 713:2 / 712:2 (desktop) · 723:125 (mobile)
   Nota 731:287: SVG ilustrativo; se config.js → plantas.terreo / .superior
   tiver uma imagem, ela substitui o SVG automaticamente.
   ========================================================= */
/* Ambientes de cada pavimento */
const PLANTA_ANDARES = [
  { num: "1", nome: "Pavimento 1", ambientes: ["Sala", "Cozinha", "Quintal", "Lavanderia"] },
  { num: "2", nome: "Pavimento 2", ambientes: ["2 quartos", "Banheiro", "Suíte"] },
  { num: "3", nome: "Pavimento 3", ambientes: ["Área social"] },
];

const PLANTA_PAVIMENTOS = [
  {
    id: "vista-1",
    nome: "Pavimento 3",
    svg: "assets/planta/planta-1.png",
    alt: "Vista ilustrativa da planta da casa — etapa 1",
  },
  {
    id: "vista-2",
    nome: "Pavimento 2",
    svg: "assets/planta/planta-2.png",
    alt: "Vista ilustrativa da planta da casa — etapa 2",
  },
  {
    id: "vista-3",
    nome: "Pavimento 1",
    svg: "assets/planta/planta-3.png",
    alt: "Vista ilustrativa da planta da casa — etapa 3",
  },
];

function PlantaCard({ pav }) {
  const oficial = CFG.plantas && CFG.plantas[pav.id];

  return (
    <figure className={`planta__card planta__card--${pav.id}`}>
      <img
        className={`planta__img${oficial ? " planta__img--oficial" : ""}`}
        src={oficial || pav.svg}
        alt={pav.alt}
        width="360"
        height="680"
        loading="lazy"
        decoding="async"
      />
      <figcaption className="planta__card-foot">
        <span className="planta__card-nome">{pav.nome}</span>
      </figcaption>
    </figure>
  );
}

function Planta() {
  const plantaRef = useRef(null);
  const plantasRef = useRef(null);

  /* Troca das plantas na rolagem: só acima de 960px. Liga/desliga quando a
     largura muda (ex.: tablet girado), para as plantas nunca ficarem invisíveis. */
  useEffect(() => {
    const mql = window.matchMedia("(max-width: 960px)");
    let desligar = null;
    const aplicar = () => {
      if (desligar) { desligar(); desligar = null; }
      if (!mql.matches) desligar = ligarTrocaNaRolagem();
    };
    aplicar();
    mql.addEventListener("change", aplicar);
    return () => {
      mql.removeEventListener("change", aplicar);
      if (desligar) desligar();
    };
  }, []);

  function ligarTrocaNaRolagem() {
    let frame = null;
    let etapaAtual = -1;
    let timerTroca = null;
    const atualizar = () => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() => {
        const secao = plantaRef.current;
        if (!secao) return;

        const cards = Array.from(secao.querySelectorAll(".planta__card"));
        if (!cards.length) return;

        const rect = secao.getBoundingClientRect();
        /* O bloco fica fixo (sticky) logo abaixo do header: o percurso começa quando o topo da seção chega ao header */
        const headerH = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--header-h')) || 0;
        const percurso = Math.max(1, secao.offsetHeight - window.innerHeight + headerH);
        const progresso = Math.max(0, Math.min(1, (headerH - rect.top) / percurso));
        const etapa = Math.min(cards.length - 1, Math.round(progresso * (cards.length - 1)));
        if (etapa === etapaAtual) return;

        const anterior = etapaAtual;
        etapaAtual = etapa;
        clearTimeout(timerTroca);

        cards.forEach((card, index) => {
          const ativo = index === etapa;
          card.style.pointerEvents = ativo ? "auto" : "none";
          card.style.zIndex = ativo ? "10" : "1";

          if (ativo) {
            card.style.opacity = "1";
            card.style.transform = "translateY(-50%) scale(1)";
            card.classList.remove("is-saindo", "is-entrando");
            void card.offsetWidth;
            card.classList.add("is-entrando");
            timerTroca = setTimeout(() => card.classList.remove("is-entrando"), 500);
          } else if (index === anterior) {
            card.classList.remove("is-entrando");
            card.classList.add("is-saindo");
            timerTroca = setTimeout(() => {
              card.classList.remove("is-saindo");
              card.style.opacity = "0";
            }, 500);
          } else {
            card.classList.remove("is-entrando", "is-saindo");
            card.style.opacity = "0";
          }
        });
      });
    };

    atualizar();
    window.addEventListener("scroll", atualizar, { passive: true });
    window.addEventListener("resize", atualizar);
    return () => {
      cancelAnimationFrame(frame);
      clearTimeout(timerTroca);
      window.removeEventListener("scroll", atualizar);
      window.removeEventListener("resize", atualizar);
      /* Limpa os estilos da troca (no layout empilhado as plantas aparecem todas) */
      const secao = plantaRef.current;
      if (secao) secao.querySelectorAll(".planta__card").forEach((card) => {
        card.style.opacity = "";
        card.style.transform = "";
        card.style.zIndex = "";
        card.style.pointerEvents = "";
        card.classList.remove("is-entrando", "is-saindo");
      });
    };
  }

  return (
    <section ref={plantaRef} id="planta" className="planta" aria-labelledby="planta-titulo">
      <div className="container planta__inner">
        <div className="planta__texto">
          <h2 id="planta-titulo" className="planta__title">A planta</h2>
          <p className="planta__lead">
            Três pavimentos: o dia a dia no primeiro, os quartos no segundo e a área social no terceiro.
          </p>
          <ol className="planta__andares">
            {PLANTA_ANDARES.map((andar) => (
              <li key={andar.num} className="planta__andar">
                <span className="planta__andar-num" aria-hidden="true">{andar.num}</span>
                <span className="planta__andar-corpo">
                  <span className="planta__andar-nome">{andar.nome}</span>
                  <span className="planta__andar-ambientes">{andar.ambientes.join(" · ")}</span>
                </span>
              </li>
            ))}
          </ol>
        </div>
 
        <div className="planta__plantas">
          {PLANTA_PAVIMENTOS.map((pav) => <PlantaCard key={pav.id} pav={pav} />)}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Planta });
