"use client"

import { useEffect } from "react"

import useStickyPositionStore, {
  StickyElementNameEnum,
} from "@/stores/sticky-position"

import { debounce } from "@/utils/debounce"

interface UseStickyPositionProps {
  ref?: React.RefObject<HTMLElement>
  name?: StickyElementNameEnum
  group?: string
}

// Global singleton ResizeObserver to observe the body only once
let resizeObserver: ResizeObserver | null = null

/**
 * Custom hook to manage sticky positioning of elements within a page.
 * This hook registers an element as sticky, calculates its top offset based on
 * other registered sticky elements, and updates the element's position dynamically.
 *
 * @param {UseStickyPositionProps} props - The properties for configuring the hook.
 * @param {React.RefObject<HTMLElement>} [props.ref] - A reference to the HTML element that should be sticky. Is optional to allow for other components to only get the height of the sticky elements.
 * @param {StickyElementNameEnum} [props.name] - A unique name for the sticky element, used for tracking.
 * @param {string} [props.group] - An optional group identifier to make multiple elements share the same top offset. Defaults to the name if not provided.
 *
 * @returns {Object} An object containing information about the sticky elements.
 * @returns {number | null} [returns.currentHeight] - The current height of the registered sticky element, or `null` if not available.
 * @returns {Array<StickyElement>} [returns.allElements] - An array containing the heights, names, and groups of all registered sticky elements.
 */
export default function useStickyPosition({
  ref,
  name,
  group,
}: UseStickyPositionProps) {
  const {
    registerSticky,
    unregisterSticky,
    stickyElements,
    updateHeights,
    getAllElements,
  } = useStickyPositionStore()

  useEffect(() => {
    if (ref && name) {
      // Register the sticky element with the given ref, name, and group.
      // If the group is not provided, it defaults to the value of the name.
      // This registration keeps track of the sticky element and its height.
      registerSticky(ref, name, group || name)

      // Update the heights of all registered sticky elements.
      // This ensures that the height information is accurate and up-to-date.
      updateHeights()

      return () => {
        unregisterSticky(ref)
      }
    }
  }, [ref, name, group, registerSticky, unregisterSticky, updateHeights])

  useEffect(() => {
    if (ref) {
      // Find the index of the current sticky element in the array of stickyElements.
      // This helps us determine its position relative to other sticky elements.
      const index = stickyElements.findIndex((el) => el.ref === ref)

      if (index !== -1 && ref.current) {
        // Get the group name of the current sticky element.
        // This will be used to filter out other elements in the same group.
        const currentGroup = stickyElements[index].group

        // Calculate the top offset for the current element.
        // We sum the heights of all elements that appear before the current element
        // in the stickyElements array, but only if they belong to a different group.
        // This ensures that elements in the same group don't stack on top of each other.
        const topOffset = stickyElements
          .slice(0, index)
          .filter((el) => el.group !== currentGroup)
          .reduce((acc, el) => acc + el.height, 0)

        // Apply the calculated top offset to the current element's style.
        // This positions the element at the correct location within the document.
        ref.current.style.top = `${topOffset}px`
      }
    }
  }, [stickyElements, ref])

  useEffect(() => {
    if (!resizeObserver) {
      const debouncedResizeHandler = debounce(() => {
        updateHeights()
      }, 100)

      resizeObserver = new ResizeObserver(debouncedResizeHandler)
    }

    resizeObserver.observe(document.body)

    return () => {
      if (resizeObserver) {
        resizeObserver.unobserve(document.body)
      }
    }
  }, [updateHeights])

  return {
    currentHeight: ref?.current?.offsetHeight || null,
    allElements: getAllElements(),
  }
}
