import { useState, useEffect } from 'react'
import Link from 'next/link'
import '~/styles/layout.css'

type AppearanceMode = undefined | 'light' | 'dark'

export default function Layout({ Component, pageProps }) {
  const [appearance, setAppearance] = useState<AppearanceMode>(undefined)

  useEffect(() => {
    if (appearance !== undefined) {
      document.body.parentElement.classList.remove('light')
      document.body.parentElement.classList.remove('dark')
      document.body.parentElement.classList.add(appearance)
    }
  }, [appearance])

  function toggleDarkMode(ev) {
    ev.preventDefault()

    const current = appearance ?? getDefaultTheme()

    switch (current) {
      case 'light':
        setAppearance('dark')
        return

      case 'dark':
        setAppearance('light')
        return

    }
  }

  return (
    <>
      <header>
        <p className="site-title"><Link href="/">ashen.earth</Link></p>
        <span className="subtitle">
          code ramblings and technical oddities
        </span>
        <nav>
          <a id="darkLightToggle" href="#" onClick={toggleDarkMode}>appearance</a>
          <a target="_blank" href="https://github.com/ashen-dawn">github</a>
        </nav>
      </header>
      <main>
        <Component {...pageProps} />
      </main>
      <noscript><style>{'#darkLightToggle { display: none; }'}</style></noscript>
    </>
  )
}

function getDefaultTheme(): 'light' | 'dark' {
  const { matches: lightTheme } = window.matchMedia('(prefers-color-scheme: light)')
  return lightTheme ? 'light' : 'dark'
}
