/**
 * Pure helper functions for generating and navigating date ranges
 * in the DayTabs component. No React, no side effects.
 */

/** Format a Date as yyyymmdd (zero-padded). */
export function formatYyyymmdd(d: Date): string {
  const y = d.getFullYear().toString();
  const m = (d.getMonth() + 1).toString().padStart(2, "0");
  const day = d.getDate().toString().padStart(2, "0");
  return `${y}${m}${day}`;
}

/** Parse a yyyymmdd string into a local Date. */
export function parseYyyymmdd(s: string): Date {
  const y = parseInt(s.slice(0, 4), 10);
  const m = parseInt(s.slice(4, 6), 10) - 1;
  const day = parseInt(s.slice(6, 8), 10);
  return new Date(y, m, day);
}

/**
 * Generate an inclusive list of yyyymmdd strings spanning
 * [base - daysBefore, base + daysAfter].
 */
export function generateDateRange(base: Date, daysBefore: number, daysAfter: number): string[] {
  const result: string[] = [];
  for (let offset = -daysBefore; offset <= daysAfter; offset++) {
    const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + offset);
    result.push(formatYyyymmdd(d));
  }
  return result;
}

/**
 * Find the page index (0-based) containing the given date, paginated by pageSize.
 * Returns 0 if the date is not in the list.
 */
export function findPageIndex(dates: string[], target: string, pageSize: number): number {
  const idx = dates.indexOf(target);
  if (idx < 0) return 0;
  return Math.floor(idx / pageSize);
}
