import { type JSX } from "react"
import Image from "next/image"
import { useEffect, useState } from "react"
import clsx from "clsx"

export default function LogoBox({ className }: { className?: string }): JSX.Element {
  const [isDarkMode, setIsDarkMode] = useState<boolean>(false)
  const [mounted, setMounted] = useState(false)

  // Set up a theme listener that will update in real-time
  useEffect(() => {
    // Initial check
    setMounted(true)
    checkTheme()

    // Set up the MutationObserver to watch for class changes on the html element
    const observer = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        if (mutation.attributeName === "class") {
          checkTheme()
        }
      })
    })

    // Start observing the html element for class changes
    observer.observe(document.documentElement, { attributes: true })

    // Clean up the observer when component unmounts
    return () => observer.disconnect()
  }, [])

  // Function to check the current theme
  const checkTheme = () => {
    const isDark = document.documentElement.classList.contains("dark")
    setIsDarkMode(isDark)
  }

  // Avoid hydration mismatch
  if (!mounted) {
    return (
      <div className={clsx("block h-11", className)}>
        <div className="flex justify-start items-center h-full px-4 mt-1">
          <div className="h-full w-60" />
        </div>
      </div>
    )
  }
  return (
    <div className={clsx("block h-11", className)}>
      <div className="flex justify-start items-center h-full px-4 mt-1">
        <Image
          src={isDarkMode ? "/images/codeflash_darkmode.svg" : "/images/codeflash_light.svg"}
          alt="Codeflash Logo"
          className="h-full w-60"
          width={20}
          height={20}
          priority
        />
      </div>
    </div>
  )
}
