"use client";

import type { ReactNode } from "react";

/**
 * Props a `Field` hands to whatever control it wraps.
 *
 * The whole point of the render-prop shape is that the caller cannot forget
 * one of these: `aria-describedby` has to name *both* the hint and the error
 * when both are present, and getting that wiring right by hand at every call
 * site is exactly how forms end up failing WCAG 3.3.1 in one place out of ten.
 */
export interface FieldControlProps {
  id: string;
  "aria-invalid": true | undefined;
  "aria-describedby": string | undefined;
  "aria-required": true | undefined;
}

export interface FieldProps {
  /** Base id — the control gets this, hint and error derive from it. */
  id: string;
  label: string;
  required?: boolean;
  hint?: ReactNode;
  error?: string;
  /** Rendered under the control, above the error (e.g. a "no last name" toggle). */
  footer?: ReactNode;
  className?: string;
  children: (props: FieldControlProps) => ReactNode;
}

export function fieldControlProps(args: {
  id: string;
  required?: boolean;
  hasHint?: boolean;
  error?: string;
}): FieldControlProps {
  const describedBy = [
    args.hasHint ? `${args.id}-hint` : null,
    args.error ? `${args.id}-error` : null,
  ]
    .filter(Boolean)
    .join(" ");

  return {
    id: args.id,
    "aria-invalid": args.error ? true : undefined,
    "aria-describedby": describedBy || undefined,
    "aria-required": args.required ? true : undefined,
  };
}

/** The small triangle used on every inline error, so they read as one family. */
export function FieldErrorIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path
        d="M8 1.75 15 14H1L8 1.75Z"
        stroke="currentColor"
        strokeWidth="1.4"
        strokeLinejoin="round"
      />
      <path d="M8 6.4v3.1" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
      <circle cx="8" cy="11.6" r="0.85" fill="currentColor" />
    </svg>
  );
}

export default function Field({
  id,
  label,
  required,
  hint,
  error,
  footer,
  className,
  children,
}: FieldProps) {
  const controlProps = fieldControlProps({
    id,
    required,
    hasHint: !!hint,
    error,
  });

  return (
    <div className={`lf-field ${className || ""}`}>
      <label className="lf-label" htmlFor={id}>
        {label}
        {required ? (
          <span className="lf-required" aria-hidden="true">
            *
          </span>
        ) : null}
      </label>

      {children(controlProps)}

      {footer}

      {hint ? (
        <p className="lf-hint" id={`${id}-hint`}>
          {hint}
        </p>
      ) : null}

      {error ? (
        <p className="lf-error" id={`${id}-error`}>
          <FieldErrorIcon />
          <span>{error}</span>
        </p>
      ) : null}
    </div>
  );
}
