import type { GroupGroupProp } from '@/features/deal-detail';

export type GroupProgressState =
  | { kind: 'full' }
  | { kind: 'next_tier'; count: number; percent: number }
  | { kind: 'best_price' }
  | { kind: 'threshold_met' }
  | { kind: 'below_min'; current: number; target: number };

export function computeGroupProgress(g: GroupGroupProp): GroupProgressState {
  const { currentReservationCount: current, minGroupSize, maxGroupSize, groupState, tiers } = g;

  if (current >= maxGroupSize) return { kind: 'full' };

  if (tiers.length > 0) {
    // Best discount already unlocked at the current count.
    const unlocked = tiers
      .filter((t) => current >= t.minParticipants)
      .reduce((max, t) => Math.max(max, t.discountPercent), 0);
    // Next tier ahead that actually improves on what's unlocked (monotonic guard).
    const next = tiers
      .filter((t) => t.minParticipants > current && t.discountPercent > unlocked)
      .sort((a, b) => a.minParticipants - b.minParticipants)[0];
    if (next)
      return {
        kind: 'next_tier',
        count: next.minParticipants - current,
        percent: next.discountPercent,
      };
    return { kind: 'best_price' };
  }

  if (groupState !== 'COLLECTING') return { kind: 'threshold_met' };
  return { kind: 'below_min', current: Math.min(current, minGroupSize), target: minGroupSize };
}

/** Bar axis max: minGroupSize for below-min non-tiered; maxGroupSize otherwise. */
export function groupProgressBarMax(g: GroupGroupProp, s: GroupProgressState): number {
  return s.kind === 'below_min' ? s.target : g.maxGroupSize;
}
