'use client';

// Common country dialing codes (India first). The stored value is the full
// string "<code> <digits>" (e.g. "+91 9876543210"); this component splits the
// code out for editing and re-joins on change.
export const COUNTRY_CODES: { code: string; label: string }[] = [
  { code: '+91', label: '🇮🇳 +91' },
  { code: '+1', label: '🇺🇸 +1' },
  { code: '+44', label: '🇬🇧 +44' },
  { code: '+971', label: '🇦🇪 +971' },
  { code: '+65', label: '🇸🇬 +65' },
  { code: '+61', label: '🇦🇺 +61' },
  { code: '+49', label: '🇩🇪 +49' },
  { code: '+33', label: '🇫🇷 +33' },
  { code: '+880', label: '🇧🇩 +880' },
  { code: '+92', label: '🇵🇰 +92' },
  { code: '+94', label: '🇱🇰 +94' },
  { code: '+977', label: '🇳🇵 +977' },
];

function splitPhone(value: string): { code: string; num: string } {
  const s = (value || '').trim();
  // Longest matching code first so "+971" wins over "+9".
  const match = [...COUNTRY_CODES]
    .sort((a, b) => b.code.length - a.code.length)
    .find((c) => s.startsWith(c.code));
  if (match) return { code: match.code, num: s.slice(match.code.length).replace(/\D/g, '') };
  return { code: '+91', num: s.replace(/\D/g, '') };
}

export default function PhoneInput({
  value,
  onChange,
  required = false,
  placeholder = '10-digit number',
  maxLength = 10,
  className = '',
}: {
  value: string;
  onChange: (fullValue: string) => void;
  required?: boolean;
  placeholder?: string;
  maxLength?: number;
  className?: string;
}) {
  const { code, num } = splitPhone(value);
  // Emit "<code><digits>" with NO space (the backend validator is
  // ^\+?1?\d{9,15}$ — spaces would be rejected). "" when empty so required fires.
  const emit = (c: string, n: string) => onChange(n ? `${c}${n}` : '');

  return (
    <div className={`flex ${className}`}>
      <select
        value={code}
        onChange={(e) => emit(e.target.value, num)}
        aria-label="Country code"
        className="shrink-0 bg-slate-50 dark:bg-slate-950 border border-slate-200 dark:border-slate-800 border-r-0 rounded-none px-2 py-2.5 text-xs font-semibold text-slate-700 dark:text-slate-200 focus:outline-none cursor-pointer"
      >
        {COUNTRY_CODES.map((c) => (
          <option key={c.code} value={c.code}>{c.label}</option>
        ))}
      </select>
      <input
        type="text"
        inputMode="numeric"
        required={required}
        value={num}
        onChange={(e) => emit(code, e.target.value.replace(/\D/g, '').slice(0, maxLength))}
        placeholder={placeholder}
        maxLength={maxLength}
        className="flex-1 min-w-0 bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-800 rounded-none px-3 py-2.5 text-xs focus:outline-none text-slate-800 dark:text-white"
      />
    </div>
  );
}
