import { clsx, type ClassValue } from "clsx";
import { extendTailwindMerge } from "tailwind-merge";

/**
 * Sprint 8 fix — plain `twMerge` doesn't know this project overrides (not extends) the
 * default fontSize scale in tailwind.config.ts. `text-h1`, `text-body-sm`, etc. don't match
 * twMerge's built-in "font-size" validators (t-shirt sizes / arbitrary values), so they fell
 * through and got bucketed under the generic "text-color" group instead — meaning
 * `cn("text-primary-contrast", "text-body-sm")` looked like two conflicting text-color
 * utilities and silently dropped the first one. This is exactly why
 * `buttonVariants({ variant: "primary", size: "sm" })` rendered ink-colored (not
 * primary-contrast) text on a primary-bronze background: an actual WCAG contrast failure
 * (3.44:1 against the 4.5:1 required) caught by a Lighthouse accessibility audit, invisible
 * in code review. Registering the custom scale under "font-size" fixes every call site at once.
 */
const twMerge = extendTailwindMerge({
  extend: {
    classGroups: {
      "font-size": [
        {
          text: [
            "display-xl",
            "display-lg",
            "display-md",
            "h1",
            "h2",
            "h3",
            "h4",
            "body-lg",
            "body-md",
            "body-sm",
            "caption",
            "label",
          ],
        },
      ],
    },
  },
});

/** Merge Tailwind class lists safely, resolving conflicting utilities. */
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

/** Formats a date as an absolute, unambiguous string — used anywhere a claim carries a date (Sprint 1 §12 trust standard). */
export function formatDocumentDate(date: Date | string): string {
  const d = typeof date === "string" ? new Date(date) : date;
  return new Intl.DateTimeFormat("en-GB", {
    day: "2-digit",
    month: "short",
    year: "numeric",
  }).format(d);
}
