<script>
  function getInitialColorMode() {
    const selectedColorPreference = window.localStorage.getItem('color-mode')
    const hasSelectedColorPreference = typeof selectedColorPreference === 'string'
    if (hasSelectedColorPreference) {
      return selectedColorPreference
    }

    // If no color has been selected, we check the system color mode
    const mql = window.matchMedia('(prefers-color-scheme: dark)')
    const hasMediaQueryPreference = typeof mql.matches === 'boolean'

    if (hasMediaQueryPreference) {
      return mql.matches ? 'dark' : 'light'
    }

    // If we could not determine a preference, we default to the light mode
    return 'light'
  }

  const initialColorMode = getInitialColorMode()
  document.documentElement.classList.add(initialColorMode)
  document.documentElement.style.setProperty('color-scheme', initialColorMode)
</script>
