(function () {
    function parseApiDate(value) {
        if (!value) return null;
        const text = String(value).trim();
        if (!text) return null;
        const isoLike = /^\d{4}-\d{2}-\d{2}[T\s]\d{2}:\d{2}/.test(text);
        const hasZone = /(?:Z|[+-]\d{2}:?\d{2})$/.test(text);
        const normalized = isoLike && !hasZone ? `${text.replace(' ', 'T')}Z` : text;
        const date = new Date(normalized);
        return Number.isNaN(date.getTime()) ? null : date;
    }

    function pad(value, length = 2) {
        return String(value).padStart(length, '0');
    }

    function toLocalInputValue(value, includeSeconds = false) {
        const date = value instanceof Date ? value : parseApiDate(value);
        if (!date) return '';
        const base = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
        return includeSeconds ? `${base}:${pad(date.getSeconds())}` : base;
    }

    function toUtcIsoFromInput(value) {
        if (!value) return '';
        const date = new Date(value);
        return Number.isNaN(date.getTime()) ? '' : date.toISOString();
    }

    function toUtcIsoFromRussianDateTime(value) {
        const match = String(value || '').trim().match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})\.(\d{1,3})$/);
        if (!match) return '';
        const [, day, month, year, hour, minute, second, millisecond] = match;
        const date = new Date(
            Number(year),
            Number(month) - 1,
            Number(day),
            Number(hour),
            Number(minute),
            Number(second),
            Number(millisecond.padEnd(3, '0'))
        );
        const valid = date.getFullYear() === Number(year)
            && date.getMonth() === Number(month) - 1
            && date.getDate() === Number(day)
            && date.getHours() === Number(hour)
            && date.getMinutes() === Number(minute)
            && date.getSeconds() === Number(second);
        return valid ? date.toISOString() : '';
    }

    function formatDateTime(value, options = {}) {
        const date = value instanceof Date ? value : parseApiDate(value);
        if (!date) return options.fallback || '-';
        return date.toLocaleString(options.locale || 'ru-RU', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: options.seconds === false ? undefined : '2-digit'
        });
    }

    window.PcpUtcTime = {
        parseApiDate,
        toLocalInputValue,
        toUtcIsoFromInput,
        toUtcIsoFromRussianDateTime,
        formatDateTime
    };
})();
