(() => {
    let appearance = Number(localStorage.getItem('appearance') || 0)
    const htmlElement = document.documentElement

    const applyAppearance = () => {
        htmlElement.classList.remove('dark', 'light')
        if (appearance === 2) {
            htmlElement.classList.add('dark')
        } else if (appearance === 1) {
            htmlElement.classList.add('light')
        } else {
            htmlElement.classList.add(
                window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
            )
        }
    }

    // Apply the appearance initially
    applyAppearance()

    if (appearance === 0) {
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', applyAppearance)
        window.matchMedia('(prefers-color-scheme: light)').addEventListener('change', applyAppearance)
    }
})()
