import { useCallback, useMemo, useState } from 'react';

import {
  BOARD_REF_DATE_KEY,
  dateToQuarter,
  parseIsoDate,
  startOfDay,
  toIsoDate,
} from '../lib/boardCalendar';

export function useBoardReferenceDate() {
  const [referenceDate, setReferenceDateState] = useState<Date>(() => {
    try {
      const stored = localStorage.getItem(BOARD_REF_DATE_KEY);
      if (stored) {
        const parsed = parseIsoDate(stored);
        if (parsed) return startOfDay(parsed);
      }
    } catch {
      /* ignore */
    }
    return startOfDay(new Date());
  });

  const setReferenceDate = useCallback((d: Date) => {
    const normalized = startOfDay(d);
    setReferenceDateState(normalized);
    try {
      localStorage.setItem(BOARD_REF_DATE_KEY, toIsoDate(normalized));
    } catch {
      /* ignore */
    }
  }, []);

  const quarter = useMemo(() => dateToQuarter(referenceDate), [referenceDate]);

  const resetToToday = useCallback(() => {
    setReferenceDate(startOfDay(new Date()));
  }, [setReferenceDate]);

  return { referenceDate, setReferenceDate, quarter, resetToToday };
}
