import { EthDateTime } from 'ethiopian-calendar-date-converter';

const EC_MONTHS_AM = [
  'መስከረም', 'ጥቅምት', 'ኅዳር', 'ታህሳስ', 'ጥር', 'የካቲት',
  'መጋቢት', 'ሚያዝያ', 'ግንቦት', 'ሰኔ', 'ሐምሌ', 'ነሐሴ', 'ጳጉሜን',
];

// EthDateTime.fromEuropeanDate() computes the day from a raw UTC-epoch
// difference. A local-midnight Date in any positive-UTC-offset timezone
// (e.g. Ethiopia, UTC+3) lands in the previous UTC day and converts to
// yesterday's Ethiopian date. Re-embedding the same Y/M/D at UTC noon fixes
// the day regardless of the runtime's timezone.
export function toEthDateTime(date: Date): EthDateTime {
  const utcNoon = new Date(
    Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), 12),
  );
  return EthDateTime.fromEuropeanDate(utcNoon);
}

export function ethMonthName(date: Date): string {
  try {
    return EC_MONTHS_AM[toEthDateTime(date).month - 1] ?? '';
  } catch {
    return '';
  }
}

export function toAmharicDisplay(date: Date): string {
  try {
    const eth = toEthDateTime(date);
    return `${ethMonthName(date)} ${eth.date}/${eth.year}`;
  } catch {
    return date.toLocaleDateString('en-US');
  }
}

export type EthPeriod = 'lelit' | 'tewat' | 'ken' | 'mata';

// Ethiopian day starts at 6am. Period is picked from the 24h hour; the
// displayed hour is the Western hour shifted 6, wrapped onto a 12-hour dial.
// Each period only spans 6 hours (not 12): ጠዋት/ማታ show 12,1..5, ቀን/ሌሊት show
// 6..11 — offering all 12 hours in every period would let a user pick e.g.
// "ጠዋት 7", which has no 06:00–11:59 preimage.
export const ETH_PERIODS: { value: EthPeriod; label: string; hours: number[] }[] = [
  { value: 'tewat', label: 'ጠዋት', hours: [12, 1, 2, 3, 4, 5] }, // 06:00–11:59
  { value: 'ken', label: 'ቀን', hours: [6, 7, 8, 9, 10, 11] }, // 12:00–17:59
  { value: 'mata', label: 'ማታ', hours: [12, 1, 2, 3, 4, 5] }, // 18:00–23:59
  { value: 'lelit', label: 'ሌሊት', hours: [6, 7, 8, 9, 10, 11] }, // 00:00–05:59
];

export function toEthTime(h24: number): { period: EthPeriod; hour: number } {
  const period: EthPeriod =
    h24 < 6 ? 'lelit' : h24 < 12 ? 'tewat' : h24 < 18 ? 'ken' : 'mata';
  return { period, hour: ((h24 + 6) % 12) || 12 };
}

export function fromEthTime(period: EthPeriod, hour: number): number {
  // Inverse of the shift, then re-add the 12h that %12 discarded for the
  // afternoon/night pair of periods.
  const pm = period === 'ken' || period === 'mata';
  return ((hour + 6) % 12) + (pm ? 12 : 0);
}

export function ethTimeLabel(date: Date): string {
  const { period, hour } = toEthTime(date.getHours());
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const label = ETH_PERIODS.find((p) => p.value === period)?.label ?? '';
  return `${String(hour).padStart(2, '0')}:${minutes} ${label}`;
}
