---
import { Button } from '@/components/ui/button'
import { Icon } from 'astro-icon/components'
---

<Button id="theme-toggle" variant="secondary" size="icon" title="Toggle theme">
  <Icon
    name="lucide:sun"
    class="size-4 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90"
  />
  <Icon
    name="lucide:moon"
    class="absolute size-4 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0"
  />
  <span class="sr-only">Toggle theme</span>
</Button>

<script>
  function handleToggleClick() {
    const element = document.documentElement

    element.classList.add('disable-transitions')
    element.classList.toggle('dark')

    window.getComputedStyle(element).getPropertyValue('opacity')

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

    const isDark = element.classList.contains('dark')
    localStorage.setItem('theme', isDark ? 'dark' : 'light')
  }

  function initThemeToggle() {
    const themeToggle = document.getElementById('theme-toggle')
    if (themeToggle) {
      themeToggle.addEventListener('click', handleToggleClick)
    }
  }

  initThemeToggle()

  document.addEventListener('astro:after-swap', () => {
    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')
    })

    initThemeToggle()
  })
</script>
