<script is:inline>
  // Favicon theme switcher for system theme-based favicon updates, using external SVG file
  class FaviconThemeSwitcher {
    constructor() {
      this.faviconLink =
        document.querySelector('link[rel="icon"]') ||
        document.querySelector('link[rel="shortcut icon"]') ||
        document.querySelector('link[rel="apple-touch-icon"]')

      if (!this.faviconLink) {
        console.warn('Favicon link not found, skipping theme switcher')
        return
      }

      this.mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      this.svgUrl = '/favicon.svg'
      this.currentColor = null
      this.svgContent = null

      this.mediaQuery.addEventListener('change', () => this.updateFavicon())
      this.init()
    }

    async init() {
      if (!this.svgContent) {
        try {
          const res = await fetch(this.svgUrl)
          this.svgContent = await res.text()
        } catch (e) {
          console.warn('Failed to fetch favicon.svg:', e)
          return
        }
      }
      this.updateFavicon()
    }

    updateFavicon() {
      const color = this.mediaQuery.matches ? '#ccc' : '#111'
      if (this.currentColor === color) return
      this.currentColor = color
      this.updateFaviconColor(color)
    }

    updateFaviconColor(color) {
      if (!this.svgContent) return
      try {
        const parser = new DOMParser()
        const doc = parser.parseFromString(this.svgContent, 'image/svg+xml')

        // Remove all <style> tags
        doc.querySelectorAll('style').forEach((style) => style.remove())

        // Recursively set fill attribute for all elements
        function setFillRecursively(node) {
          if (node.nodeType === 1) {
            // Element node
            node.setAttribute('fill', color)
            // Remove fill from style attribute if present
            if (node.hasAttribute('style')) {
              let style = node.getAttribute('style')
              style = style.replace(/fill\s*:\s*[^;]+;?/gi, '')
              node.setAttribute('style', style)
            }
            for (let i = 0; i < node.childNodes.length; i++) {
              setFillRecursively(node.childNodes[i])
            }
          }
        }
        setFillRecursively(doc.documentElement)

        const serializer = new XMLSerializer()
        const svg = serializer.serializeToString(doc)
        const blob = new Blob([svg], { type: 'image/svg+xml' })
        const blobUrl = URL.createObjectURL(blob)
        this.faviconLink.href = blobUrl
        if (this.previousBlobUrl) {
          URL.revokeObjectURL(this.previousBlobUrl)
        }
        this.previousBlobUrl = blobUrl
      } catch (e) {
        console.warn('Failed to update favicon color:', e)
      }
    }
  }

  // Initialize favicon theme switcher
  function init() {
    try {
      new FaviconThemeSwitcher()
    } catch (error) {
      console.warn('Failed to initialize favicon theme switcher:', error)
    }
  }

  // Initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init)
  } else {
    init()
  }

  // Re-initialize on Astro page loads
  document.addEventListener('astro:page-load', init)
</script>
