"use client";

import { motion } from "framer-motion";
import type { ReactNode } from "react";

type HtmlTag = "div" | "section" | "article" | "header" | "footer" | "aside";
import { useReducedMotionSafe } from "./use-reduced-motion-safe";

export interface QueueSectionProps {
  children: ReactNode;
  className?: string;
  /** HTML tag to render (default "div"). */
  as?: HtmlTag;
  /** Seconds between each direct QueueItem/StaggerGrid child's entrance. */
  stagger?: number;
  /** Seconds before the first child starts, once the section enters view. */
  delay?: number;
  /** Fraction of the section that must be visible before it triggers (0-1). */
  amount?: number;
  /** Animate only once — never replay on scroll back up. */
  once?: boolean;
}

/**
 * Orchestrates a "queue" of child `QueueItem`/`StaggerGrid` entrances: this
 * section triggers once when scrolled into view, and its `staggerChildren`/
 * `delayChildren` transition (via the shared "hidden"/"visible" variant
 * names) makes Framer Motion stagger every direct child automatically — no
 * manual index/delay math needed in either this component or its children.
 *
 * `prefers-reduced-motion` (see `useReducedMotionSafe`) skips the
 * orchestration entirely: children render immediately via a plain
 * `initial={false}` wrapper rather than a shortened version of the same
 * animation, matching this codebase's existing convention (e.g.
 * `EventStackSection`'s static fallback) of swapping to a fully static
 * branch instead of just zeroing durations.
 */
export function QueueSection({
  children,
  className,
  as = "div",
  stagger = 0.15,
  delay = 0,
  amount = 0.2,
  once = true,
}: QueueSectionProps) {
  const reduced = useReducedMotionSafe();
  const Component = motion[as];

  if (reduced) {
    return (
      <Component className={className} initial={false}>
        {children}
      </Component>
    );
  }

  return (
    <Component
      className={className}
      initial="hidden"
      whileInView="visible"
      viewport={{ once, amount }}
      variants={{
        hidden: {},
        visible: {
          transition: { staggerChildren: stagger, delayChildren: delay },
        },
      }}
    >
      {children}
    </Component>
  );
}
