// src/components/auth/password-strength.tsx
"use client";

import { useTranslations } from "next-intl";
import {
  type PasswordCriterion,
  scorePassword,
} from "@/lib/auth/password-policy";
import { cn } from "@/lib/utils";

/** Fill color per score — red→amber→yellow→green (app palette). */
const SCORE_COLORS: Record<number, string> = {
  0: "bg-red-500",
  1: "bg-red-500",
  2: "bg-amber-500",
  3: "bg-yellow-500",
  4: "bg-green-500",
};

const SCORE_LABEL_KEYS = [
  "strengthWeak",
  "strengthWeak",
  "strengthFair",
  "strengthGood",
  "strengthStrong",
] as const;

const HINT_KEYS = {
  length: "pwNeedLength",
  lower: "pwNeedLower",
  upper: "pwNeedUpper",
  digit: "pwNeedDigit",
  symbol: "pwNeedSymbol",
} as const satisfies Record<PasswordCriterion, string>;

/**
 * 4-segment strength gauge + missing-criteria hints for password fields.
 * Renders nothing until the user starts typing.
 */
export function PasswordStrength({ password }: { password: string }) {
  const t = useTranslations("Auth");
  if (!password) return null;
  const { score, missing } = scorePassword(password);
  const filled = Math.max(score, 1); // even "0" shows one red segment
  return (
    <div className="flex flex-col gap-1.5" aria-live="polite">
      <div className="flex items-center gap-2">
        <div className="flex flex-1 gap-1">
          {[0, 1, 2, 3].map((i) => (
            <div
              key={i}
              className={cn(
                "h-1 flex-1 rounded-full bg-muted",
                i < filled && SCORE_COLORS[score],
              )}
            />
          ))}
        </div>
        <span className="text-muted-foreground text-xs">
          {t(SCORE_LABEL_KEYS[score])}
        </span>
      </div>
      {missing.length > 0 ? (
        <ul className="text-muted-foreground text-xs">
          {missing.map((m) => (
            <li key={m}>{t(HINT_KEYS[m])}</li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}
