/** Timezone-selector pattern — populate select-ui[searchable] from Intl.supportedValuesOf. */

function offsetLabel(tz, when = new Date()) {
  try {
    const parts = new Intl.DateTimeFormat('en-US', {
      timeZone: tz,
      timeZoneName: 'shortOffset',
    }).formatToParts(when);
    const name = parts.find(p => p.type === 'timeZoneName')?.value || '';
    // shortOffset → "GMT-8" / "GMT+05:30"; normalize to "UTC-8".
    return name.replace(/^GMT/, 'UTC') || '';
  } catch {
    return '';
  }
}

function localTimeIn(tz, when = new Date()) {
  try {
    return new Intl.DateTimeFormat([], {
      timeZone: tz,
      hour: '2-digit',
      minute: '2-digit',
      weekday: 'short',
    }).format(when);
  } catch {
    return '';
  }
}

function timezoneOptions() {
  let zones = [];
  try {
    zones = Intl.supportedValuesOf('timeZone');
  } catch {
    zones = ['UTC', 'America/Los_Angeles', 'America/New_York', 'Europe/London', 'Europe/Berlin', 'Asia/Tokyo', 'Asia/Shanghai', 'Australia/Sydney'];
  }
  return zones.map(tz => ({
    value: tz,
    label: `${tz} · ${offsetLabel(tz)}`,
  }));
}

function populate(select, defaultTz) {
  select.options = timezoneOptions();
  if (defaultTz) select.value = defaultTz;
}

export default function setup(router) {
  const root = router || document;
  const defaultTz = Intl.DateTimeFormat().resolvedOptions().timeZone;

  // Basic picker
  const basic = root.querySelector?.('#tz-select-basic');
  if (basic) {
    populate(basic, defaultTz);
    const hint = root.querySelector('#tz-hint-basic');
    if (hint) hint.textContent = `Detected from your browser locale: ${defaultTz} (${offsetLabel(defaultTz)}).`;
  }

  // With live preview
  const preview = root.querySelector?.('#tz-select-preview');
  const previewLine = root.querySelector?.('#tz-preview');
  if (preview && previewLine) {
    populate(preview, defaultTz);
    const update = () => {
      const tz = preview.value || defaultTz;
      previewLine.textContent = `Current time in ${tz}: ${localTimeIn(tz)} (${offsetLabel(tz)}).`;
    };
    update();
    preview.addEventListener('change', update);
  }
}
