// components/ui/Checkbox.tsx
// Accessible checkbox for unbundled, UNTICKED-by-default consent (Ley 29733,
// architecture.md section 6.5). Server-safe.
//
// Critical: the data-consent checkbox MUST be unticked by default and separate
// from terms and from marketing consent. This primitive defaults `defaultChecked`
// to false and never forces a checked state.

import * as React from "react";

export interface CheckboxProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, "type"> {
  /** Label content (can include links to the bases / privacy policy). */
  label: React.ReactNode;
  id?: string;
  error?: string;
}

export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
  function Checkbox({ label, id, name, error, className = "", required, ...rest }, ref) {
    const fieldId = id ?? (name ? `check-${name}` : undefined);
    const errorId = fieldId ? `${fieldId}-error` : undefined;

    return (
      <div className="flex flex-col gap-1.5">
        <div className="flex items-start gap-3">
          <input
            ref={ref}
            type="checkbox"
            id={fieldId}
            name={name}
            required={required}
            aria-invalid={error ? true : undefined}
            aria-describedby={error ? errorId : undefined}
            // Sized so the hit area meets the 44px target via the wrapping label.
            className={[
              "mt-0.5 h-6 w-6 shrink-0 rounded-sm accent-[var(--brand-primary)]",
              "focus-visible:outline focus-visible:outline-[3px]",
              "focus-visible:outline-offset-2 focus-visible:outline-steelblue",
              error ? "outline outline-1 outline-primary" : "",
              className,
            ]
              .filter(Boolean)
              .join(" ")}
            {...rest}
          />
          <label
            htmlFor={fieldId}
            className="font-body text-body-md text-ink-strong leading-snug cursor-pointer min-h-[44px] flex items-center"
          >
            {label}
            {required ? (
              <span className="text-primary" aria-hidden="true">
                {" "}
                *
              </span>
            ) : null}
          </label>
        </div>
        {error ? (
          <p
            id={errorId}
            role="alert"
            className="font-body text-caption text-primary pl-9"
          >
            {error}
          </p>
        ) : null}
      </div>
    );
  },
);
