<script lang="ts">
  import type { Snippet } from 'svelte';
  import { onMount, onDestroy } from 'svelte';

  let {
    top = 0,
    bottom = 0,
    left = 0,
    right = 0,
    steps = 100,
    threshold = 0.01,
    once = false,
    children
  }: {
    top?: number;
    bottom?: number;
    left?: number;
    right?: number;
    steps?: number;
    threshold?: number;
    once?: boolean;
    children?: Snippet<[{ visible: boolean; percent: number }]>;
  } = $props();
  let element: Element;
  let percent: number = $state(0);
  let visible = $state(false);
  let observer: IntersectionObserver;

  const intersectPercent = (
    entries: IntersectionObserverEntry[],
    observer: IntersectionObserver
  ) => {
    for (let entry of entries)
      if (entry.target === element) {
        percent = Math.round(entry.intersectionRatio * 100);
        visible = entry.intersectionRatio >= threshold;

        if (visible && once) observer.unobserve(element);

        break;
      }
  };

  onMount(() => {
    if ('IntersectionObserver' in window) {
      let options = {
        rootMargin: `${top}px ${right}px ${bottom}px ${left}px`,
        threshold: Array.from({ length: steps }, (_, i) => i / (steps - 1))
      };

      observer = new IntersectionObserver(intersectPercent, options);
      observer.observe(element);
    }
  });

  onDestroy(() => observer?.unobserve(element));
</script>

<div bind:this={element}>
  {@render children?.({ visible, percent })}
</div>
