import { toLatinDigits } from '@/lib/i18n/persianCalendar';

/** Force `YYYY-MM-DD` shape while typing (Latin digits). */
export function maskGregorianDateTyping(raw: string): string {
  const digits = toLatinDigits(raw).replace(/\D/g, '').slice(0, 8);
  const segments: string[] = [];
  if (digits.length > 0) segments.push(digits.slice(0, Math.min(4, digits.length)));
  if (digits.length > 4) segments.push(digits.slice(4, Math.min(6, digits.length)));
  if (digits.length > 6) segments.push(digits.slice(6, 8));
  return segments.join('-');
}

/** Parse typed Gregorian `YYYY-MM-DD` (slashes OK) → `YYYY-MM-DD` or null. */
export function parseGregorianDateInputText(raw: string): string | null {
  const normalized = toLatinDigits(raw.trim()).replace(/\//g, '-');
  const match = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(normalized);
  if (!match) return null;

  const year = Number(match[1]);
  const month = Number(match[2]);
  const day = Number(match[3]);
  if (month < 1 || month > 12 || day < 1) return null;

  const date = new Date(year, month - 1, day, 0, 0, 0, 0);
  if (
    date.getFullYear() !== year ||
    date.getMonth() !== month - 1 ||
    date.getDate() !== day
  ) {
    return null;
  }

  const gm = String(month).padStart(2, '0');
  const gd = String(day).padStart(2, '0');
  return `${year}-${gm}-${gd}`;
}

/** `YYYY-MM-DD` → typed Gregorian field text. */
export function formatIsoAsGregorianDateInput(iso: string): string {
  if (!iso) return '';
  const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
  return match ? iso : '';
}
