import { Routes, Route, Navigate } from 'react-router-dom'
import { Suspense, lazy } from 'react'
import { useAuthStore } from './store/authStore'
import { useMembershipStore } from './store/membershipStore'

// Landing page — eagerly loaded (first thing visitors see)
import LandingPage from './pages/public/LandingPage'
import CurisOsLandingPage from './pages/public/CurisOsLandingPage'
import { getBrand } from './branding'

// Layouts — lazy loaded
const DashboardLayout = lazy(() => import('./components/layouts/DashboardLayout'))
const AuthLayout = lazy(() => import('./components/layouts/AuthLayout'))

// Auth Pages
const LoginPage = lazy(() => import('./pages/auth/LoginPage'))
const RegisterPage = lazy(() => import('./pages/auth/RegisterPage'))
const AcceptInvitePage = lazy(() => import('./pages/auth/AcceptInvitePage'))
const InstagramCallbackPage = lazy(() => import('./pages/auth/InstagramCallbackPage'))
const FacebookCallbackPage = lazy(() => import('./pages/auth/FacebookCallbackPage'))

// Business Pages
const BusinessesPage = lazy(() => import('./pages/business/BusinessesPage'))
const BusinessDetailPage = lazy(() => import('./pages/business/BusinessDetailPage'))
const BotsPage = lazy(() => import('./pages/business/BotsPage'))
const NotificationsPage = lazy(() => import('./pages/business/NotificationsPage'))
const UserManagementPage = lazy(() => import('./pages/business/UserManagementPage'))
const GoogleBusinessProfilePage = lazy(() => import('./pages/business/GoogleBusinessProfilePage'))
const OperatorPage = lazy(() => import('./pages/business/OperatorPage'))
const IntelligenceSettingsPage = lazy(() => import('./pages/business/IntelligenceSettingsPage'))
const BusinessFeedPage = lazy(() => import('./pages/business/BusinessFeedPage'))
const WebsiteManagePage = lazy(() => import('./pages/business/WebsiteManagePage'))
const ResourceCalendarPage = lazy(() => import('./pages/business/ResourceCalendarPage'))

// Chatbot Pages
const ChatbotsPage = lazy(() => import('./pages/chatbots/ChatbotsPage'))
const ChatbotDetailPage = lazy(() => import('./pages/chatbots/ChatbotDetailPage'))
const ChatbotSettingsPage = lazy(() => import('./pages/chatbots/ChatbotSettingsPage'))
const UnifiedCalendarPage = lazy(() => import('./pages/chatbots/UnifiedCalendarPage'))
const WebhookSettingsPage = lazy(() => import('./pages/chatbots/WebhookSettingsPage'))
const PlaygroundPage = lazy(() => import('./pages/chatbots/PlaygroundPage'))
const DocumentsPage = lazy(() => import('./pages/chatbots/DocumentsPage'))
const FAQsPage = lazy(() => import('./pages/chatbots/FAQsPage'))
const UniboxPage = lazy(() => import('./pages/chatbots/UniboxPage'))
const AnalyticsPage = lazy(() => import('./pages/chatbots/AnalyticsPage'))
const LeadsPage = lazy(() => import('./pages/chatbots/LeadsPage'))
const CRMPage = lazy(() => import('./pages/chatbots/CRMPage'))
const SocialConnectionsPage = lazy(() => import('./pages/chatbots/SocialConnectionsPage'))
const VoiceSettingsPage = lazy(() => import('./pages/chatbots/VoiceSettingsPage'))
const ToolsSettingsPage = lazy(() => import('./pages/chatbots/ToolsSettingsPage'))
const AISettingsPage = lazy(() => import('./pages/chatbots/AISettingsPage'))
const VoicebotPhoneNumbersPage = lazy(() => import('./pages/chatbots/VoicebotPhoneNumbersPage'))
const EstimatesPage = lazy(() => import('./pages/chatbots/EstimatesPage'))
const EstimateDetailPage = lazy(() => import('./pages/chatbots/EstimateDetailPage'))
const EstimateCreatePage = lazy(() => import('./pages/chatbots/EstimateCreatePage'))
const InvoicesPage = lazy(() => import('./pages/chatbots/InvoicesPage'))
const InvoiceDetailPage = lazy(() => import('./pages/chatbots/InvoiceDetailPage'))
const InvoiceCreatePage = lazy(() => import('./pages/chatbots/InvoiceCreatePage'))

// Settings Pages
const SettingsPage = lazy(() => import('./pages/settings/SettingsPage'))
const TeamPage = lazy(() => import('./pages/settings/TeamPage'))
const PhoneNumbersPage = lazy(() => import('./pages/settings/PhoneNumbersPage'))
const ApiKeysPage = lazy(() => import('./pages/settings/ApiKeysPage'))
const BillingPage = lazy(() => import('./pages/settings/BillingPage'))
const FeedbackPage = lazy(() => import('./pages/FeedbackPage'))
const NewsfeedPage = lazy(() => import('./pages/NewsfeedPage'))

// Admin Pages
const AdminDashboardPage = lazy(() => import('./pages/admin/AdminDashboardPage'))
const AdminBusinessesPage = lazy(() => import('./pages/admin/AdminBusinessesPage'))
const UsersPage = lazy(() => import('./pages/admin/UsersPage'))
const PlansPage = lazy(() => import('./pages/admin/PlansPage'))
const AdminFeedbackPage = lazy(() => import('./pages/admin/AdminFeedbackPage'))
const AdminVoiceSettingsPage = lazy(() => import('./pages/admin/AdminVoiceSettingsPage'))
const AdminSystemHealthPage = lazy(() => import('./pages/admin/AdminSystemHealthPage'))

// Public Pages
import PublicTestPage from './pages/public/PublicTestPage'
import LandingPageV1 from './pages/public/LandingPageV1'
import LandingPageV1Light from './pages/public/LandingPageV1Light'
import LandingPageV2 from './pages/public/LandingPageV2'
import LandingPageV3 from './pages/public/LandingPageV3'
import LandingPageV4 from './pages/public/LandingPageV4'
import LandingPageV5 from './pages/public/LandingPageV5'
import LandingPageV6 from './pages/public/LandingPageV6'
import LandingPageV7 from './pages/public/LandingPageV7'
import LandingPageV8 from './pages/public/LandingPageV8'
import HeroSvgPreview from './pages/public/HeroSvgPreview'
import LogoShowcasePage from './pages/public/LogoShowcasePage'
import AgencyBookingPage from './pages/chatbots/agency/AgencyBookingPage'
import AgencyRelationsPage from './pages/chatbots/agency/AgencyRelationsPage'
import MyHoursPage from './pages/chatbots/agency/MyHoursPage'
import LogoDownloadPage from './pages/public/LogoDownloadPage'
import DesignDemoPage from './pages/public/DesignDemoPage'
import NavDemoPage from './pages/public/NavDemoPage'
import BookingManagePage from './pages/public/BookingManagePage'
import PrivacyPolicyPage from './pages/public/PrivacyPolicyPage'
import TermsOfServicePage from './pages/public/TermsOfServicePage'
import EstimateViewPage from './pages/public/EstimateViewPage'
import InvoiceViewPage from './pages/public/InvoiceViewPage'

function ProtectedRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  return <>{children}</>
}

function AdminRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, user } = useAuthStore()

  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }

  if (!user?.is_superuser) {
    return <Navigate to="/dashboard" replace />
  }

  return <>{children}</>
}

function PublicRoute({ children }: { children: React.ReactNode }) {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (isAuthenticated) {
    return <Navigate to="/businesses" replace />
  }

  return <>{children}</>
}

/**
 * Smart calendar page: shows ResourceCalendarPage for users who only have
 * calendar_access permissions, UnifiedCalendarPage for admins/owners.
 */
function SmartCalendarPage() {
  const { permissions, isOwner, isAdmin } = useMembershipStore()

  // Owners and admins always see the full admin calendar
  if (isOwner || isAdmin()) {
    return <UnifiedCalendarPage />
  }

  // Users with calendar_access but NOT calendar.manage see the resource view
  const hasCalendarAccess = permissions.some(p => p.startsWith('calendar_access.'))
  const hasAdminCalendar = permissions.some(p => p.startsWith('calendar.') && !p.startsWith('calendar_access.'))

  if (hasCalendarAccess && !hasAdminCalendar) {
    return <ResourceCalendarPage />
  }

  // Default: show admin calendar (for agents with calendar.* permissions)
  return <UnifiedCalendarPage />
}

function LandingPageRoute() {
  const isAuthenticated = useAuthStore((state) => state.isAuthenticated)

  if (isAuthenticated) {
    return <Navigate to="/businesses" replace />
  }

  if (getBrand().name === 'CurisOS') {
    return <CurisOsLandingPage />
  }

  return <LandingPage />
}

export default function App() {
  return (
    <Suspense fallback={<div className="flex items-center justify-center min-h-screen"><div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600" /></div>}>
    <Routes>
      {/* Public routes */}
      <Route
        element={
          <PublicRoute>
            <AuthLayout />
          </PublicRoute>
        }
      >
        <Route path="/login" element={<LoginPage />} />
        <Route path="/register" element={<RegisterPage />} />
      </Route>

      {/* Protected routes */}
      <Route
        element={
          <ProtectedRoute>
            <DashboardLayout />
          </ProtectedRoute>
        }
      >
        <Route path="/dashboard" element={<Navigate to="/businesses" replace />} />
        <Route path="/feed" element={<NewsfeedPage />} />

        {/* New Business Routes */}
        <Route path="/businesses" element={<BusinessesPage />} />
        <Route path="/business/:id" element={<BusinessDetailPage />}>
          {/* Business tab routes */}
          <Route path="feed" element={<BusinessFeedPage />} />
          <Route path="bots" element={<BotsPage />} />
          <Route path="bots/chatbot" element={<BotsPage />} />
          <Route path="bots/voicebot" element={<BotsPage />} />
          <Route path="bots/settings/documents" element={<DocumentsPage />} />
          <Route path="bots/settings/faqs" element={<FAQsPage />} />
          <Route path="bots/settings/ai" element={<AISettingsPage />} />
          <Route path="bots/settings/playground" element={<PlaygroundPage />} />
          <Route path="bots/chatbot/widget" element={<ChatbotSettingsPage />} />
          <Route path="bots/chatbot/embed" element={<ChatbotDetailPage />} />
          <Route path="bots/chatbot/messages" element={<ChatbotSettingsPage />} />
          <Route path="bots/chatbot/leads" element={<ChatbotSettingsPage />} />
          <Route path="bots/voicebot/phone-numbers" element={<VoicebotPhoneNumbersPage />} />
          <Route path="bots/voicebot/voice" element={<VoiceSettingsPage />} />
          <Route path="bots/voicebot/call-handling" element={<VoiceSettingsPage />} />
          <Route path="unibox" element={<UniboxPage />} />
          <Route path="unibox/social" element={<SocialConnectionsPage />} />
          <Route path="customers" element={<CRMPage />} />
          <Route path="customers/leads" element={<LeadsPage />} />
          <Route path="invoicing" element={<EstimatesPage />} />
          <Route path="invoicing/estimates" element={<EstimatesPage />} />
          <Route path="invoicing/estimates/new" element={<EstimateCreatePage />} />
          <Route path="invoicing/estimates/:estimateId" element={<EstimateDetailPage />} />
          <Route path="invoicing/invoices" element={<InvoicesPage />} />
          <Route path="invoicing/invoices/new" element={<InvoiceCreatePage />} />
          <Route path="invoicing/invoices/:invoiceId" element={<InvoiceDetailPage />} />
          <Route path="calendar" element={<SmartCalendarPage />} />
          <Route path="agency/booking" element={<AgencyBookingPage />} />
          <Route path="agency/relations" element={<AgencyRelationsPage />} />
          <Route path="agency/hours" element={<MyHoursPage />} />
          <Route path="notifications" element={<NotificationsPage />} />
          <Route path="notifications/user" element={<NotificationsPage />} />
          <Route path="notifications/client" element={<NotificationsPage />} />
          <Route path="notifications/channels" element={<NotificationsPage />} />
          <Route path="users" element={<UserManagementPage />} />
          <Route path="users/permissions" element={<UserManagementPage />} />
          <Route path="users/activity" element={<UserManagementPage />} />
          <Route path="analytics" element={<AnalyticsPage />} />
          <Route path="google-business" element={<GoogleBusinessProfilePage />} />
          <Route path="consultant" element={<OperatorPage />} />
          <Route path="website" element={<WebsiteManagePage />} />
          <Route path="intelligence/settings" element={<IntelligenceSettingsPage />} />
        </Route>

        {/* Bot detail routes (within business) */}
        <Route path="/business/:id/bots/chatbot/:botId" element={<ChatbotDetailPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/playground" element={<PlaygroundPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/documents" element={<DocumentsPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/faqs" element={<FAQsPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/tools" element={<ToolsSettingsPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/webhooks" element={<WebhookSettingsPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/settings" element={<ChatbotSettingsPage />} />
        <Route path="/business/:id/bots/chatbot/:botId/ai-settings" element={<AISettingsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId" element={<VoiceSettingsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/playground" element={<PlaygroundPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/documents" element={<DocumentsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/faqs" element={<FAQsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/phone-numbers" element={<VoicebotPhoneNumbersPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/tools" element={<ToolsSettingsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/webhooks" element={<WebhookSettingsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/settings" element={<VoiceSettingsPage />} />
        <Route path="/business/:id/bots/voicebot/:botId/ai-settings" element={<AISettingsPage />} />

        {/* Legacy chatbot routes (for backwards compatibility) */}
        <Route path="/chatbots" element={<Navigate to="/businesses" replace />} />
        <Route path="/chatbots/:id" element={<ChatbotDetailPage />} />
        <Route path="/chatbots/:id/playground" element={<PlaygroundPage />} />
        <Route path="/chatbots/:id/settings" element={<ChatbotSettingsPage />} />
        <Route path="/chatbots/:id/calendar" element={<UnifiedCalendarPage />} />
        <Route path="/chatbots/:id/webhooks" element={<WebhookSettingsPage />} />
        <Route path="/chatbots/:id/documents" element={<DocumentsPage />} />
        <Route path="/chatbots/:id/faqs" element={<FAQsPage />} />
        <Route path="/chatbots/:id/unibox" element={<UniboxPage />} />
        <Route path="/chatbots/:id/analytics" element={<AnalyticsPage />} />
        <Route path="/chatbots/:id/leads" element={<LeadsPage />} />
        <Route path="/chatbots/:id/crm" element={<CRMPage />} />
        <Route path="/chatbots/:id/social" element={<SocialConnectionsPage />} />
        <Route path="/chatbots/:id/social/callback" element={<SocialConnectionsPage />} />
        <Route path="/chatbots/:id/social/callback/instagram-direct" element={<SocialConnectionsPage />} />
        <Route path="/chatbots/:id/voice" element={<VoiceSettingsPage />} />
        <Route path="/chatbots/:id/tools" element={<ToolsSettingsPage />} />
        <Route path="/chatbots/:id/estimates" element={<EstimatesPage />} />
        <Route path="/chatbots/:id/estimates/new" element={<EstimateCreatePage />} />
        <Route path="/chatbots/:id/estimates/:estimateId" element={<EstimateDetailPage />} />
        <Route path="/chatbots/:id/invoices" element={<InvoicesPage />} />
        <Route path="/chatbots/:id/invoices/new" element={<InvoiceCreatePage />} />
        <Route path="/chatbots/:id/invoices/:invoiceId" element={<InvoiceDetailPage />} />

        {/* Settings routes */}
        <Route path="/settings" element={<SettingsPage />} />
        <Route path="/settings/team" element={<TeamPage />} />
        <Route path="/settings/phone-numbers" element={<PhoneNumbersPage />} />
        <Route path="/settings/api-keys" element={<ApiKeysPage />} />
        <Route path="/settings/billing" element={<BillingPage />} />
        <Route path="/feedback" element={<FeedbackPage />} />
      </Route>

      {/* Admin routes */}
      <Route
        element={
          <AdminRoute>
            <DashboardLayout />
          </AdminRoute>
        }
      >
        <Route path="/admin" element={<AdminDashboardPage />} />
        <Route path="/admin/businesses" element={<AdminBusinessesPage />} />
        <Route path="/admin/users" element={<UsersPage />} />
        <Route path="/admin/plans" element={<PlansPage />} />
        <Route path="/admin/feedback" element={<AdminFeedbackPage />} />
        <Route path="/admin/voice" element={<AdminVoiceSettingsPage />} />
        <Route path="/admin/health" element={<AdminSystemHealthPage />} />
      </Route>

      {/* Accept invitation page (no auth required - handles both logged in and logged out) */}
      <Route path="/accept-invite" element={<AcceptInvitePage />} />

      {/* Social OAuth callbacks (no auth required during OAuth flow) */}
      <Route path="/instagram/callback" element={<InstagramCallbackPage />} />
      <Route path="/facebook/callback" element={<FacebookCallbackPage />} />

      {/* Facebook OAuth callback (no auth required during OAuth flow) */}
      <Route path="/facebook/callback" element={<FacebookCallbackPage />} />

      {/* Public test page (no auth required) */}
      <Route path="/test/:slug" element={<PublicTestPage />} />

      {/* Booking management page (no auth required) */}
      <Route path="/booking/:token" element={<BookingManagePage />} />
      <Route path="/booking/:token/reschedule" element={<BookingManagePage initialAction="reschedule" />} />
      <Route path="/booking/:token/cancel" element={<BookingManagePage initialAction="cancel" />} />

      {/* Public booking page (no auth required) — shareable per-chatbot URL */}
      <Route path="/book/:slug" element={<BookingManagePage />} />

      {/* Public estimate and invoice pages (no auth required) */}
      <Route path="/estimate/:token" element={<EstimateViewPage />} />
      <Route path="/invoice/:token" element={<InvoiceViewPage />} />

      {/* Legal pages (no auth required) */}
      <Route path="/privacy" element={<PrivacyPolicyPage />} />
      <Route path="/terms" element={<TermsOfServicePage />} />

      {/* Landing page variations (for preview) */}
      <Route path="/landing/v1" element={<LandingPageV1 />} />
      <Route path="/landing/v1-light" element={<LandingPageV1Light />} />
      <Route path="/landing/v2" element={<LandingPageV2 />} />
      <Route path="/landing/v3" element={<LandingPageV3 />} />
      <Route path="/landing/v4" element={<LandingPageV4 />} />
      <Route path="/landing/v5" element={<LandingPageV5 />} />
      <Route path="/landing/v6" element={<LandingPageV6 />} />
      <Route path="/landing/v7" element={<LandingPageV7 />} />
      <Route path="/landing/v8" element={<LandingPageV8 />} />
      <Route path="/landing/hero-preview" element={<HeroSvgPreview />} />
      <Route path="/landing/logos" element={<LogoShowcasePage />} />
      <Route path="/landing/logos/download" element={<LogoDownloadPage />} />
      <Route path="/design-demo" element={<DesignDemoPage />} />
      <Route path="/nav-demo" element={<NavDemoPage />} />

      {/* Landing page - show to non-authenticated users */}
      <Route path="/" element={<LandingPageRoute />} />

      {/* 404 */}
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
    </Suspense>
  )
}
