// src/Router.jsx
import React from 'react';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import AppLayout from '@/shared/components/layout/AppLayout';
import LoginPage from '@/features/auth/pages/LoginPage';
import RegisterPage from '@/features/auth/pages/RegisterPage';
import DashboardPage from '@/features/dashboard/pages/DashboardPage';
import ProjectsPage from '@/features/projects/pages/ProjectsPage';
import ProjectBoardPage from '@/features/projects/pages/ProjectBoardPage';
import TasksPage from '@/features/tasks/pages/TasksPage';
import TeamPage from '@/features/team/pages/TeamPage';

export default function Router({ user }) {
  const location = useLocation();

  // Detect token or register route directly from location
  const hasInviteToken = location.search.includes('token=') || window.location.hash.includes('token=');
  const isRegisterRoute = location.pathname.startsWith('/register') || hasInviteToken;

  return (
    <Routes>
      {/* 🔓 PUBLIC ROUTES */}
      <Route path="/register" element={<RegisterPage />} />
      <Route 
        path="/login" 
        element={!user ? <LoginPage /> : <Navigate to="/dashboard" replace />} 
      />

      {/* 🔒 PROTECTED ROUTES */}
      {user && !hasInviteToken ? (
        <Route path="/" element={<AppLayout />}>
          <Route index element={<Navigate to="/dashboard" replace />} />
          <Route path="dashboard" element={<DashboardPage />} />
          <Route path="projects" element={<ProjectsPage />} />
          <Route path="projects/:id" element={<ProjectBoardPage />} />
          <Route path="projects/:id/board" element={<ProjectBoardPage />} />
          <Route path="tasks" element={<TasksPage />} />
          <Route path="team" element={<TeamPage />} />
        </Route>
      ) : null}

      {/* 🔄 CATCH-ALL FALLBACK */}
      <Route
        path="*"
        element={
          isRegisterRoute ? (
            <RegisterPage />
          ) : user ? (
            <Navigate to="/dashboard" replace />
          ) : (
            <Navigate to="/login" replace />
          )
        }
      />
    </Routes>
  );
}