import * as React from "react";
import { cn } from "@/lib/utils";

const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn(
        "surface rounded-xl text-card-foreground",
        className
      )}
      {...props}
    />
  )
);
Card.displayName = "Card";

const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div ref={ref} className={cn("flex flex-col space-y-1 p-6", className)} {...props} />
  )
);
CardHeader.displayName = "CardHeader";

type CardTitleProps<E extends React.ElementType = "div"> = Omit<
  React.ComponentPropsWithoutRef<E>,
  "as"
> & {
  as?: E;
};

type CardTitleComponent = <E extends React.ElementType = "div">(
  props: CardTitleProps<E> & { ref?: React.ForwardedRef<React.ElementRef<E>> }
) => React.ReactElement | null;

const CardTitle = React.forwardRef<HTMLDivElement, CardTitleProps<"div">>(
  function CardTitleImpl(
    { as, className, ...props }: CardTitleProps<"div">,
    ref: React.ForwardedRef<HTMLDivElement>
  ) {
    const Component = (as ?? "div") as React.ElementType;
    return (
      <Component
        ref={ref as React.Ref<HTMLDivElement>}
        className={cn("text-base font-semibold leading-none tracking-tight", className)}
        {...props}
      />
    );
  }
) as unknown as CardTitleComponent;
(CardTitle as unknown as { displayName: string }).displayName = "CardTitle";

const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn("text-sm text-muted-foreground", className)}
      {...props}
    />
  )
);
CardDescription.displayName = "CardDescription";

const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
  )
);
CardContent.displayName = "CardContent";

const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn("flex items-center p-6 pt-0", className)}
      {...props}
    />
  )
);
CardFooter.displayName = "CardFooter";

export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter };
