'use client';

import { useMemo } from 'react';
import { useLocale } from 'next-intl';
import { APP_DATE, createAppDateFormatter } from '@/lib/i18n/format';

export function useTodayDayLabelFormatter() {
  const locale = useLocale();
  return useMemo(
    () => createAppDateFormatter(locale, APP_DATE.chartDay),
    [locale],
  );
}

export function formatTodayChartDayLabel(
  code: string,
  formatter: Intl.DateTimeFormat,
): string {
  const [year, month, day] = code.split('-').map(Number);
  if (!year || !month || !day) return code;
  return formatter.format(new Date(year, month - 1, day));
}

export function mapWeekChartBuckets<T extends { code: string; label: string }>(
  buckets: T[],
  formatter: Intl.DateTimeFormat,
): T[] {
  return buckets.map((bucket) => ({
    ...bucket,
    label: formatTodayChartDayLabel(bucket.code, formatter),
  }));
}

/**
 * Recharts XAxis spacing for dense day-series (e.g. 30-day month view).
 * `preserveStartEnd` keeps first/last ticks; `minTickGap` skips overlaps.
 */
export function todayChartDenseXAxisProps(pointCount: number): {
  interval: number | 'preserveStartEnd';
  minTickGap?: number;
  fontSize: number;
} {
  if (pointCount <= 8) {
    return { interval: 0, fontSize: 11 };
  }
  if (pointCount <= 14) {
    return { interval: 1, fontSize: 10 };
  }
  return { interval: 'preserveStartEnd', minTickGap: 36, fontSize: 10 };
}

/**
 * Category bar charts (prosthesis / treatment mix) — fewer bars but longer labels.
 */
export function todayChartCategoryXAxisProps(pointCount: number): {
  interval: number | 'preserveStartEnd';
  minTickGap?: number;
  fontSize: number;
  truncateMax: number;
} {
  if (pointCount <= 4) {
    return { interval: 0, fontSize: 11, truncateMax: 12 };
  }
  if (pointCount <= 6) {
    return { interval: 1, fontSize: 10, truncateMax: 9, minTickGap: 28 };
  }
  return {
    interval: 'preserveStartEnd',
    minTickGap: 40,
    fontSize: 10,
    truncateMax: 8,
  };
}
