import { Routes, Route, Navigate, useNavigate, useLocation } from 'react-router-dom'
import useAuthStore from './store/authStore'
import LoginPage from './pages/LoginPage'
import SitesPage from './pages/SitesPage'
import SiteDetailPage from './pages/SiteDetailPage'
import RegisterSitePage from './pages/RegisterSitePage'

function Layout({ children }) {
  const { logout } = useAuthStore()
  const navigate = useNavigate()
  const location = useLocation()

  function handleLogout() {
    logout()
    navigate('/login', { replace: true })
  }

  return (
    <div className="min-h-screen bg-gray-950">
      <nav className="border-b border-gray-800 bg-gray-950/80 backdrop-blur sticky top-0 z-10">
        <div className="max-w-5xl mx-auto px-4 h-12 flex items-center justify-between">
          <button
            onClick={() => navigate('/sites')}
            className="flex items-center gap-2 text-white font-semibold text-sm"
          >
            <div className="w-6 h-6 bg-cyan-500/20 border border-cyan-500/40 rounded flex items-center justify-center">
              <svg className="w-3 h-3 text-cyan-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
              </svg>
            </div>
            Sysadmin
          </button>

          <div className="flex items-center gap-4">
            <span className={`text-xs px-2.5 py-1 rounded font-mono ${
              location.pathname.startsWith('/sites') ? 'text-cyan-400 bg-cyan-500/10' : 'text-gray-500'
            }`}>
              Sites
            </span>
            <button
              onClick={handleLogout}
              className="text-xs text-gray-500 hover:text-gray-300 transition-colors"
            >
              Sign out
            </button>
          </div>
        </div>
      </nav>

      <main className="max-w-5xl mx-auto px-4 py-6">
        {children}
      </main>
    </div>
  )
}

function RequireAuth({ children }) {
  const { token } = useAuthStore()
  if (!token) return <Navigate to="/login" replace />
  return children
}

export default function App() {
  const { token } = useAuthStore()

  return (
    <Routes>
      <Route path="/login" element={token ? <Navigate to="/sites" replace /> : <LoginPage />} />
      <Route path="/sites" element={
        <RequireAuth><Layout><SitesPage /></Layout></RequireAuth>
      } />
      <Route path="/sites/register" element={
        <RequireAuth><Layout><RegisterSitePage /></Layout></RequireAuth>
      } />
      <Route path="/sites/:siteId" element={
        <RequireAuth><Layout><SiteDetailPage /></Layout></RequireAuth>
      } />
      <Route path="*" element={<Navigate to="/sites" replace />} />
    </Routes>
  )
}
