"use client";

// `Field` groups a label and its control with `role="group"`. The suggested
// tags (`fieldset`, `details`, `hgroup`…) all carry extra semantics or default
// chrome that would leak into every form.
// oxlint-disable jsx-a11y/prefer-tag-over-role

import { cva, type VariantProps } from "class-variance-authority";

import { cn } from "@/lib/utils";
import { Label } from "@/components/ui/label";

/**
 * Trimmed shadcn `field` primitive. The generated file shipped ten
 * sub-components; the site has exactly one form (`footer/NewsletterForm`) and it
 * consumes two of them, so the other eight were dead code that `knip` reported
 * and that nothing here can grow into without being written on purpose. Re-add
 * a sub-component from the registry (`bunx --bun shadcn@latest add field`) the
 * day a form actually needs it, rather than keeping an unused surface alive.
 *
 * The `responsive` orientation went with them: it keyed off the
 * `@container/field-group` that only `FieldGroup` declared, so it could no
 * longer resolve. `vertical` and `horizontal` are kept verbatim.
 */
const fieldVariants = cva("group/field flex w-full gap-2 data-[invalid=true]:text-destructive", {
  variants: {
    orientation: {
      vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
      horizontal:
        "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
    },
  },
  defaultVariants: {
    orientation: "vertical",
  },
});

function Field({
  className,
  orientation = "vertical",
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
  return (
    <div
      role="group"
      data-slot="field"
      data-orientation={orientation}
      className={cn(fieldVariants({ orientation }), className)}
      {...props}
    />
  );
}

function FieldLabel({ className, ...props }: React.ComponentProps<typeof Label>) {
  return (
    <Label
      data-slot="field-label"
      className={cn(
        "group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50 has-data-checked:border-primary/30 has-data-checked:bg-primary/5 has-[>[data-slot=field]]:rounded-lg has-[>[data-slot=field]]:border has-[>[data-slot=field]]:not-has-[:disabled,[data-disabled]]:hover:bg-muted/50 has-[>[data-slot=field]]:has-[:focus-visible]:border-ring has-[>[data-slot=field]]:has-[:focus-visible]:ring-3 has-[>[data-slot=field]]:has-[:focus-visible]:ring-ring/50 *:data-[slot=field]:p-2.5 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
        "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
        className,
      )}
      {...props}
    />
  );
}

export { Field, FieldLabel };
