"use client";

import { useEffect, type ReactNode } from "react";
import {
  LazyMotion,
  MotionConfig,
  domAnimation,
  m,
  useAnimationControls,
  useReducedMotion,
} from "framer-motion";

type AnimatedDashboardProps = { children: ReactNode };
type DashboardRevealProps = {
  children: ReactNode;
  className?: string;
  delay?: number;
  hover?: boolean;
};

export function AnimatedDashboard({ children }: AnimatedDashboardProps) {
  return (
    <LazyMotion features={domAnimation}>
      <MotionConfig reducedMotion="user">{children}</MotionConfig>
    </LazyMotion>
  );
}

export function DashboardReveal({
  children,
  className = "",
  delay = 0,
  hover = false,
}: DashboardRevealProps) {
  const controls = useAnimationControls();
  const reducedMotion = useReducedMotion();

  useEffect(() => {
    if (reducedMotion !== false) {
      controls.set({ opacity: 1, y: 0 });
      return;
    }
    // Keep SSR content visible; animate only once the component is hydrated.
    void controls.start({
      opacity: [0.7, 1],
      y: [12, 0],
      transition: { type: "tween", duration: 0.42, delay, ease: [0.22, 1, 0.36, 1] },
    });
    return () => controls.stop();
  }, [controls, delay, reducedMotion]);

  return (
    <m.div
      className={`dashboard-reveal ${className}`}
      initial={false}
      animate={controls}
      whileHover={hover && !reducedMotion ? { y: -3 } : undefined}
      transition={{ type: "spring", stiffness: 350, damping: 28 }}
    >
      {children}
    </m.div>
  );
}
