"use client";
import { motion, stagger, useInView } from "motion/react";
import { createContext, type FC, useRef } from "react";
import { cn } from "@/lib/utils";
import type { SectionProps } from "./section.types";

export const InViewContext = createContext(false);

const Section: FC<SectionProps> = ({
	children,
	name,
	extraStyles,
	maxWidth = true,
	extraClassNames = "",
	threshold = 0,
	height = "fit-content",
	transition = { delayChildren: stagger(0.1) },
	noPadding = false,
	variants = {
		container: {
			enter: {},
			from: {},
			exit: {},
		},
	},
}) => {
	const ref = useRef<HTMLElement>(null);
	const inView = useInView(ref, { once: true, amount: threshold });

	return (
		<section
			{...(name ? { id: name } : {})}
			ref={ref}
			style={{
				height: height,
				...extraStyles,
			}}
			className={cn(
				"relative w-full",
				noPadding ? "p-0" : "p-main",
				maxWidth ? "max-w-max-section m-auto" : "",
				extraClassNames,
			)}
		>
			<InViewContext.Provider value={inView}>
				<motion.div
					className="h-full"
					transition={transition}
					initial="from"
					animate={inView ? "enter" : "from"}
					exit="exit"
					variants={variants.container}
				>
					{children}
				</motion.div>
			</InViewContext.Provider>
		</section>
	);
};

export default Section;
