'use client'
import { useState, useEffect, MouseEvent } from 'react'

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

export default function Appearance() {
  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: MouseEvent<HTMLAnchorElement>) {
    ev.preventDefault()

    const current = appearance ?? getDefaultTheme()

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

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

    }
  }

  return (
    <a id="darkLightToggle" href="#" onClick={toggleDarkMode}>appearance</a>
  )
}

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