import { cva, type VariantProps } from "class-variance-authority";
import { splitProps, type JSX } from "solid-js";
import { Dynamic } from "solid-js/web";
import { cn } from "../../lib/cn";

type CardElement = "article" | "aside" | "div" | "section";

export const cardVariants = cva("rounded-md border border-line bg-surface", {
  variants: {
    padding: {
      none: "",
      small: "p-4",
      medium: "p-5",
    },
    elevation: {
      flat: "",
      raised: "shadow-sm",
    },
  },
  defaultVariants: {
    padding: "none",
    elevation: "flat",
  },
});

export type CardProps = JSX.HTMLAttributes<HTMLElement> &
  VariantProps<typeof cardVariants> & {
    as?: CardElement;
  };

/**
 * Generic bordered surface.
 *
 * `as` preserves document semantics at the call site; Card only owns visual
 * framing and must not encode page or domain behavior.
 */
export function Card(props: CardProps) {
  const [local, rest] = splitProps(props, ["as", "padding", "elevation", "class", "children"]);
  return (
    <Dynamic
      component={local.as ?? "div"}
      {...rest}
      data-slot="card"
      class={cn(cardVariants({ padding: local.padding, elevation: local.elevation }), local.class)}
    >
      {local.children}
    </Dynamic>
  );
}

export type CardHeaderProps = JSX.HTMLAttributes<HTMLDivElement>;

/** Standard Card heading/action row. */
export function CardHeader(props: CardHeaderProps) {
  const [local, rest] = splitProps(props, ["class", "children"]);
  return (
    <div
      {...rest}
      data-slot="card-header"
      class={cn(
        "flex min-h-16 items-center justify-between gap-4 border-b border-line px-5 py-3 [&_h2]:text-base [&_h2]:font-semibold [&_p]:mt-0.5 [&_p]:text-xs [&_p]:text-muted",
        local.class,
      )}
    >
      {local.children}
    </div>
  );
}
