// Wasabil — Palette switch (estilo Mercury)
// Detecta cuándo una sección con [data-palette="light"] entra al viewport
// y cambia las CSS variables del documento a una paleta clara, con transición
// suave. Cuando sale hacia arriba vuelve a oscuro.

const { useEffect: useEffectPS } = React;

function PaletteSwitch() {
  useEffectPS(() => {
    if (typeof window === "undefined") return;

    const root = document.documentElement;
    // Habilitar transición suave en las CSS variables principales
    root.style.transition = "background-color 600ms ease, color 600ms ease";
    document.body.style.transition = "background-color 600ms ease, color 600ms ease";

    // Las paletas se aplican vía dataset attribute en <html>.
    // En styles-v2.css definimos la oscura por defecto, y la clara con
    // selector [data-palette="light"].
    const setPalette = (mode) => {
      if (root.dataset.palette === mode) return;
      root.dataset.palette = mode;
    };

    setPalette("dark"); // estado inicial

    // Buscar TODOS los targets con data-palette-trigger
    const targets = document.querySelectorAll("[data-palette-trigger]");
    if (targets.length === 0) return;

    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        const targetMode = entry.target.dataset.paletteTrigger || "light";
        if (entry.isIntersecting) {
          setPalette(targetMode);
        } else {
          // Si salimos del viewport hacia arriba (rect.top > 0 después de salir),
          // volvemos al modo previo (oscuro).
          // Si salimos por abajo, también es porque seguimos avanzando — mantenemos.
          // Para simplificar: si NO está intersecting Y rect.bottom < 0 (estamos por arriba)
          // → volver a dark. Si rect.top > viewport (lejos abajo) → mantener.
          const rect = entry.target.getBoundingClientRect();
          if (rect.bottom < 0) {
            // Pasamos hacia arriba la sección clara — volver a oscuro
            setPalette("dark");
          } else if (rect.top > window.innerHeight) {
            // Aún no llegamos a la sección clara — oscuro
            setPalette("dark");
          }
        }
      });
    }, {
      threshold: 0,
      // El cambio sucede cuando la sección está al ~25% dentro del viewport
      rootMargin: "-25% 0px -25% 0px",
    });

    targets.forEach((t) => io.observe(t));

    return () => io.disconnect();
  }, []);

  return null;
}

Object.assign(window, { PaletteSwitch });
