const API_URL =
    'https://script.google.com/macros/s/AKfycbyuVF4ShwcVrEtkMXAumI8wx4ou9XsM43hIdcMhGrpmy24noQ0faO5eRdaQEpFat3ST/exec'

export async function fetchKaraokeData() {
    const response = await fetch(API_URL)
    if (!response.ok) {
        throw new Error(`Erro na rede: ${response.status} ${response.statusText}`)
    }
    return response.json()
}

export function calculateAllEstimates(data) {
    const durationPerPersonMs = (5 * 60 + 33) * 1000
    let estimatedTime = new Date()

    return data.map((item, index) => {
        if (index > 0) {
            estimatedTime = new Date(estimatedTime.getTime() + durationPerPersonMs)
        }

        const peopleBeforeInFullList = index
        let peopleRemainingText = ''
        if (peopleBeforeInFullList === 0) {
            peopleRemainingText = 'Próximo a cantar'
        } else if (peopleBeforeInFullList === 1) {
            peopleRemainingText = 'Falta 1 pessoa para cantar'
        } else {
            peopleRemainingText = `Faltam ${peopleBeforeInFullList} pessoas para cantar`
        }

        const hours = String(estimatedTime.getHours()).padStart(2, '0')
        const minutes = String(estimatedTime.getMinutes()).padStart(2, '0')

        return {
            ...item,
            estimatedTime: `${hours}:${minutes}`,
            peopleRemaining: peopleRemainingText,
        }
    })
}
