import { AwardInstance } from '@/types/Award';

/**
 * Resolves the locale-correct slug for a `/dij/[slug]` link.
 * Prefers the English slug (`urlEn`) on English, falls back to the Hungarian
 * slug, and finally to the numeric id — mirrors `getEventProgramSlug`.
 */
export const getAwardSlug = (
  award: { url?: string | null; urlEn?: string | null; id: number },
  locale: string
): string => {
  const localized = locale.startsWith('en') ? award.urlEn || award.url : award.url;
  return localized?.trim() || award.id.toString();
};

/* ---- Award type chips ----------------------------------------------------
   Two-tone by status: state awards ("állami") read gold (mma-yellow), every
   other award reads blue. Dark ink text keeps both legible on white. Classes
   are literal so Tailwind emits them.
     • chip    → the badge fill.
     • accent  → the left-border accent on award cards / panels.
     • surface → the tinted panel background (e.g. the type-info box).
     • hover   → the card background tint on hover (clickable cards). */
type AwardTypeChip = { chip: string; accent: string; surface: string; hover: string };

const STATE_CHIP: AwardTypeChip = {
  chip: 'bg-mma-yellow/90 text-brand-primary',
  accent: 'border-l-mma-yellow',
  surface: 'bg-mma-yellow/[0.08]',
  hover: 'hover:bg-mma-yellow/10',
};

const DEFAULT_CHIP: AwardTypeChip = {
  chip: 'bg-mma-cyan/90 text-brand-primary',
  accent: 'border-l-mma-cyan',
  surface: 'bg-mma-cyan/[0.08]',
  hover: 'hover:bg-mma-cyan/10',
};

/** Award type id for state ("állami") awards — locale-independent. */
export const STATE_AWARD_TYPE_ID = 121001;

/** State awards are gold and the only ones with a detail page for now. */
export const isStateAward = (typeId?: number | null): boolean => typeId === STATE_AWARD_TYPE_ID;

export const getAwardTypeChip = (typeId?: number | null): AwardTypeChip =>
  isStateAward(typeId) ? STATE_CHIP : DEFAULT_CHIP;

/** A set of recipients that received the award in the same year. */
export interface AwardYearGroup {
  year: number | null;
  recipients: AwardInstance[];
}

/**
 * Groups award instances by year (newest first); records without a year fall
 * into a trailing group so nothing is dropped.
 */
export const groupAwardInstancesByYear = (instances: AwardInstance[]): AwardYearGroup[] => {
  const byYear = new Map<number | null, AwardInstance[]>();

  for (const instance of instances) {
    const year = instance.dijPeldany?.ev ?? null;
    const list = byYear.get(year) ?? [];
    list.push(instance);
    byYear.set(year, list);
  }

  return Array.from(byYear.entries())
    .map(([year, recipients]) => ({ year, recipients }))
    .sort((a, b) => {
      if (a.year === null) return 1;
      if (b.year === null) return -1;
      return b.year - a.year;
    });
};
