import Script from 'next/script'

const modeScript = `
  const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')

  const updateMode = () => {
    const isSystemDarkMode = darkModeMediaQuery.matches
    const isDarkMode = window.localStorage.isDarkMode === 'true' || (!('isDarkMode' in window.localStorage) && isSystemDarkMode)

    console.log(isSystemDarkMode)

    if (isDarkMode) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }

    if (isDarkMode === isSystemDarkMode) {
      delete window.localStorage.isDarkMode
    }
  }

  const disableTransitionsTemporarily = () => {
    document.documentElement.classList.add('[&_*]:!transition-none')
    window.setTimeout(() => {
      document.documentElement.classList.remove('[&_*]:!transition-none')
    }, 0)
  }

  const updateModeWithoutTransitions = () => {
    disableTransitionsTemporarily()
    updateMode()
  }

  updateMode()
  darkModeMediaQuery.addEventListener('change', updateModeWithoutTransitions)
  window.addEventListener('storage', updateModeWithoutTransitions)
`

export default function CommonHead() {
  return (
    <>
      <link
        rel="apple-touch-icon"
        sizes="180x180"
        href="/favicon/apple-touch-icon.png"
      />
      <link
        rel="icon"
        type="image/png"
        sizes="32x32"
        href="/favicon/favicon-32x32.png"
      />
      <link
        rel="icon"
        type="image/png"
        sizes="16x16"
        href="/favicon/favicon-16x16.png"
      />
      <link rel="manifest" href="/site.webmanifest" />

      <Script
        id="mode-script"
        dangerouslySetInnerHTML={{ __html: modeScript }}
      />

      <link
        rel="alternate"
        type="application/rss+xml"
        href={`${process.env.NEXT_PUBLIC_SITE_URL}/rss/feed.xml`}
      />
      <link
        rel="alternate"
        type="application/feed+json"
        href={`${process.env.NEXT_PUBLIC_SITE_URL}/rss/feed.json`}
      />
    </>
  )
}
