/**
 * Date-axis helpers for the Yield Manager multi-calendar.
 *
 * The day-grid columns are driven by a single shared axis (an ordered list of
 * YYYY-MM-DD strings) so every row's cells line up under the same headers. The
 * axis is derived from the union of all loaded series dates, falling back to a
 * generated today..+(DAY_COUNT-1) range while series are still loading.
 */
import { addDays, format, parseISO } from 'date-fns';

/** Number of nights the backend returns per property (~90). */
export const DAY_COUNT = 90;

/** Fixed pixel width of one day column (header + cell share it). */
export const DAY_COL_WIDTH = 56;

/** Generate today..+(count-1) as YYYY-MM-DD strings. */
export function generateAxis(count: number = DAY_COUNT, from: Date = new Date()): string[] {
    const out: string[] = [];
    for (let i = 0; i < count; i += 1) {
        out.push(format(addDays(from, i), 'yyyy-MM-dd'));
    }
    return out;
}

/**
 * Union of all dates present across the loaded series, ascending. Falls back to
 * a generated range when nothing is loaded yet so the grid renders immediately.
 */
export function buildAxis(seriesValues: ReadonlyArray<ReadonlyArray<{ date: string }>>): string[] {
    const set = new Set<string>();
    for (const series of seriesValues) {
        for (const day of series) {
            set.add(day.date);
        }
    }
    if (set.size === 0) {
        return generateAxis();
    }
    return Array.from(set).sort();
}

/** Parsed-date metadata for a column header. */
export interface AxisDay {
    iso: string;
    dayOfMonth: number;
    /** Short weekday label, locale-aware (e.g. "ven."). */
    weekday: string;
    isWeekend: boolean;
    isToday: boolean;
}

const todayIso = format(new Date(), 'yyyy-MM-dd');

/** Decorate an axis with display metadata used by the column headers. */
export function decorateAxis(axis: string[], locale: string): AxisDay[] {
    return axis.map((iso) => {
        const d = parseISO(iso);
        const weekdayIndex = d.getDay(); // 0 = Sunday … 6 = Saturday
        return {
            iso,
            dayOfMonth: d.getDate(),
            weekday: d.toLocaleDateString(locale, { weekday: 'short' }).replace('.', ''),
            isWeekend: weekdayIndex === 0 || weekdayIndex === 6,
            isToday: iso === todayIso,
        };
    });
}
