import { computed, type Ref } from 'vue'
import type { Flight } from '@/Types/types'

export type CodeType = 'iata' | 'icao'

const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('')
const digits  = '0123456789'.split('')

export function getAllLetters(showNumbers: boolean): string[] {
    return showNumbers ? [...digits, ...letters] : letters
}

export function useAlphabetAirlines(
    flights: Ref<Flight[]>,
    codeType: Ref<CodeType>,
    showNumbers: Ref<boolean>,
) {
    const allLetters = computed(() => getAllLetters(showNumbers.value))

    const flightsByLetter = computed(() => {
        const map: Record<string, Flight[]> = {}

        for (const flight of flights.value) {
            const raw = codeType.value === 'iata'
                ? flight.airline?.iata_code
                : flight.airline?.icao_code

            const code = raw?.trim().toUpperCase()
            if (!code) continue

            const key = code[0]
            if (!allLetters.value.includes(key)) continue

                ;(map[key] ??= []).push(flight)
        }

        return map
    })

    const visitedLetters = computed(() => new Set(Object.keys(flightsByLetter.value)))

    return { flightsByLetter, visitedLetters, allLetters }
}
