"use client"

import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "../../lib/utils"

/**
 * Premium Aspect Ratio Component
 * 
 * Advanced component that maintains specific aspect ratios with preset support,
 * responsive behavior, animations, and enhanced styling options.
 * Perfect for images, videos, and media content in modern applications.
 */

// Preset ratios
const PRESET_RATIOS = {
  square: 1,
  video: 16 / 9,
  portrait: 3 / 4,
  landscape: 4 / 3,
  golden: 1.618,
  ultrawide: 21 / 9,
  cinema: 2.39,
  instagram: 4 / 5,
  story: 9 / 16,
  banner: 3 / 1,
} as const

type PresetRatio = keyof typeof PRESET_RATIOS

// Responsive ratio configuration
interface ResponsiveRatio {
  sm?: number | PresetRatio
  md?: number | PresetRatio
  lg?: number | PresetRatio
  xl?: number | PresetRatio
  "2xl"?: number | PresetRatio
}

const MoonUIaspectRatioVariantsPro = cva(
  "relative overflow-hidden",
  {
    variants: {
      variant: {
        default: "bg-muted/10",
        ghost: "bg-transparent",
        outline: "border border-border",
        card: "bg-card shadow-sm",
        glass: "bg-white/10 backdrop-blur-md border border-white/20",
        gradient: "bg-gradient-to-br from-primary/10 to-secondary/10",
      },
      radius: {
        none: "rounded-none",
        sm: "rounded-sm",
        md: "rounded-md",
        lg: "rounded-lg",
        xl: "rounded-xl",
        "2xl": "rounded-2xl",
        full: "rounded-full",
      },
      animate: {
        true: "transition-all duration-300 ease-in-out",
        false: "",
      },
      hover: {
        true: "hover:scale-105 hover:shadow-lg cursor-pointer",
        false: "",
      },
      loading: {
        true: "animate-pulse",
        false: "",
      },
    },
    defaultVariants: {
      variant: "default",
      radius: "md",
      animate: false,
      hover: false,
      loading: false,
    },
  }
)

interface AspectRatioProps 
  extends React.HTMLAttributes<HTMLDivElement>,
    VariantProps<typeof MoonUIaspectRatioVariantsPro> {
  /**
   * Aspect ratio (width/height). For example 16/9, 4/3, 1/1 etc.
   * @default 16/9
   */
  ratio?: number
  /**
   * Preset aspect ratio for quick usage
   */
  preset?: PresetRatio
  /**
   * Responsive aspect ratios for different breakpoints
   */
  responsive?: ResponsiveRatio
  /**
   * Enable smooth aspect ratio changes
   */
  smoothTransition?: boolean
  /**
   * Add overlay content
   */
  overlay?: React.ReactNode
  /**
   * Overlay position
   */
  overlayPosition?: "center" | "top-left" | "top-right" | "bottom-left" | "bottom-right"
  /**
   * Show loading skeleton
   */
  skeleton?: boolean
}

const MoonUIAspectRatioPro = React.forwardRef<
  HTMLDivElement,
  AspectRatioProps
>(({ 
  className, 
  variant, 
  radius, 
  animate, 
  hover, 
  loading,
  ratio = 16 / 9, 
  preset,
  responsive,
  smoothTransition = false,
  overlay,
  overlayPosition = "center",
  skeleton = false,
  style, 
  children, 
  ...props 
}, ref) => {
  const [currentRatio, setCurrentRatio] = React.useState(() => {
    if (preset) return PRESET_RATIOS[preset]
    return ratio
  })

  // Update ratio when props change
  React.useEffect(() => {
    const newRatio = preset ? PRESET_RATIOS[preset] : ratio
    if (smoothTransition) {
      setCurrentRatio(newRatio)
    } else {
      setCurrentRatio(newRatio)
    }
  }, [preset, ratio, smoothTransition])

  // Handle responsive ratios
  React.useEffect(() => {
    if (!responsive) return

    const handleResize = () => {
      const width = window.innerWidth
      let newRatio = currentRatio

      if (width >= 1536 && responsive["2xl"]) {
        newRatio = typeof responsive["2xl"] === "string" 
          ? PRESET_RATIOS[responsive["2xl"]] 
          : responsive["2xl"]
      } else if (width >= 1280 && responsive.xl) {
        newRatio = typeof responsive.xl === "string" 
          ? PRESET_RATIOS[responsive.xl] 
          : responsive.xl
      } else if (width >= 1024 && responsive.lg) {
        newRatio = typeof responsive.lg === "string" 
          ? PRESET_RATIOS[responsive.lg] 
          : responsive.lg
      } else if (width >= 768 && responsive.md) {
        newRatio = typeof responsive.md === "string" 
          ? PRESET_RATIOS[responsive.md] 
          : responsive.md
      } else if (width >= 640 && responsive.sm) {
        newRatio = typeof responsive.sm === "string" 
          ? PRESET_RATIOS[responsive.sm] 
          : responsive.sm
      }

      setCurrentRatio(newRatio)
    }

    handleResize()
    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [responsive, currentRatio])

  const overlayPositionClasses = {
    center: "items-center justify-center",
    "top-left": "items-start justify-start p-4",
    "top-right": "items-start justify-end p-4",
    "bottom-left": "items-end justify-start p-4",
    "bottom-right": "items-end justify-end p-4",
  }

  return (
    <div
      ref={ref} 
      className={cn(
        MoonUIaspectRatioVariantsPro({ variant, radius, animate: animate || smoothTransition, hover, loading: loading || skeleton }),
        className
      )}
      style={{
        position: "relative",
        paddingBottom: `${(1 / currentRatio) * 100}%`,
        ...style
      }}
      {...props}
    >
      <div className="absolute inset-0">
        {skeleton ? (
          <div className="w-full h-full bg-muted animate-pulse" />
        ) : (
          children
        )}
        {overlay && (
          <div className={cn(
            "absolute inset-0 flex",
            overlayPositionClasses[overlayPosition]
          )}>
            {overlay}
          </div>
        )}
      </div>
    </div>
  )
})
MoonUIAspectRatioPro.displayName = "AspectRatioPro"


// Internal aliases for Pro component usage
export const aspectRatioVariantsInternal = MoonUIaspectRatioVariantsPro
export const AspectRatioInternal = MoonUIAspectRatioPro

// Pro exports  
export { MoonUIaspectRatioVariantsPro, MoonUIAspectRatioPro }

// Clean exports (without MoonUI prefix for easier usage)
export { MoonUIaspectRatioVariantsPro as aspectRatioVariants, MoonUIAspectRatioPro as AspectRatio }
export type { AspectRatioProps }
