import { BrowserRouter, Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { Toaster } from 'react-hot-toast';
import { AuthProvider, useAuth } from './context/AuthContext';
import Sidebar from './components/Sidebar';
import Header from './components/Header';
import Profile from './pages/Profile';
import { lazy, Suspense, useEffect, useState } from 'react';
import { defaultRouteForAppMode, isStandalonePwa } from './utils/appMode';
import './styles/pwa.css';

const Login = lazy(() => import('./pages/Login'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Projects = lazy(() => import('./pages/Projects'));
const ProjectDetail = lazy(() => import('./pages/ProjectDetail'));
const Tasks = lazy(() => import('./pages/Tasks'));
const Kanban = lazy(() => import('./pages/Kanban'));
const Backlog = lazy(() => import('./pages/Backlog'));
const Sprints = lazy(() => import('./pages/Sprints'));
const Team = lazy(() => import('./pages/Team'));
const MeetingList = lazy(() => import('./pages/MeetingList'));
const Files = lazy(() => import('./pages/Files'));
const Reports = lazy(() => import('./pages/Reports'));
const Notifications = lazy(() => import('./pages/Notifications'));
const Roles = lazy(() => import('./pages/Roles'));
const Settings = lazy(() => import('./pages/Settings'));
const Organization = lazy(() => import('./pages/Organization'));
const SprintWorkspace = lazy(() => import('./pages/SprintWorkspace'));
const MeetingWorkspace = lazy(() => import('./pages/MeetingWorkspace'));
const PwaLayout = lazy(() => import('./pwa/PwaLayout'));

function PageFallback() {
  return <div className="page-loading" role="status">در حال بارگذاری...</div>;
}

function AppLayout({ children, title }) {
  const [collapsed, setCollapsed] = useState(false);
  const [mobileNavOpen, setMobileNavOpen] = useState(false);

  useEffect(() => {
    const handleKeyDown = (event) => {
      if (event.key === 'Escape') setMobileNavOpen(false);
    };
    const handleResize = () => {
      if (window.innerWidth > 768) setMobileNavOpen(false);
    };
    document.addEventListener('keydown', handleKeyDown);
    window.addEventListener('resize', handleResize);
    return () => {
      document.removeEventListener('keydown', handleKeyDown);
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  const toggleMobileNav = () => {
    setCollapsed(false);
    setMobileNavOpen((current) => !current);
  };

  return (
    <div className="layout">
      <Sidebar collapsed={collapsed} onToggle={() => setCollapsed(!collapsed)} mobileOpen={mobileNavOpen} onMobileClose={() => setMobileNavOpen(false)} />
      {mobileNavOpen && <button type="button" className="mobile-sidebar-overlay" aria-label="بستن منوی اصلی" onClick={() => setMobileNavOpen(false)} />}
      <div className={`main-content ${collapsed ? 'sidebar-collapsed' : ''}`}>
        <Header title={title} collapsed={collapsed} mobileNavOpen={mobileNavOpen} onToggleMobileNav={toggleMobileNav} />
        <div className="main-inner">{children}</div>
      </div>
    </div>
  );
}

function DefaultAppRoute() {
  const route = defaultRouteForAppMode();
  if (route === '/pwa') return <Navigate to="/pwa" replace />;
  return <AppLayout title="داشبورد"><Dashboard /></AppLayout>;
}

function AppRoutes() {
  const { user, loading } = useAuth();
  const location = useLocation();
  if (loading) return <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>در حال بارگذاری...</div>;

  if (!user) {
    return (
      <Suspense fallback={<PageFallback />}>
        <Routes>
          <Route path="/login" element={<Login />} />
          <Route path="*" element={<Navigate to="/login" replace />} />
        </Routes>
      </Suspense>
    );
  }

  const isPwaPath = location.pathname === '/pwa' || location.pathname.startsWith('/pwa/');
  if (isStandalonePwa() && !isPwaPath) return <Navigate to="/pwa" replace />;

  return (
    <Suspense fallback={<PageFallback />}>
      <Routes>
        <Route path="/login" element={<Navigate to={defaultRouteForAppMode()} replace />} />
        <Route path="/pwa/*" element={<PwaLayout />} />
        <Route path="/" element={<DefaultAppRoute />} />
        <Route path="/projects" element={<AppLayout title="پروژه‌ها"><Projects /></AppLayout>} />
        <Route path="/projects/:id" element={<AppLayout title="جزئیات پروژه"><ProjectDetail /></AppLayout>} />
        <Route path="/tasks" element={<AppLayout title="تسک‌ها"><Tasks /></AppLayout>} />
        <Route path="/kanban" element={<AppLayout title="برد کاری"><Kanban /></AppLayout>} />
        <Route path="/backlog" element={<AppLayout title="بک‌لاگ"><Backlog /></AppLayout>} />
        <Route path="/sprints" element={<AppLayout title="اسپرینت‌ها"><Sprints /></AppLayout>} />
        <Route path="/sprints/:id/workspace" element={<AppLayout title="مرکز فرمان Sprint"><SprintWorkspace /></AppLayout>} />
        <Route path="/team" element={<AppLayout title="اعضای تیم"><Team /></AppLayout>} />
        <Route path="/meetings" element={<AppLayout title="جلسات"><MeetingList /></AppLayout>} />
        <Route path="/meetings/:id/workspace" element={<AppLayout title="فضای کاری جلسه"><MeetingWorkspace /></AppLayout>} />
        <Route path="/files" element={<AppLayout title="فایل‌ها"><Files /></AppLayout>} />
        <Route path="/reports" element={<AppLayout title="گزارش‌ها"><Reports /></AppLayout>} />
        <Route path="/notifications" element={<AppLayout title="اعلان‌ها"><Notifications /></AppLayout>} />
        <Route path="/roles" element={<AppLayout title="نقش‌ها و دسترسی‌ها"><Roles /></AppLayout>} />
        <Route path="/organization" element={<AppLayout title="ساختار سازمانی"><Organization /></AppLayout>} />
        <Route path="/settings" element={<AppLayout title="تنظیمات"><Settings /></AppLayout>} />
        <Route path="/profile" element={<AppLayout title="پروفایل کاربری"><Profile /></AppLayout>} />
        <Route path="*" element={<Navigate to="/" />} />
      </Routes>
    </Suspense>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthProvider>
        <Toaster position="top-center" toastOptions={{ className: 'app-toast' }} />
        <AppRoutes />
      </AuthProvider>
    </BrowserRouter>
  );
}
