export type BusinessHours = Record<string, { open: string; close: string }>;

export type SwitchListValue = Array<string | number>;

export function normalizeBusinessHours(value: unknown): BusinessHours {
  if (!value || typeof value !== 'object') return {};

  return Object.entries(value as Record<string, unknown>).reduce<BusinessHours>((hours, [day, range]) => {
    if (typeof range === 'string') {
      const [open, close] = range.split('-').map((part) => part.trim());
      if (open && close) hours[day] = { open: normalizeTime(open), close: normalizeTime(close) };
      return hours;
    }

    if (range && typeof range === 'object') {
      const record = range as { open?: string; close?: string };
      if (record.open && record.close) {
        hours[day] = { open: normalizeTime(record.open), close: normalizeTime(record.close) };
      }
    }

    return hours;
  }, {});
}

export function normalizeSwitchList(value: unknown): SwitchListValue {
  if (Array.isArray(value)) return value;
  if (!value || typeof value !== 'object') return [];
  return Object.keys(value as Record<string, unknown>).filter((key) => (value as Record<string, unknown>)[key]);
}

function normalizeTime(value: string): string {
  if (!value) return '';
  const parsed = new Date(`2000-01-01 ${value}`);
  if (!Number.isNaN(parsed.getTime())) {
    return `${String(parsed.getHours()).padStart(2, '0')}:${String(parsed.getMinutes()).padStart(2, '0')}`;
  }
  return value;
}

export function buildTimeOptions(): string[] {
  return Array.from({ length: 48 }, (_, index) => {
    const hours = Math.floor(index / 2);
    const minutes = index % 2 === 0 ? '00' : '30';
    return `${String(hours).padStart(2, '0')}:${minutes}`;
  });
}

export function displayTime(value: string): string {
  if (!value) return '';
  const [hours, minutes] = value.split(':').map(Number);
  if (Number.isNaN(hours) || Number.isNaN(minutes)) return value;
  const period = hours >= 12 ? 'PM' : 'AM';
  const hour12 = hours % 12 === 0 ? 12 : hours % 12;
  return `${hour12}:${String(minutes).padStart(2, '0')} ${period}`;
}
