// Native <input type="datetime-local">/date-time picker values carry no
// timezone info  the browser just gives back a "YYYY-MM-DDTHH:mm" wall-clock
// string. These helpers interpret/display that string against the tenant's
// configured timezone (Settings > General Settings) instead of assuming the
// browser's own local timezone, so scheduling behaves the same regardless of
// which device/timezone someone happens to be using when they schedule a send.

function getParts(date, timeZone) {
    const parts = new Intl.DateTimeFormat('en-US', {
        timeZone,
        hour12: false,
        year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit', second: '2-digit',
    }).formatToParts(date);

    const get = (type) => Number(parts.find((p) => p.type === type)?.value ?? 0);

    return {
        year: get('year'),
        month: get('month'),
        day: get('day'),
        hour: get('hour') % 24, // Intl can report "24" for midnight
        minute: get('minute'),
        second: get('second'),
    };
}

// Convert a "YYYY-MM-DDTHH:mm" wall-clock string, meant to represent that
// time in `timeZone`, into a UTC ISO string.
export function zonedTimeToUtcIso(localValue, timeZone) {
    if (!localValue) return null;

    const [datePart, timePart] = localValue.split('T');
    const [year, month, day] = datePart.split('-').map(Number);
    const [hour, minute] = (timePart || '00:00').split(':').map(Number);

    // First guess: treat the wall-clock numbers as if they were already UTC.
    const guessUtc = Date.UTC(year, month - 1, day, hour, minute, 0);

    // Find what that guessed UTC instant actually displays as in `timeZone`,
    // then correct by the difference  this is the standard offset-less
    // conversion trick for going from an arbitrary IANA zone to UTC.
    const asIfLocal = getParts(new Date(guessUtc), timeZone);
    const asIfLocalUtc = Date.UTC(
        asIfLocal.year, asIfLocal.month - 1, asIfLocal.day,
        asIfLocal.hour, asIfLocal.minute, asIfLocal.second
    );

    const correction = guessUtc - asIfLocalUtc;
    return new Date(guessUtc + correction).toISOString();
}

// Format a UTC ISO string for display in `timeZone`.
export function formatInTimeZone(isoString, timeZone, options = {}) {
    if (!isoString) return '';
    return new Date(isoString).toLocaleString('en-US', {
        timeZone,
        month: 'short', day: 'numeric', year: 'numeric',
        hour: 'numeric', minute: '2-digit', hour12: true,
        ...options,
    });
}

// "Right now", as a "YYYY-MM-DD HH:mm:ss" wall-clock string in `timeZone` 
// for "current time in your account timezone" style hints next to pickers.
export function nowInTimeZone(timeZone) {
    const p = getParts(new Date(), timeZone);
    const pad = (n) => String(n).padStart(2, '0');
    return `${p.year}-${pad(p.month)}-${pad(p.day)} ${pad(p.hour)}:${pad(p.minute)}:${pad(p.second)}`;
}
