import React, { useEffect, useState } from 'react';
import { motion, useScroll, useSpring } from 'framer-motion';

export interface ProgressBarProps {
  /** Color of the progress bar */
  color?: string;
  /** Height of the progress bar in pixels */
  height?: number;
  /** Position of the progress bar */
  position?: 'top' | 'bottom';
  /** Show progress bar (default: true) */
  show?: boolean;
  /** Additional CSS classes */
  className?: string;
}

/**
 * ProgressBar - Shows page scroll progress
 *
 * Features:
 * - Smooth animation with spring physics
 * - Customizable color and height
 * - Can be positioned at top or bottom
 * - Automatically hides when at top of page
 * - Zero-cost when not visible
 *
 * @example
 * <ProgressBar color="var(--color-primary)" height={4} position="top" />
 */
export const ProgressBar: React.FC<ProgressBarProps> = ({
  color = 'var(--color-primary)',
  height = 4,
  position = 'top',
  show = true,
  className = '',
}) => {
  const { scrollYProgress } = useScroll();
  const scaleX = useSpring(scrollYProgress, {
    stiffness: 100,
    damping: 30,
    restDelta: 0.001,
  });

  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    const unsubscribe = scrollYProgress.on('change', (latest) => {
      // Show progress bar when scrolled past 100px
      setIsVisible(latest > 0.05);
    });

    return () => unsubscribe();
  }, [scrollYProgress]);

  if (!show || !isVisible) {
    return null;
  }

  return (
    <motion.div
      className={`fixed ${position === 'top' ? 'top-0' : 'bottom-0'} left-0 right-0 z-50 ${className}`}
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      style={{
        height: `${height}px`,
        transformOrigin: '0%',
      }}
    >
      <motion.div
        style={{
          scaleX,
          height: '100%',
          background: color,
          transformOrigin: '0%',
        }}
      />
    </motion.div>
  );
};

export default ProgressBar;
