import { type HTMLAttributes, type ReactNode } from 'react';
import styles from './card.module.css';

interface CardProps extends HTMLAttributes<HTMLDivElement> {
  readonly interactive?: boolean;
  readonly children: ReactNode;
}

export function Card({
  interactive = false,
  className,
  children,
  onClick,
  ...rest
}: CardProps) {
  const classNames = [
    styles.card,
    interactive ? styles.interactive : undefined,
    className,
  ]
    .filter(Boolean)
    .join(' ');

  const handleKeyDown = interactive && onClick
    ? (event: React.KeyboardEvent<HTMLDivElement>) => {
        if (event.key === 'Enter' || event.key === ' ') {
          event.preventDefault();
          onClick(event as unknown as React.MouseEvent<HTMLDivElement>);
        }
      }
    : undefined;

  return (
    <div
      className={classNames}
      onClick={onClick}
      onKeyDown={handleKeyDown}
      tabIndex={interactive && onClick ? 0 : undefined}
      role={interactive && onClick ? 'button' : undefined}
      {...rest}
    >
      {children}
    </div>
  );
}

export function CardHeader({
  className,
  children,
  ...rest
}: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={[styles.header, className].filter(Boolean).join(' ')} {...rest}>
      {children}
    </div>
  );
}

export function CardBody({
  className,
  children,
  ...rest
}: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={[styles.body, className].filter(Boolean).join(' ')} {...rest}>
      {children}
    </div>
  );
}

export function CardFooter({
  className,
  children,
  ...rest
}: HTMLAttributes<HTMLDivElement>) {
  return (
    <div className={[styles.footer, className].filter(Boolean).join(' ')} {...rest}>
      {children}
    </div>
  );
}
