// Shared utilities
const {
  motion,
  useScroll,
  useTransform,
  useInView,
  useMotionValue,
  useSpring,
  AnimatePresence,
  animate,
} = window.Motion;

const CALENDLY_URL = "https://calendly.com/jackzwhitee/15min";

const fadeUp = (delay = 0, distance = 28) => ({
  initial: { opacity: 0, y: distance },
  whileInView: { opacity: 1, y: 0 },
  viewport: { once: true, margin: "-80px" },
  transition: { duration: 0.72, delay, ease: [0.22, 1, 0.36, 1] },
});

const fadeIn = (delay = 0) => ({
  initial: { opacity: 0 },
  whileInView: { opacity: 1 },
  viewport: { once: true, margin: "-60px" },
  transition: { duration: 0.8, delay, ease: "easeOut" },
});

// Detect touch/mobile device (hover: none means touch primary)
function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState(false);
  React.useEffect(() => {
    const mq = window.matchMedia('(hover: none), (max-width: 768px)');
    setIsMobile(mq.matches);
    const handler = (e) => setIsMobile(e.matches);
    mq.addEventListener('change', handler);
    return () => mq.removeEventListener('change', handler);
  }, []);
  return isMobile;
}

// Tilt card hook — disabled automatically on touch
function useTilt(disabled = false) {
  const ref = React.useRef(null);
  const x = useMotionValue(0);
  const y = useMotionValue(0);
  const rotateX = useSpring(useTransform(y, [-0.5, 0.5], disabled ? [0, 0] : [4, -4]), { stiffness: 200, damping: 30 });
  const rotateY = useSpring(useTransform(x, [-0.5, 0.5], disabled ? [0, 0] : [-4, 4]), { stiffness: 200, damping: 30 });

  const handleMouseMove = (e) => {
    if (disabled || !ref.current) return;
    const rect = ref.current.getBoundingClientRect();
    x.set((e.clientX - rect.left) / rect.width - 0.5);
    y.set((e.clientY - rect.top) / rect.height - 0.5);
  };
  const handleMouseLeave = () => { x.set(0); y.set(0); };

  return { ref, rotateX, rotateY, handleMouseMove, handleMouseLeave };
}

Object.assign(window, {
  motion, useScroll, useTransform, useInView, useMotionValue, useSpring,
  AnimatePresence, animate,
  CALENDLY_URL, fadeUp, fadeIn, useTilt, useIsMobile,
});
