'use client';

export type TodayChartPeriod = 'week' | 'month' | 'year';

export type TodayChartPeriodKey =
  | 'appointmentsWeekAll'
  | 'appointmentsWeekMine'
  | 'labTaskActivity'
  | 'casesDue'
  | 'treatmentMix'
  | 'casePartners'
  | 'efficiency';

export type TodayChartPeriods = Record<TodayChartPeriodKey, TodayChartPeriod>;

export const TODAY_CHART_PERIOD_KEYS: TodayChartPeriodKey[] = [
  'appointmentsWeekAll',
  'appointmentsWeekMine',
  'labTaskActivity',
  'casesDue',
  'treatmentMix',
  'casePartners',
  'efficiency',
];

export const TODAY_CHART_PERIOD_DEFAULTS: TodayChartPeriods = {
  appointmentsWeekAll: 'week',
  appointmentsWeekMine: 'week',
  labTaskActivity: 'week',
  casesDue: 'week',
  treatmentMix: 'week',
  casePartners: 'month',
  efficiency: 'month',
};

/** Aggregate charts that support year; day-series charts are week/month only. */
export const TODAY_CHART_PERIODS_WITH_YEAR: ReadonlySet<TodayChartPeriodKey> = new Set([
  'treatmentMix',
  'casePartners',
  'efficiency',
]);

export function daysForTodayChartPeriod(period: TodayChartPeriod): 7 | 30 | 365 {
  switch (period) {
    case 'month':
      return 30;
    case 'year':
      return 365;
    default:
      return 7;
  }
}

export function allowedPeriodsForChart(
  key: TodayChartPeriodKey,
): readonly TodayChartPeriod[] {
  return TODAY_CHART_PERIODS_WITH_YEAR.has(key)
    ? (['week', 'month', 'year'] as const)
    : (['week', 'month'] as const);
}

function storageKey(organizationId: string): string {
  return `dyolink:today-chart-periods:${organizationId}`;
}

function normalizePeriod(
  key: TodayChartPeriodKey,
  value: unknown,
): TodayChartPeriod {
  const allowed = allowedPeriodsForChart(key);
  if (typeof value === 'string' && (allowed as readonly string[]).includes(value)) {
    return value as TodayChartPeriod;
  }
  return TODAY_CHART_PERIOD_DEFAULTS[key];
}

export function loadTodayChartPeriods(organizationId: string): TodayChartPeriods {
  if (typeof window === 'undefined') return { ...TODAY_CHART_PERIOD_DEFAULTS };
  try {
    const raw = window.localStorage.getItem(storageKey(organizationId));
    if (!raw) return { ...TODAY_CHART_PERIOD_DEFAULTS };
    const parsed = JSON.parse(raw) as Partial<Record<TodayChartPeriodKey, unknown>>;
    const next = { ...TODAY_CHART_PERIOD_DEFAULTS };
    for (const key of TODAY_CHART_PERIOD_KEYS) {
      next[key] = normalizePeriod(key, parsed[key]);
    }
    return next;
  } catch {
    return { ...TODAY_CHART_PERIOD_DEFAULTS };
  }
}

export function saveTodayChartPeriods(
  organizationId: string,
  periods: TodayChartPeriods,
): void {
  if (typeof window === 'undefined') return;
  try {
    window.localStorage.setItem(storageKey(organizationId), JSON.stringify(periods));
  } catch {
    // ignore quota / private mode
  }
}
