"use client";

import React, { createContext, useContext, useEffect, useState } from "react";
import { useReducedMotion as framerUseReducedMotion } from "framer-motion";

interface ReducedMotionContextType {
  prefersReducedMotion: boolean;
}

const ReducedMotionContext = createContext<ReducedMotionContextType | undefined>(undefined);

export const ReducedMotionProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const prefersReducedMotionFramer = framerUseReducedMotion();
  const [prefersReducedMotion, setPrefersReducedMotion] = useState<boolean>(false);

  useEffect(() => {
    // 🧠 sync once client mounts (safe for SSR)
    if (typeof prefersReducedMotionFramer === "boolean") {
      setPrefersReducedMotion(prefersReducedMotionFramer);
      return;
    }

    // Fallback: detect manually if needed
    if (typeof window !== "undefined" && "matchMedia" in window) {
      const query = window.matchMedia("(prefers-reduced-motion: reduce)");
      setPrefersReducedMotion(query.matches);
      const listener = (e: MediaQueryListEvent) => setPrefersReducedMotion(e.matches);
      query.addEventListener("change", listener);
      return () => query.removeEventListener("change", listener);
    }
  }, [prefersReducedMotionFramer]);

  return (
    <ReducedMotionContext.Provider value={{ prefersReducedMotion }}>
      {children}
    </ReducedMotionContext.Provider>
  );
};

export const useReducedMotionPreference = () => {
  const context = useContext(ReducedMotionContext);
  if (context === undefined) {
    throw new Error("useReducedMotionPreference must be used within a ReducedMotionProvider");
  }
  return context.prefersReducedMotion;
};
