const COOKIE_NAME = 'e_ticket_consent'
const COOKIE_DAYS = 365

function getCookie(name) {
    const match = new RegExp('(^| )' + name + '=([^;]+)').exec(document.cookie)

    return match ? match[2] : null
}

function setCookie(name, value, days) {
    const date = new Date()
    date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000)
    document.cookie = name + '=' + value + ';expires=' + date.toUTCString() + ';path=/;SameSite=Lax;Secure'
}

export function initCookieConsent() {
    const consent = getCookie(COOKIE_NAME)

    if ('accepted' === consent || 'refused' === consent) {
        return
    }

    const banner = document.getElementById('cookie-banner')
    if (!banner) {
        return
    }

    banner.classList.remove('hidden')

    const acceptBtn = document.getElementById('cookie-accept')
    const refuseBtn = document.getElementById('cookie-refuse')

    if (acceptBtn) {
        acceptBtn.addEventListener('click', () => {
            setCookie(COOKIE_NAME, 'accepted', COOKIE_DAYS)
            banner.classList.add('hidden')
        })
    }

    if (refuseBtn) {
        refuseBtn.addEventListener('click', () => {
            setCookie(COOKIE_NAME, 'refused', COOKIE_DAYS)
            banner.classList.add('hidden')
        })
    }
}
