"use client";

import type { ReactNode } from "react";
import { FormLabel, FieldError } from "@/components/ui/label";
import { useT } from "@/i18n";
import type { Dictionary } from "@/i18n/dictionaries/en";

/**
 * A labelled field: label (with optional required marker), the control, an
 * optional hint, and the error message from RHF or the server. Zod messages that
 * are `errors.*` keys are translated, so schemas stay locale agnostic.
 */
export function FormField({
  label,
  htmlFor,
  required = false,
  hint,
  error,
  children,
}: {
  label: ReactNode;
  htmlFor?: string;
  required?: boolean;
  hint?: ReactNode;
  error?: ReactNode;
  children: ReactNode;
}) {
  const t = useT();

  const message =
    typeof error === "string" && error.startsWith("errors.")
      ? t(error as keyof Dictionary)
      : error;

  return (
    <div>
      <FormLabel htmlFor={htmlFor} required={required}>
        {label}
      </FormLabel>
      {children}
      {hint && !message ? (
        <p className="mt-1.5 text-xs text-muted-foreground">{hint}</p>
      ) : null}
      <FieldError>{message}</FieldError>
    </div>
  );
}