export function setCookie(name: string, value: string, days = 30) {
    const expires = new Date()
    expires.setTime(expires.getTime() + days * 24 * 60 * 60 * 1000)
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${expires.toUTCString()}; path=/`
}

export function getCookie(name: string): string | null {
    const nameEQ = `${name}=`
    const cookies = document.cookie.split(';')
    for (let cookie of cookies) {
        cookie = cookie.trim()
        if (cookie.indexOf(nameEQ) === 0) {
            return decodeURIComponent(cookie.substring(nameEQ.length))
        }
    }
    return null
}

export function saveCurrentEpisodeId(id: string) {
    setCookie('qishier_current_episode_id', id, 30)
}

export function getCurrentEpisodeId() {
    return getCookie('qishier_current_episode_id')
}

export function saveEpisodeProgress(id: string, seconds: number) {
    setCookie(`qishier_progress_${id}`, String(Math.floor(seconds)), 30)
}

export function getEpisodeProgress(id: string): number {
    const value = getCookie(`qishier_progress_${id}`)
    if (!value) return 0
    const num = Number(value)
    return Number.isNaN(num) ? 0 : num
}
