/** * @file InfiniteScroll.vue * @description A Vue component that implements
infinite scrolling functionality using the Intersection Observer API. * This
component emits a 'reached-bottom' event when the user scrolls near the bottom
of the content. * It includes debouncing to prevent multiple rapid triggers and
loading state management. * * @author Matthew Raymer * @version 1.0.0 */

<template>
  <div ref="scrollContainer">
    <slot />
    <div ref="sentinel" style="height: 1px"></div>
  </div>
</template>

<script lang="ts">
import { Component, Emit, Prop, Vue } from "vue-facing-decorator";

/**
 * InfiniteScroll Component
 *
 * This component implements infinite scrolling functionality by observing when a user
 * scrolls near the bottom of the content. It uses the Intersection Observer API for
 * efficient scroll detection and includes debouncing to prevent multiple rapid triggers.
 *
 * Usage in template:
 * ```vue
 * <InfiniteScroll @reached-bottom="loadMore">
 *   <div>Content goes here</div>
 * </InfiniteScroll>
 * ```
 *
 * Props:
 * - distance: number (default: 200) - Distance in pixels from the bottom at which to trigger the event
 *
 * Events:
 * - reached-bottom: Emitted when the user scrolls near the bottom of the content
 */
@Component
export default class InfiniteScroll extends Vue {
  /** Distance in pixels from the bottom at which to trigger the reached-bottom event */
  @Prop({ default: 200 })
  readonly distance!: number;

  /** Intersection Observer instance for detecting scroll position */
  private observer!: IntersectionObserver;

  /** Flag to track initial render state */
  private isInitialRender = true;

  /** Flag to prevent multiple simultaneous loading states */
  private isLoading = false;

  /** Timeout ID for debouncing scroll events */
  private debounceTimeout: number | null = null;

  /**
   * Vue lifecycle hook that runs after component updates.
   * Initializes the Intersection Observer if not already set up.
   *
   * @internal
   * Used internally by Vue's lifecycle system
   */
  updated() {
    if (!this.observer) {
      const options = {
        root: null,
        rootMargin: `0px 0px ${this.distance}px 0px`,
        threshold: 1.0,
      };
      this.observer = new IntersectionObserver(
        this.handleIntersection,
        options,
      );
      this.observer.observe(this.$refs.sentinel as HTMLElement);
    }
  }

  /**
   * Vue lifecycle hook that runs before component unmounting.
   * Cleans up the Intersection Observer and any pending timeouts.
   *
   * @internal
   * Used internally by Vue's lifecycle system
   */
  beforeUnmount() {
    if (this.observer) {
      this.observer.disconnect();
    }
    if (this.debounceTimeout) {
      window.clearTimeout(this.debounceTimeout);
    }
  }

  /**
   * Handles intersection observer callbacks when the sentinel element becomes visible.
   * Implements debouncing to prevent multiple rapid triggers and manages loading state.
   *
   * @param entries - Array of IntersectionObserverEntry objects
   * @returns false (required by @Emit decorator)
   *
   * @internal
   * Used internally by the Intersection Observer
   * @emits reached-bottom - Emitted when the user scrolls near the bottom
   */
  @Emit("reached-bottom")
  handleIntersection(entries: IntersectionObserverEntry[]) {
    const entry = entries[0];
    if (entry.isIntersecting && !this.isLoading) {
      // Debounce the intersection event
      if (this.debounceTimeout) {
        window.clearTimeout(this.debounceTimeout);
      }

      this.debounceTimeout = window.setTimeout(() => {
        this.isLoading = true;
        this.$emit("reached-bottom", true);
        // Reset loading state after a short delay
        setTimeout(() => {
          this.isLoading = false;
        }, 1000);
      }, 300);
    }
    return false;
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>
