package de.tsschulz.tt_tagebuch.app.ui

import de.tsschulz.tt_tagebuch.shared.api.models.Member
import java.time.LocalDate
import java.time.Period
import java.time.ZoneId

/** Erstes Kalenderjahr der laufenden Spielzeit (Aug–Jul). */
fun getSeasonStartYearFromDateToday(zone: ZoneId = ZoneId.systemDefault()): Int {
    val d = LocalDate.now(zone)
    return if (d.monthValue >= 8) d.year else d.year - 1
}

fun formatSeasonSlash(seasonStartYear: Int): String =
    "${seasonStartYear}/${(seasonStartYear + 1).toString().takeLast(2)}"

fun getStichtagDate(seasonStartYear: Int, classNum: Int): LocalDate =
    LocalDate.of(seasonStartYear - (classNum - 1), 1, 1)

private fun parseBirth(member: Member): LocalDate? {
    val raw = member.birthDate?.trim()?.take(10) ?: return null
    return runCatching { LocalDate.parse(raw) }.getOrNull()
}

fun memberBirthLocalDate(member: Member): LocalDate? = parseBirth(member)

fun memberAgeYears(member: Member, today: LocalDate = LocalDate.now()): Int? {
    val b = parseBirth(member) ?: return null
    return Period.between(b, today).years
}

fun isFemaleGenderMember(member: Member): Boolean =
    member.gender?.trim()?.lowercase() == "female"

/**
 * Jugendklasse exklusiv (J9…J19) oder adult; `null` = kein gültiges Geburtsdatum.
 */
fun getExclusiveJugendClass(member: Member, seasonStartYear: Int): String? {
    val t = parseBirth(member)?.toEpochDay() ?: return null
    fun c(k: Int) = getStichtagDate(seasonStartYear, k).toEpochDay()
    val c9 = c(9)
    val c11 = c(11)
    val c13 = c(13)
    val c15 = c(15)
    val 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"
}

fun memberMatchesTtAgeClass(member: Member, filterKey: String, seasonStartYear: Int): Boolean {
    if (filterKey.isEmpty() || filterKey == "range") return true
    val jClass = getExclusiveJugendClass(member, seasonStartYear) ?: return false
    return when {
        filterKey == "adult" -> jClass == "adult"
        filterKey.startsWith("J") -> jClass == filterKey
        filterKey.startsWith("M") -> isFemaleGenderMember(member) && jClass == "J${filterKey.substring(1)}"
        else -> true
    }
}
