import { ResponsiveCalendar } from '@nivo/calendar';
import type { ComponentProps } from 'react';
import type { HabitService } from '../habits/service';

export type CalendarResponse = ReturnType<HabitService['calendar']>;
export type ResponsiveCalendarProps = ComponentProps<typeof ResponsiveCalendar>;

/** Data adapter only: no frontend component or page is rendered here. */
export function toResponsiveCalendarProps(calendar: CalendarResponse) {
  // Nivo calls colorScale with a value, not a date. Give each date a stable
  // index so identical shade levels under different historical targets cannot
  // collapse into one color. Actual progress remains in calendar.days.
  const data = calendar.days.map((day, index) => ({ day: day.date, value: index }));
  const colorScale = Object.assign(
    (value: number | { valueOf(): number }) => calendar.days[Number(value)]?.color ?? calendar.settings.notDueColor,
    { ticks: () => [] as number[] },
  );
  const props = {
    from: calendar.from, to: calendar.to, data, colorScale,
    emptyColor: calendar.settings.notDueColor,
    valueFormat: (index: number) => {
      const day = calendar.days[index];
      if (!day) return '';
      if (day.future) return 'Upcoming';
      if (day.ratio === null) return 'Nothing scheduled';
      // Counts for combined charts are always equal-weight completed habits.
      if (calendar.kind === 'combined') return `${day.completed} of ${day.due} habits complete`;
      const habit = day.habits[0]!;
      return `${habit.value} of ${habit.target} ${habit.unit}`;
    },
  } satisfies ResponsiveCalendarProps;
  return props;
}
