import { useTranslation } from '@/hooks/use-translation';
import { cn } from '@/lib/utils';
import { daysInRange, rangesOverlap } from '../season-range-utils';

export type TimelineSegment = {
    start_date: string;
    end_date: string;
    /** Tailwind background classes (literal strings so the JIT sees them). */
    color: string;
    /** Human label, shown in the native tooltip and the legend (include the price). */
    label: string;
};

type SeasonTimelineProps = {
    /** Window start, local ISO date (YYYY-MM-DD). */
    today: string;
    /** Window end (inclusive), usually `addOneYear(today)`. */
    horizon: string;
    /**
     * Pre-computed by the parent (seasons + base-price gaps + untouched
     * stretches). Expected to cover the window contiguously; segments are
     * clamped/sorted here, but holes are not re-filled.
     */
    segments: TimelineSegment[];
};

/** dd/MM/yy — compact, always unambiguous across the 1-year window. */
function formatShort(iso: string): string {
    const [year, month, day] = iso.split('-');
    return `${day}/${month}/${year.slice(2)}`;
}

/**
 * Spec D — proportional coverage bar of the [today → today + 1 year] window.
 * Pure CSS flex: each segment's width is its inclusive day count as a
 * percentage of the window. Native `title` tooltips, small legend below.
 */
export default function SeasonTimeline({ today, horizon, segments }: SeasonTimelineProps) {
    const { t } = useTranslation();
    const window = { start_date: today, end_date: horizon };
    const totalDays = daysInRange(window);

    const visible = segments
        .filter((s) => s.start_date <= s.end_date && rangesOverlap(s, window))
        .map((s) => ({
            ...s,
            start_date: s.start_date < today ? today : s.start_date,
            end_date: s.end_date > horizon ? horizon : s.end_date,
        }))
        .sort((a, b) => (a.start_date < b.start_date ? -1 : a.start_date > b.start_date ? 1 : 0));

    // Legend: one entry per distinct color+label pair, in bar order.
    const legend = visible.filter((s, i) => visible.findIndex((o) => o.color === s.color && o.label === s.label) === i);

    return (
        <div className="flex flex-col gap-1.5">
            <p className="text-sm font-medium">{t('properties.step6', 'timeline_title')}</p>
            <div className="flex h-3 w-full overflow-hidden rounded-full">
                {visible.map((s, i) => (
                    <div
                        key={`${s.start_date}-${i}`}
                        title={`${s.label} · ${formatShort(s.start_date)} → ${formatShort(s.end_date)}`}
                        className={cn('h-full min-w-px', s.color)}
                        // Proportional width: the one dynamic value Tailwind cannot express statically.
                        style={{ width: `${(daysInRange(s) / totalDays) * 100}%` }}
                    />
                ))}
            </div>
            <div className="text-muted-foreground flex justify-between text-[10px]">
                <span>{formatShort(today)}</span>
                <span>{formatShort(horizon)}</span>
            </div>
            {legend.length > 0 && (
                <div className="flex flex-wrap gap-x-3 gap-y-1">
                    {legend.map((s) => (
                        <span key={`${s.color}-${s.label}`} className="text-muted-foreground flex items-center gap-1 text-xs">
                            <span className={cn('h-2 w-2 shrink-0 rounded-full', s.color)} />
                            {s.label}
                        </span>
                    ))}
                </div>
            )}
        </div>
    );
}
