/**
 * Tischtennis-Altersklassen nach Stichtag 01.01. (z. B. DTTB / Mannschafts- und Einzelspielbetrieb).
 * Pro Saison verschieben sich die Jahrgänge um ein Jahr; die Logik nutzt das erste Saisonjahr (z. B. 2025 für 2025/26).
 */

const YOUTH_BANDS = [9, 11, 13, 15, 19];

/**
 * @param {Date} [d]
 * @returns {number} Erstes Kalenderjahr der laufenden Spielzeit (01.08.–31.07. üblich: Aug–Dez = Jahr, Jan–Jul = Vorjahr).
 */
export function getSeasonStartYearFromDate(d = new Date()) {
  const month = d.getMonth() + 1;
  const year = d.getFullYear();
  return month >= 8 ? year : year - 1;
}

/**
 * Stichtag 01.01. für „Mädchen & Jungen n“: Geburtsdatum >= 01.01.(Saisonbeginn − (n − 1))
 * Beispiel Saison 2025/26: J19 → 01.01.2007, J15 → 01.01.2011, …, J9 → 01.01.2017
 * @param {number} seasonStartYear z. B. 2025
 * @param {number} classNum 9 | 11 | 13 | 15 | 19
 */
export function getStichtagDate(seasonStartYear, classNum) {
  const y = seasonStartYear - (classNum - 1);
  return new Date(y, 0, 1);
}

/** @param {object} member */
export function isFemaleGender(member) {
  const g = member?.gender;
  if (g == null || g === '') return false;
  return String(g).toLowerCase() === 'female';
}

function birthDateToTime(birthDate) {
  if (!birthDate) return null;
  let d;
  if (birthDate instanceof Date && !Number.isNaN(birthDate.getTime())) {
    d = birthDate;
  } else if (typeof birthDate === 'string') {
    const t = birthDate.trim();
    if (t.includes('-')) {
      const [a, b, c] = t.split(/[T\s]/)[0].split('-').map(Number);
      if (Number.isFinite(a) && Number.isFinite(b) && Number.isFinite(c)) {
        d = new Date(a, b - 1, c);
      }
    } else if (t.includes('.')) {
      const parts = t.split('.');
      if (parts.length >= 3) {
        const day = parseInt(parts[0], 10);
        const month = parseInt(parts[1], 10);
        const year = parseInt(parts[2], 10);
        if (Number.isFinite(day) && Number.isFinite(month) && Number.isFinite(year)) {
          d = new Date(year, month - 1, day);
        }
      }
    }
  }
  if (!d || Number.isNaN(d.getTime())) return null;
  return d.getTime();
}

/**
 * Engste Jugend-Altersklasse (exklusive Bänder zwischen den Stichtagen).
 * @returns {'J9'|'J11'|'J13'|'J15'|'J19'|'adult'|null} null = kein gültiges Geburtsdatum
 */
export function getExclusiveJugendClass(birthDate, seasonStartYear) {
  const t = birthDateToTime(birthDate);
  if (t === null) return null;

  const c = (k) => getStichtagDate(seasonStartYear, k).getTime();
  const c9 = c(9);
  const c11 = c(11);
  const c13 = c(13);
  const c15 = c(15);
  const c19 = c(19);

  if (t < c19) return 'adult';
  if (t >= c9) return 'J9';
  if (t >= c11 && t < c9) return 'J11';
  if (t >= c13 && t < c11) return 'J13';
  if (t >= c15 && t < c13) return 'J15';
  if (t >= c19 && t < c15) return 'J19';
  return 'adult';
}

/**
 * @param {object} member
 * @param {string} filterKey '', 'adult', 'range', 'J9'…'J19', 'M9'…'M19'
 * @param {number} seasonStartYear
 * @returns {boolean}
 */
export function memberMatchesTtAgeClass(member, filterKey, seasonStartYear) {
  if (!filterKey || filterKey === 'range') return true;

  const jClass = getExclusiveJugendClass(member.birthDate, seasonStartYear);

  if (filterKey === 'adult') {
    return jClass === 'adult';
  }

  if (filterKey.startsWith('J')) {
    return jClass === filterKey;
  }

  if (filterKey.startsWith('M')) {
    if (!isFemaleGender(member)) return false;
    const want = `J${filterKey.slice(1)}`;
    return jClass === want;
  }

  return true;
}

/**
 * Anzeige in der Liste: Jungen nur J…; Mädchen J… und M…
 */
export function formatMemberTtAgeClassLabels(member, seasonStartYear) {
  const j = getExclusiveJugendClass(member.birthDate, seasonStartYear);
  if (j === null) return { primary: null, secondary: null };
  if (j === 'adult') return { primary: 'adult', secondary: null };
  if (isFemaleGender(member)) {
    const m = `M${j.slice(1)}`;
    return { primary: j, secondary: m };
  }
  return { primary: j, secondary: null };
}

export function formatSeasonSlash(seasonStartYear) {
  const y = seasonStartYear;
  return `${y}/${String(y + 1).slice(-2)}`;
}

export { YOUTH_BANDS };
