import { useEffect, useState } from 'react'
import { useAuthStore } from '../store/authStore'

/** Put your file in `public/one-island-resort.jpeg` (rename from "one island resort.jpeg" if needed). */
const BRAND_LOGO_SRC = '/one-island-resort.jpeg'

export default function Topbar() {
  const logout = useAuthStore((s) => s.logout)
  const authUser = useAuthStore((s) => s.username)
  const [clock, setClock] = useState('')
  const [todayLabel, setTodayLabel] = useState('')
  const [logoOk, setLogoOk] = useState(true)
  const [theme, setTheme] = useState(() => localStorage.getItem('hotel-pos-theme') || 'dark')

  useEffect(() => {
    const tick = () => {
      setClock(
        new Date().toLocaleTimeString('en-MY', {
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
        })
      )
      setTodayLabel(
        new Date().toLocaleDateString('en-MY', {
          weekday: 'short',
          day: 'numeric',
          month: 'short',
          year: 'numeric',
        })
      )
    }
    tick()
    const id = setInterval(tick, 1000)
    return () => clearInterval(id)
  }, [])

  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme)
    localStorage.setItem('hotel-pos-theme', theme)
  }, [theme])

  const toggleTheme = () => setTheme((t) => (t === 'dark' ? 'light' : 'dark'))

  return (
    <div className="topbar">
      <div className="brand brand-logo-only">
        {logoOk ? (
          <img
            src={BRAND_LOGO_SRC}
            alt=""
            className="brand-logo"
            onError={() => setLogoOk(false)}
          />
        ) : (
          <div className="brand-icon brand-icon-fallback" aria-hidden>
            🏝
          </div>
        )}
      </div>
      <div className="topbar-right">
        <button
          type="button"
          className="tb-theme-toggle"
          onClick={toggleTheme}
          aria-label={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
          title={`Switch to ${theme === 'dark' ? 'light' : 'dark'} theme`}
        >
          <span className="tb-theme-icon" aria-hidden>
            {theme === 'dark' ? '🌙' : '☀️'}
          </span>
          <span className="tb-theme-label">{theme === 'dark' ? 'Dark' : 'Light'}</span>
          <span className={`tb-theme-knob${theme === 'light' ? ' on' : ''}`} aria-hidden />
        </button>
        <div className="tb-chip tb-clock">{clock}</div>
        <div className="tb-chip live">● System Online</div>
        <div className="tb-chip">{todayLabel}</div>
        <div className="tb-chip">{authUser || 'Staff'}</div>
        <button type="button" className="tb-chip tb-logout" onClick={() => logout()}>
          Log out
        </button>
      </div>
    </div>
  )
}
