import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
import { cv, type VariantProps } from '../../lib/cv.js'

const card = cv(
  'rounded-[var(--radius)] border border-[var(--border)] bg-[var(--card)] text-[var(--card-foreground)]',
  {
    variants: {
      padding: {
        none: 'p-0',
        sm: 'p-4',
        md: 'p-6',
        lg: 'p-8',
      },
      elevation: {
        flat: 'shadow-none',
        sm: 'shadow-sm',
        md: 'shadow-md',
        lg: 'shadow-lg',
      },
    },
    defaultVariants: { padding: 'md', elevation: 'sm' },
  },
)

export type CardVariants = VariantProps<typeof card>

const INTERACTIVE_CLASS = 'transition-shadow hover:shadow-md focus-within:shadow-md'

export interface CardProps extends HTMLAttributes<HTMLDivElement>, CardVariants {
  /** Apply hover/focus elevation transitions (e.g. for clickable cards). */
  interactive?: boolean
  children?: ReactNode
}

export const Card = forwardRef<HTMLDivElement, CardProps>(function Card(
  { padding, elevation, interactive, className, children, ...rest },
  ref,
) {
  const extras = [interactive ? INTERACTIVE_CLASS : '', className].filter(Boolean).join(' ')
  return (
    <div ref={ref} className={card({ padding, elevation, class: extras })} {...rest}>
      {children}
    </div>
  )
})

/**
 * Header slot — sits at the top of a card. Pair with CardTitle / CardDescription.
 */
export function CardHeader({ className = '', children, ...rest }: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={`flex flex-col space-y-1.5 ${className}`} {...rest}>
      {children}
    </div>
  )
}

export function CardTitle({
  className = '',
  children,
  ...rest
}: HTMLAttributes<HTMLHeadingElement>) {
  return (
    <h3
      className={`text-lg leading-tight font-medium tracking-tight text-[var(--card-foreground)] ${className}`}
      {...rest}
    >
      {children}
    </h3>
  )
}

export function CardDescription({
  className = '',
  children,
  ...rest
}: HTMLAttributes<HTMLParagraphElement>) {
  return (
    <p className={`text-sm text-[var(--muted-foreground)] ${className}`} {...rest}>
      {children}
    </p>
  )
}

export function CardContent({ className = '', children, ...rest }: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={className} {...rest}>
      {children}
    </div>
  )
}

export function CardFooter({ className = '', children, ...rest }: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={`flex items-center justify-end gap-2 pt-4 ${className}`} {...rest}>
      {children}
    </div>
  )
}

export { card as cardVariants }
