<script lang="ts">
  import { onMount } from 'svelte'
  import IconSun from '~icons/lucide/sun'
  import IconMoon from '~icons/lucide/moon'

  let mounted = $state(false)

  onMount(() => {
    mounted = true

    const theme = (() => {
      const localStorageTheme = localStorage?.getItem('theme') ?? ''
      if (['dark', 'light'].includes(localStorageTheme)) {
        return localStorageTheme
      }
      if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
        return 'dark'
      }
      return 'light'
    })()

    if (theme === 'light') {
      document.documentElement.classList.remove('dark')
    } else {
      document.documentElement.classList.add('dark')
    }
    window.localStorage.setItem('theme', theme)

    const handleAfterSwap = () => {
      const storedTheme = localStorage.getItem('theme')
      const element = document.documentElement

      element.classList.add('disable-transitions')
      window.getComputedStyle(element).getPropertyValue('opacity')

      if (storedTheme === 'dark') {
        element.classList.add('dark')
      } else {
        element.classList.remove('dark')
      }

      requestAnimationFrame(() => {
        element.classList.remove('disable-transitions')
      })
    }

    document.addEventListener('astro:after-swap', handleAfterSwap)

    return () => {
      document.removeEventListener('astro:after-swap', handleAfterSwap)
    }
  })

  function toggleTheme() {
    const element = document.documentElement
    element.classList.toggle('dark')
    const isDark = element.classList.contains('dark')
    localStorage.setItem('theme', isDark ? 'dark' : 'light')
  }

  function handleToggle(event: MouseEvent) {
    const button = event.currentTarget as HTMLButtonElement
    const rect = button.getBoundingClientRect()
    const x = rect.left + rect.width / 2
    const y = rect.top + rect.height / 2

    // Check if View Transitions API is supported
    if (!document.startViewTransition) {
      toggleTheme()
      return
    }

    // Set CSS custom properties for the animation origin
    document.documentElement.style.setProperty('--toggle-x', `${x}px`)
    document.documentElement.style.setProperty('--toggle-y', `${y}px`)

    // Start the view transition
    document.startViewTransition(() => {
      toggleTheme()
    })
  }
</script>

<button
  onclick={(e) => handleToggle(e)}
  class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium transition-[color,box-shadow] disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 bg-secondary text-secondary-foreground hover:bg-secondary/80 size-9 cursor-pointer"
  title="Toggle theme"
>
  <IconSun class="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90" />
  <IconMoon class="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0" />
  <span class="sr-only">Toggle theme</span>
</button>
