import { useLayoutEffect, useState } from "react"

function getInitialIsDark() {
  try {
    const saved = localStorage.getItem("theme")
    if (saved === "dark") return true
    if (saved === "light") return false
  } catch {}
  return window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false
}

export default function ThemeToggle() {
  const [isDark, setIsDark] = useState<boolean>(() => getInitialIsDark())

  useLayoutEffect(() => {
    document.documentElement.classList.toggle("dark", isDark)
    document.documentElement.style.colorScheme = isDark ? "dark" : "light"
  }, [isDark])

  const toggle = () => {
    setIsDark((prev) => {
      const next = !prev
      try {
        localStorage.setItem("theme", next ? "dark" : "light")
      } catch {}
      return next
    })
  }

  return (
    <button
      type="button"
      onClick={toggle}
      aria-label="Tema değiştir"
      className="relative inline-flex h-9 w-16 items-center rounded-full border border-border bg-surface-2 transition-colors focus:outline-none focus:ring-2 focus:ring-[var(--color-primary-ring)]"
    >
      <span
        className={`absolute left-1 inline-flex h-7 w-7 items-center justify-center rounded-full bg-surface shadow transition-transform ${
          isDark ? "translate-x-7" : "translate-x-0"
        }`}
      >
        <span className="text-sm">{isDark ? "🌙" : "☀️"}</span>
      </span>

      <span className="w-full px-2 text-xs font-semibold text-text-muted flex justify-between">
        <span className={isDark ? "opacity-40" : "opacity-100"}></span>
        <span className={isDark ? "opacity-100" : "opacity-40"}></span>
      </span>
    </button>
  )
}
