'use client'

import { forwardRef, type HTMLAttributes, type ReactNode } from 'react'
import { cn } from '@/lib/utils'

/**
 * Forge Card / Panel — implements DESIGN.md §4.Card
 *
 * Variants
 *  - surface : `bg-surface-1` (default — top-level panel on the canvas)
 *  - nested  : `bg-surface-2` (nested inside another card)
 *  - floating : `bg-surface-2` + shadow-lg (popovers / floating)
 */

export type CardVariant = 'surface' | 'nested' | 'floating'

export interface CardProps extends HTMLAttributes<HTMLDivElement> {
  variant?: CardVariant
  /** Add internal padding (default true). */
  padded?: boolean
}

const variantClasses: Record<CardVariant, string> = {
  surface: 'bg-surface-1 border border-hairline',
  nested: 'bg-surface-2 border border-hairline',
  floating: 'bg-surface-2 border border-hairline shadow-modal',
}

export const Card = forwardRef<HTMLDivElement, CardProps>(function Card(
  { variant = 'surface', padded = true, className, children, ...rest },
  ref,
) {
  return (
    <div
      ref={ref}
      className={cn(
        'rounded-panel',
        variantClasses[variant],
        padded && 'p-5',
        className,
      )}
      {...rest}
    >
      {children}
    </div>
  )
})

export interface CardHeaderProps extends Omit<HTMLAttributes<HTMLDivElement>, 'title'> {
  title?: ReactNode
  description?: ReactNode
  action?: ReactNode
}

export function CardHeader({
  title,
  description,
  action,
  className,
  children,
  ...rest
}: CardHeaderProps) {
  return (
    <div className={cn('flex items-start justify-between gap-3 mb-4', className)} {...rest}>
      <div className="min-w-0">
        {title && <h3 className="text-[15px] font-semibold text-ink leading-tight">{title}</h3>}
        {description && <p className="mt-1 text-[12px] text-ink-muted">{description}</p>}
        {children}
      </div>
      {action && <div className="shrink-0">{action}</div>}
    </div>
  )
}

export function CardSection({ className, children, ...rest }: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={cn('space-y-4', className)} {...rest}>
      {children}
    </div>
  )
}
