'use client'
import { useEffect, useState } from 'react'

export default function ThemeToggle() {
  const [dark, setDark] = useState(true)

  useEffect(() => {
    // Read from localStorage (set by anti-flash script in layout)
    const saved = localStorage.getItem('fibe-theme')
    setDark(saved !== 'light')
  }, [])

  const toggle = () => {
    const next = !dark
    setDark(next)
    if (next) {
      document.documentElement.removeAttribute('data-theme')
      localStorage.setItem('fibe-theme', 'dark')
    } else {
      document.documentElement.setAttribute('data-theme', 'light')
      localStorage.setItem('fibe-theme', 'light')
    }
  }

  return (
    <button
      onClick={toggle}
      aria-label={dark ? 'Switch to light mode' : 'Switch to dark mode'}
      title={dark ? 'Light mode' : 'Dark mode'}
      className="w-8 h-8 flex items-center justify-center rounded-lg transition-all hover:scale-110"
      style={{
        color: dark ? 'rgba(167,139,250,0.7)' : 'rgba(124,58,237,0.7)',
        background: dark ? 'rgba(139,92,246,0.1)' : 'rgba(124,58,237,0.08)',
        border: dark ? '1px solid rgba(139,92,246,0.2)' : '1px solid rgba(124,58,237,0.18)',
      }}
    >
      {dark ? (
        // Sun icon
        <svg width="15" height="15" viewBox="0 0 15 15" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
          <circle cx="7.5" cy="7.5" r="2.5" />
          <line x1="7.5" y1="1" x2="7.5" y2="2.5" />
          <line x1="7.5" y1="12.5" x2="7.5" y2="14" />
          <line x1="1" y1="7.5" x2="2.5" y2="7.5" />
          <line x1="12.5" y1="7.5" x2="14" y2="7.5" />
          <line x1="2.93" y1="2.93" x2="3.99" y2="3.99" />
          <line x1="11.01" y1="11.01" x2="12.07" y2="12.07" />
          <line x1="2.93" y1="12.07" x2="3.99" y2="11.01" />
          <line x1="11.01" y1="3.99" x2="12.07" y2="2.93" />
        </svg>
      ) : (
        // Moon icon
        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 9A6 6 0 0 1 5 2a6 6 0 1 0 7 7z" />
        </svg>
      )}
    </button>
  )
}
