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

export function SegmentedControl(props: JSX.HTMLAttributes<HTMLDivElement>) {
  const [local, rest] = splitProps(props, ["class", "children"]);
  return (
    <div
      {...rest}
      data-slot="segmented-control"
      class={cn("inline-flex rounded-md border border-line bg-canvas p-1", local.class)}
    >
      {local.children}
    </div>
  );
}

export const segmentVariants = cva(
  "min-h-8 rounded-sm px-3 py-1 text-xs font-semibold text-muted transition-colors",
  {
    variants: {
      active: {
        true: "bg-white text-ink shadow-sm",
        false: "hover:text-ink",
      },
    },
    defaultVariants: {
      active: false,
    },
  },
);

export type SegmentProps = JSX.ButtonHTMLAttributes<HTMLButtonElement> &
  VariantProps<typeof segmentVariants>;

/** One mutually exclusive option inside a SegmentedControl. */
export function Segment(props: SegmentProps) {
  const [local, rest] = splitProps(props, ["active", "class", "children", "type"]);
  return (
    <button
      {...rest}
      data-slot="segment"
      type={local.type ?? "button"}
      aria-pressed={local.active === true}
      class={cn(segmentVariants({ active: local.active }), local.class)}
    >
      {local.children}
    </button>
  );
}
