import { useEffect, useState } from 'react'
import { BrowserRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom'
import useAuthStore from './store/authStore'
import AppLayout from './layouts/AppLayout'
import client from './api/client'

// Auth / setup
import LoginPage from './pages/LoginPage'
import SetupWizard from './pages/SetupWizard'

// Standalone (no shell)
import KdsPage from './pages/KdsPage'

// Operation
import DashboardPage from './pages/DashboardPage'
import TablesPage from './pages/TablesPage'
import OrderDetailPage from './pages/OrderDetailPage'
import OnlineOrdersPage from './pages/OnlineOrdersPage'

// CRM
import ContactsPage from './pages/crm/ContactsPage'
import CustomersPage from './pages/crm/CustomersPage'

// Financials
import ExpensesPage from './pages/financials/ExpensesPage'
import TabsPage from './pages/financials/TabsPage'

// Management
import ProductsPage from './pages/Management/ProductsPage'
import TablesConfigPage from './pages/Management/TablesConfigPage'
import StaffPage from './pages/Management/StaffPage'
import ManagementSchedulePage from './pages/Management/SchedulePage'
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
import PricingPage from './pages/Management/PricingPage'

// Inventory
import ThrowawaysPage from './pages/inventory/ThrowawaysPage'
import StockPage from './pages/inventory/StockPage'

// Reports
import TodayPage from './pages/reports/TodayPage'
import StorePage from './pages/reports/StorePage'
import StaffReportPage from './pages/reports/StaffReportPage'
import ProductsReportPage from './pages/reports/ProductsReportPage'
import PrepZonesPage from './pages/reports/PrepZonesPage'
import ExpensesReportPage from './pages/reports/ExpensesReportPage'
import TechnicalPage from './pages/reports/TechnicalPage'
import MiscPage from './pages/reports/MiscPage'

// Other
import AppsPage from './pages/AppsPage'
import PhonePage from './pages/PhonePage'
import SettingsPage from './pages/Settings/SettingsPage'
import NotesPage from './pages/NotesPage'
import PermissionGuard from './components/PermissionGuard'

function Spinner() {
  return (
    <div className="min-h-screen bg-slate-50 flex items-center justify-center">
      <div className="w-6 h-6 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
    </div>
  )
}

function AuthRehydrator({ children }) {
  const { token, user, rehydrate, logout } = useAuthStore()
  const [ready, setReady] = useState(false)

  useEffect(() => {
    if (token && !user) {
      client.get('/api/auth/me')
        .then(r => { rehydrate(r.data, token) })
        .catch(() => { logout() })
        .finally(() => setReady(true))
    } else {
      setReady(true)
    }
  }, []) // intentionally runs once on mount

  if (!ready) return <Spinner />
  return children
}

function RequireAuth({ children }) {
  const token = useAuthStore(s => s.token)
  return token ? children : <Navigate to="/login" replace />
}

function SetupGuard({ children }) {
  const [checked, setChecked] = useState(false)
  const navigate = useNavigate()

  useEffect(() => {
    client.get('/api/setup/status')
      .then(({ data }) => {
        if (data.needs_setup) navigate('/setup', { replace: true })
      })
      .catch(() => {})
      .finally(() => setChecked(true))
  }, [navigate])

  if (!checked) return <Spinner />
  return children
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthRehydrator>
        <Routes>
          <Route path="/setup" element={<SetupWizard />} />
          <Route path="/login" element={<SetupGuard><LoginPage /></SetupGuard>} />
          <Route path="/kds" element={<RequireAuth><KdsPage /></RequireAuth>} />

          <Route path="/" element={<RequireAuth><AppLayout /></RequireAuth>}>
            <Route index element={<Navigate to="/dashboard" replace />} />

            {/* ── Operation ── */}
            <Route path="dashboard"     element={<DashboardPage />} />
            <Route path="tables"        element={<TablesPage />} />
            <Route path="online-orders" element={<OnlineOrdersPage />} />
            <Route path="orders/:orderId" element={<OrderDetailPage />} />

            {/* ── CRM ── */}
            <Route path="crm/contacts"  element={<ContactsPage />} />
            <Route path="crm/customers" element={<CustomersPage />} />

            {/* ── Financials ── */}
            <Route path="financials/expenses" element={<ExpensesPage />} />
            <Route path="financials/tabs"     element={<TabsPage />} />

            {/* ── Management (Headquarters) ── */}
            <Route path="management/products"   element={<PermissionGuard perm="manageMenu"><ProductsPage /></PermissionGuard>} />
            <Route path="management/tables"     element={<PermissionGuard perm="manageTables"><TablesConfigPage /></PermissionGuard>} />
            <Route path="management/staff"      element={<PermissionGuard perm="manageStaff"><StaffPage /></PermissionGuard>} />
            <Route path="management/schedule"   element={<PermissionGuard perm="manageStaff"><ManagementSchedulePage /></PermissionGuard>} />
            <Route path="management/prep-zones" element={<PermissionGuard perm="manageMenu"><PrepZonesConfigPage /></PermissionGuard>} />
            <Route path="management/pricing"    element={<PermissionGuard perm="manageMenu"><PricingPage /></PermissionGuard>} />

            {/* ── Inventory ── */}
            <Route path="inventory/throwaways" element={<ThrowawaysPage />} />
            <Route path="inventory/stock"      element={<StockPage />} />

            {/* ── Reports (Overwatch) ── */}
            <Route path="reports/today"      element={<PermissionGuard perm="viewReports"><TodayPage /></PermissionGuard>} />
            <Route path="reports/store"      element={<PermissionGuard perm="viewReports"><StorePage /></PermissionGuard>} />
            <Route path="reports/staff"      element={<PermissionGuard perm="viewReports"><StaffReportPage /></PermissionGuard>} />
            <Route path="reports/products"   element={<PermissionGuard perm="viewReports"><ProductsReportPage /></PermissionGuard>} />
            <Route path="reports/prep-zones" element={<PermissionGuard perm="viewReports"><PrepZonesPage /></PermissionGuard>} />
            <Route path="reports/expenses"   element={<PermissionGuard perm="viewReports"><ExpensesReportPage /></PermissionGuard>} />
            <Route path="reports/technical"  element={<PermissionGuard perm="viewReports"><TechnicalPage /></PermissionGuard>} />
            <Route path="reports/misc"       element={<PermissionGuard perm="viewReports"><MiscPage /></PermissionGuard>} />

            {/* ── Apps & Settings ── */}
            <Route path="apps"            element={<AppsPage />} />
            <Route path="apps/phone"      element={<PhonePage />} />
            <Route path="settings" element={<PermissionGuard perm="manageSettings"><SettingsPage /></PermissionGuard>} />
            <Route path="notes"    element={<NotesPage />} />

            {/* ── Legacy redirects (old URLs → new locations) ── */}
            <Route path="contacts"   element={<Navigate to="/crm/contacts"       replace />} />
            <Route path="customers"  element={<Navigate to="/crm/customers"      replace />} />
            <Route path="expenses"   element={<Navigate to="/financials/expenses" replace />} />
            <Route path="tabs"       element={<Navigate to="/financials/tabs"     replace />} />
            <Route path="waste"      element={<Navigate to="/inventory/throwaways" replace />} />
            <Route path="schedule"   element={<Navigate to="/management/schedule" replace />} />
            <Route path="management" element={<Navigate to="/management/products" replace />} />
            <Route path="reports"    element={<Navigate to="/reports/today"       replace />} />
          </Route>
        </Routes>
      </AuthRehydrator>
    </BrowserRouter>
  )
}
