/**
 * Timezone types and utilities — timezone-handling (wave-11 leaf-E).
 */

export type IanaTimezone = string & { readonly __brand: 'IanaTimezone' }

export const DEFAULT_TIMEZONE = 'Asia/Jerusalem' as IanaTimezone

export function isValidTimezone(tz: string): tz is IanaTimezone {
  if (!tz) return false
  try {
    new Intl.DateTimeFormat(undefined, { timeZone: tz })
    return true
  } catch {
    return false
  }
}

export function listSupportedTimezones(): IanaTimezone[] {
  const intlWithSupported = Intl as unknown as {
    supportedValuesOf?: (key: string) => string[]
  }
  const zones = intlWithSupported.supportedValuesOf
    ? intlWithSupported.supportedValuesOf('timeZone')
    : [DEFAULT_TIMEZONE]
  return [...zones].sort() as IanaTimezone[]
}

export function groupTimezonesByContinent(
  zones: IanaTimezone[],
): Record<string, IanaTimezone[]> {
  const out: Record<string, IanaTimezone[]> = {}
  for (const z of zones) {
    const continent = z.includes('/') ? z.slice(0, z.indexOf('/')) : 'Other'
    ;(out[continent] ??= []).push(z)
  }
  return out
}
