import { Sections } from "@/i18n/translations";
import { useLayoutEffect, useRef } from "react";

export const linksOrder: Array<Sections> = [
  "about",
  "tickets",
  "cfp",
  "details",
  "contact",
]

export function useColorSections(parent: React.RefObject<HTMLDivElement | null>) {
  const previous = useRef<Sections>(linksOrder[0])

  useLayoutEffect(() => {
    if (parent.current === null) return;

    const options = {
      root: null,
      rootMargin: "-10px",
      threshold: 0.5, // Adjust the visibility threshold as needed
    };


    const sections = linksOrder.map(value => document.getElementById(value));
    const subs = linksOrder.reduce((acc, value) => {
      acc[value] = parent.current!.querySelector('[data-sub="' + value + '"]')!;
      return acc;
    }, {} as Record<Sections, HTMLAnchorElement>);
    console.log(subs);
    const links = linksOrder.reduce((acc, value) => {
      acc[value] = parent.current!.querySelector('[href="#' + value + '"]')!;
      return acc;
    }, {} as Record<Sections, HTMLAnchorElement>);

    console.log(links)

    // Set of currently intersecting sections by ID.
    let intersecting: Set<string> = new Set;

    const observer = new IntersectionObserver((entries) => {
      // Update intersection set based on diff.
      let startedIntersecting: Set<string> = new Set;
      let stoppedIntersecting: Set<string> = new Set;
      for (const entry of entries) {
        if (entry.isIntersecting) {
          startedIntersecting.add(entry.target.id);
        } else {
          stoppedIntersecting.add(entry.target.id);
        }
      }
      intersecting = intersecting.difference(stoppedIntersecting);
      intersecting = intersecting.union(startedIntersecting);
      console.log(intersecting);

      // Act upon intersection set to find the highest intersecting section -
      // that's our 'active' section.
      for (const id of linksOrder) {
        if (intersecting.has(id)) {
          console.log("best: " + id);
          subs[previous.current]?.classList.remove('scale-x-100');
          links[previous.current]?.classList.remove('text-primary');
          previous.current = id;

          subs[previous.current]?.classList.add('scale-x-100');
          links[previous.current]?.classList.add('text-primary');
          break;
        }
      }
    }, options);

    sections.forEach(section => {
      if (section) {
        observer.observe(section);
      }
    });

    return () => {
      observer.disconnect()
    };
  }, [parent]);

}
