/**
 * Fechas "solo calendario" del API (Y-m-d o ISO con T/Z) sin desfase por UTC:
 * el día mostrado y el Y-m-d del formulario coinciden con el backend.
 */

const YMD_AT_START = /^(\d{4})-(\d{2})-(\d{2})/;

/**
 * Devuelve `YYYY-MM-DD` tomado del inicio del string (parte calendario antes de hora/zona).
 */
export function calendarYmdFromServer(value: string | null | undefined): string {
    if (value == null || typeof value !== 'string') return '';
    const s = value.trim();
    const m = s.match(YMD_AT_START);
    if (!m) return '';
    return `${m[1]}-${m[2]}-${m[3]}`;
}

/** Fecha local de hoy en `YYYY-MM-DD` (no usar `toISOString()` para evitar cambio de día por UTC). */
export function todayLocalYmd(): string {
    const n = new Date();
    const y = n.getFullYear();
    const mo = String(n.getMonth() + 1).padStart(2, '0');
    const d = String(n.getDate()).padStart(2, '0');
    return `${y}-${mo}-${d}`;
}

/** Presentación fija **dd/mm/yyyy** cuando el valor trae prefijo `YYYY-MM-DD`. */
export function formatCalendarDateEs(value: string | null | undefined): string {
    const ymd = calendarYmdFromServer(value ?? '');
    if (ymd) {
        const [yy, mm, dd] = ymd.split('-');
        return `${dd}/${mm}/${yy}`;
    }
    if (value == null || !String(value).trim()) return '-';
    const dt = new Date(String(value));
    return Number.isNaN(dt.getTime()) ? '-' : dt.toLocaleDateString('es-ES');
}

/** True si la fecha calendario del valor es estrictamente anterior a hoy (zona local). */
export function isCalendarDateBeforeToday(value: string | null | undefined): boolean {
    const ymd = calendarYmdFromServer(value ?? '');
    if (!ymd) {
        const dt = new Date(String(value ?? ''));
        return !Number.isNaN(dt.getTime()) && dt < new Date();
    }
    return ymd < todayLocalYmd();
}
