'use client';

import { useTranslations } from 'next-intl';
import { cn } from '@/lib/utils';

export type PasswordStrength = 'weak' | 'medium' | 'strong';

export function getPasswordStrength(password: string): PasswordStrength {
  if (!password || password.length < 8) return 'weak';
  let score = 0;
  if (password.length >= 12) score++;
  if (/[A-Z]/.test(password)) score++;
  if (/[0-9]/.test(password)) score++;
  if (/[^A-Za-z0-9]/.test(password)) score++;
  if (score >= 3) return 'strong';
  if (score >= 1) return 'medium';
  return 'weak';
}

interface PasswordStrengthMeterProps {
  password: string;
}

export function PasswordStrengthMeter({ password }: PasswordStrengthMeterProps) {
  const t = useTranslations('auth.register.password_strength');
  if (!password) return null;

  const strength = getPasswordStrength(password);

  const segments = [
    { active: true, color: strength === 'weak' ? 'bg-danger' : strength === 'medium' ? 'bg-warning' : 'bg-success' },
    { active: strength !== 'weak', color: strength === 'medium' ? 'bg-warning' : 'bg-success' },
    { active: strength === 'strong', color: 'bg-success' },
  ];

  const labelColor = strength === 'weak' ? 'text-danger' : strength === 'medium' ? 'text-warning' : 'text-success';

  const requirements = [
    { key: 'req_length', met: password.length >= 12 },
    { key: 'req_upper', met: /[A-Z]/.test(password) },
    { key: 'req_number', met: /[0-9]/.test(password) },
    { key: 'req_special', met: /[^A-Za-z0-9]/.test(password) },
  ] as const;

  const allMet = requirements.every((r) => r.met);

  return (
    <div className="mt-1.5" aria-live="polite" aria-atomic="true">
      <div className="flex gap-1 mb-1" role="progressbar" aria-label={t('label')} aria-valuenow={strength === 'weak' ? 1 : strength === 'medium' ? 2 : 3} aria-valuemin={0} aria-valuemax={3}>
        {segments.map((seg, i) => (
          <div
            key={i}
            className={cn(
              'h-1 flex-1 rounded-full transition-colors',
              seg.active ? seg.color : 'bg-neutral-200',
            )}
          />
        ))}
      </div>
      <p className={cn('text-xs font-medium', labelColor)}>
        {t(strength)}
      </p>
      {!allMet && (
        <ul className="mt-1.5 space-y-0.5">
          {requirements.map((req) => (
            <li key={req.key} className={cn('flex items-center gap-1.5 text-xs', req.met ? 'text-success' : 'text-neutral-400')}>
              <span aria-hidden className="text-[10px]">{req.met ? '✓' : '○'}</span>
              {t(req.key)}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
