import * as React from "react";
import { motion, useReducedMotion, type Variants } from "motion/react";

const easeOut = [0.22, 1, 0.36, 1] as const;

/** Fade + rise on mount. Respects prefers-reduced-motion. */
export function FadeIn({
  children,
  delay = 0,
  y = 8,
  className,
  immediate = false,
}: {
  children: React.ReactNode;
  delay?: number;
  y?: number;
  className?: string;
  /** Animate on mount instead of waiting to scroll into view. Dashboards. */
  immediate?: boolean;
}) {
  const reduce = useReducedMotion();
  const visible = { opacity: 1, y: 0 };
  return (
    <motion.div
      className={className}
      initial={reduce ? false : { opacity: 0, y }}
      {...(immediate
        ? { animate: visible }
        : { whileInView: visible, viewport: { once: true, margin: "-10% 0px" as const } })}
      transition={reduce ? { duration: 0 } : { duration: 0.4, ease: easeOut, delay }}
    >
      {children}
    </motion.div>
  );
}

/** Stagger container — pair with <StaggerItem>. */
export const staggerContainer: Variants = {
  hidden: {},
  show: { transition: { staggerChildren: 0.06 } },
};
export const staggerItem: Variants = {
  hidden: { opacity: 0, y: 10 },
  show: { opacity: 1, y: 0, transition: { duration: 0.4, ease: easeOut } },
};

export function Stagger({ children, className }: { children: React.ReactNode; className?: string }) {
  const reduce = useReducedMotion();
  return (
    <motion.div
      className={className}
      variants={reduce ? undefined : staggerContainer}
      initial={reduce ? false : "hidden"}
      whileInView="show"
      viewport={{ once: true, margin: "-10% 0px" }}
    >
      {children}
    </motion.div>
  );
}
export function StaggerItem({ children, className }: { children: React.ReactNode; className?: string }) {
  const reduce = useReducedMotion();
  return <motion.div className={className} variants={reduce ? undefined : staggerItem}>{children}</motion.div>;
}

export { motion };
