All files / src App.tsx

48.58% Statements 172/354
25.43% Branches 44/173
8.92% Functions 10/112
66.53% Lines 171/257

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926                              1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x                         1x 2x 2x                         1x                                         1x     8x 7x 7x     8x 8x     8x 8x 8x     8x 8x 8x 8x     8x     8x   7x 7x     7x   8x 8x 8x     8x 7x 7x         8x 7x 7x 7x     7x   7x   4x 4x 3x   1x 1x 1x 1x           8x 7x 7x 7x   7x                                                                                         8x         8x 1x       7x 7x   7x 7x         7x 3x                                                       4x 4x 4x 4x     4x 4x 4x     4x     4x   1x 1x                                                       3x                                                                           8x 8x 8x 8x   8x 8x 8x     8x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           1x 7x                    
/**
 * Main App Component - Integrated with Real API
 */
 
import React, { useState, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { useCurrentUser, useMasquerade, useLogout } from './hooks/useAuth';
import { useCurrentBusiness } from './hooks/useBusiness';
import { useUpdateBusiness } from './hooks/useBusiness';
import { useTenantExists } from './hooks/useTenantExists';
import { setCookie } from './utils/cookies';
 
// Import Login Page
const LoginPage = React.lazy(() => import('./pages/LoginPage'));
const MarketingLoginPage = React.lazy(() => import('./pages/marketing/MarketingLoginPage'));
const TenantLoginPage = React.lazy(() => import('./pages/TenantLoginPage'));
const MFAVerifyPage = React.lazy(() => import('./pages/MFAVerifyPage'));
const OAuthCallback = React.lazy(() => import('./pages/OAuthCallback'));
 
// Import layouts
import BusinessLayout from './layouts/BusinessLayout';
import PlatformLayout from './layouts/PlatformLayout';
import CustomerLayout from './layouts/CustomerLayout';
import MarketingLayout from './layouts/MarketingLayout';
 
// Import marketing pages
const HomePage = React.lazy(() => import('./pages/marketing/HomePage'));
const FeaturesPage = React.lazy(() => import('./pages/marketing/FeaturesPage'));
const PricingPage = React.lazy(() => import('./pages/marketing/PricingPage'));
const AboutPage = React.lazy(() => import('./pages/marketing/AboutPage'));
const ContactPage = React.lazy(() => import('./pages/marketing/ContactPage'));
const SignupPage = React.lazy(() => import('./pages/marketing/SignupPage'));
const PrivacyPolicyPage = React.lazy(() => import('./pages/marketing/PrivacyPolicyPage'));
const TermsOfServicePage = React.lazy(() => import('./pages/marketing/TermsOfServicePage'));
 
// Import pages
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const Scheduler = React.lazy(() => import('./pages/Scheduler'));
const Customers = React.lazy(() => import('./pages/Customers'));
const Settings = React.lazy(() => import('./pages/Settings'));
const Payments = React.lazy(() => import('./pages/Payments'));
const Resources = React.lazy(() => import('./pages/Resources'));
const Services = React.lazy(() => import('./pages/Services'));
const Staff = React.lazy(() => import('./pages/Staff'));
const TimeBlocks = React.lazy(() => import('./pages/TimeBlocks'));
const MyAvailability = React.lazy(() => import('./pages/MyAvailability'));
const CustomerDashboard = React.lazy(() => import('./pages/customer/CustomerDashboard'));
const CustomerSupport = React.lazy(() => import('./pages/customer/CustomerSupport'));
const ResourceDashboard = React.lazy(() => import('./pages/resource/ResourceDashboard'));
const BookingPage = React.lazy(() => import('./pages/customer/BookingPage'));
const CustomerBilling = React.lazy(() => import('./pages/customer/CustomerBilling'));
const TrialExpired = React.lazy(() => import('./pages/TrialExpired'));
const Upgrade = React.lazy(() => import('./pages/Upgrade'));
 
// Import platform pages
const PlatformDashboard = React.lazy(() => import('./pages/platform/PlatformDashboard'));
const PlatformBusinesses = React.lazy(() => import('./pages/platform/PlatformBusinesses'));
const PlatformSupportPage = React.lazy(() => import('./pages/platform/PlatformSupport'));
const PlatformEmailAddresses = React.lazy(() => import('./pages/platform/PlatformEmailAddresses'));
const PlatformUsers = React.lazy(() => import('./pages/platform/PlatformUsers'));
const PlatformStaff = React.lazy(() => import('./pages/platform/PlatformStaff'));
const PlatformSettings = React.lazy(() => import('./pages/platform/PlatformSettings'));
const ProfileSettings = React.lazy(() => import('./pages/ProfileSettings'));
const VerifyEmail = React.lazy(() => import('./pages/VerifyEmail'));
const EmailVerificationRequired = React.lazy(() => import('./pages/EmailVerificationRequired'));
const AcceptInvitePage = React.lazy(() => import('./pages/AcceptInvitePage'));
const TenantOnboardPage = React.lazy(() => import('./pages/TenantOnboardPage'));
const TenantLandingPage = React.lazy(() => import('./pages/TenantLandingPage'));
const Tickets = React.lazy(() => import('./pages/Tickets')); // Import Tickets page
const HelpGuide = React.lazy(() => import('./pages/HelpGuide')); // Import Platform Guide page
const HelpTicketing = React.lazy(() => import('./pages/HelpTicketing')); // Import Help page for ticketing
const HelpApiDocs = React.lazy(() => import('./pages/HelpApiDocs')); // Import API documentation page
const HelpPluginDocs = React.lazy(() => import('./pages/help/HelpPluginDocs')); // Import Plugin documentation page
const HelpEmailSettings = React.lazy(() => import('./pages/HelpEmailSettings')); // Import Email settings help page
 
// Import new help pages
const HelpDashboard = React.lazy(() => import('./pages/help/HelpDashboard'));
const HelpScheduler = React.lazy(() => import('./pages/help/HelpScheduler'));
const HelpTasks = React.lazy(() => import('./pages/help/HelpTasks'));
const HelpCustomers = React.lazy(() => import('./pages/help/HelpCustomers'));
const HelpServices = React.lazy(() => import('./pages/help/HelpServices'));
const HelpResources = React.lazy(() => import('./pages/help/HelpResources'));
const HelpStaff = React.lazy(() => import('./pages/help/HelpStaff'));
const HelpTimeBlocks = React.lazy(() => import('./pages/HelpTimeBlocks'));
const HelpMessages = React.lazy(() => import('./pages/help/HelpMessages'));
const HelpPayments = React.lazy(() => import('./pages/help/HelpPayments'));
const HelpContracts = React.lazy(() => import('./pages/help/HelpContracts'));
const HelpPlugins = React.lazy(() => import('./pages/help/HelpPlugins'));
const HelpSettingsGeneral = React.lazy(() => import('./pages/help/HelpSettingsGeneral'));
const HelpSettingsResourceTypes = React.lazy(() => import('./pages/help/HelpSettingsResourceTypes'));
const HelpSettingsBooking = React.lazy(() => import('./pages/help/HelpSettingsBooking'));
const HelpSettingsAppearance = React.lazy(() => import('./pages/help/HelpSettingsAppearance'));
const HelpSettingsEmail = React.lazy(() => import('./pages/help/HelpSettingsEmail'));
const HelpSettingsDomains = React.lazy(() => import('./pages/help/HelpSettingsDomains'));
const HelpSettingsApi = React.lazy(() => import('./pages/help/HelpSettingsApi'));
const HelpSettingsAuth = React.lazy(() => import('./pages/help/HelpSettingsAuth'));
const HelpSettingsBilling = React.lazy(() => import('./pages/help/HelpSettingsBilling'));
const HelpSettingsQuota = React.lazy(() => import('./pages/help/HelpSettingsQuota'));
const HelpComprehensive = React.lazy(() => import('./pages/help/HelpComprehensive'));
const PlatformSupport = React.lazy(() => import('./pages/PlatformSupport')); // Import Platform Support page (for businesses to contact SmoothSchedule)
const PluginMarketplace = React.lazy(() => import('./pages/PluginMarketplace')); // Import Plugin Marketplace page
const MyPlugins = React.lazy(() => import('./pages/MyPlugins')); // Import My Plugins page
const CreatePlugin = React.lazy(() => import('./pages/CreatePlugin')); // Import Create Plugin page
const Tasks = React.lazy(() => import('./pages/Tasks')); // Import Tasks page for scheduled plugin executions
const EmailTemplates = React.lazy(() => import('./pages/EmailTemplates')); // Import Email Templates page
const Contracts = React.lazy(() => import('./pages/Contracts')); // Import Contracts page
const ContractTemplates = React.lazy(() => import('./pages/ContractTemplates')); // Import Contract Templates page
const ContractSigning = React.lazy(() => import('./pages/ContractSigning')); // Import Contract Signing page (public)
 
// Settings pages
const SettingsLayout = React.lazy(() => import('./layouts/SettingsLayout'));
const GeneralSettings = React.lazy(() => import('./pages/settings/GeneralSettings'));
const BrandingSettings = React.lazy(() => import('./pages/settings/BrandingSettings'));
const ResourceTypesSettings = React.lazy(() => import('./pages/settings/ResourceTypesSettings'));
const BookingSettings = React.lazy(() => import('./pages/settings/BookingSettings'));
const CustomDomainsSettings = React.lazy(() => import('./pages/settings/CustomDomainsSettings'));
const ApiSettings = React.lazy(() => import('./pages/settings/ApiSettings'));
const AuthenticationSettings = React.lazy(() => import('./pages/settings/AuthenticationSettings'));
const EmailSettings = React.lazy(() => import('./pages/settings/EmailSettings'));
const CommunicationSettings = React.lazy(() => import('./pages/settings/CommunicationSettings'));
const BillingSettings = React.lazy(() => import('./pages/settings/BillingSettings'));
const QuotaSettings = React.lazy(() => import('./pages/settings/QuotaSettings'));
 
import { Toaster } from 'react-hot-toast'; // Import Toaster for notifications
 
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      refetchOnWindowFocus: false,
      retry: 1,
      staleTime: 30000, // 30 seconds
    },
  },
});
 
/**
 * Loading Component
 */
const LoadingScreen: React.FC = () => {
  const { t } = useTranslation();
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
      <div className="text-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
        <p className="text-gray-600 dark:text-gray-400">{t('common.loading')}</p>
      </div>
    </div>
  );
};
 
/**
 * Error Component
 */
const ErrorScreen: React.FC<{ error: Error }> = ({ error }) => {
  const { t } = useTranslation();
  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
      <div className="text-center max-w-md">
        <h2 className="text-2xl font-bold text-red-600 dark:text-red-400 mb-4">{t('common.error')}</h2>
        <p className="text-gray-600 dark:text-gray-400 mb-4">{error.message}</p>
        <button
          onClick={() => window.location.reload()}
          className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
        >
          {t('common.reload')}
        </button>
      </div>
    </div>
  );
};
 
/**
 * App Content - Handles routing based on auth state
 */
const AppContent: React.FC = () => {
  // Check for tokens in URL FIRST - before any queries execute
  // This handles login/masquerade redirects that pass tokens in the URL
  const [processingUrlTokens] = useState(() => {
    const params = new URLSearchParams(window.location.search);
    return !!(params.get('access_token') && params.get('refresh_token'));
  });
 
  const { data: user, isLoading: userLoading, error: userError } = useCurrentUser();
  const { data: business, isLoading: businessLoading, error: businessError } = useCurrentBusiness();
 
  // Get subdomain info early for tenant validation
  const currentHostnameForTenant = window.location.hostname;
  const hostnamePartsForTenant = currentHostnameForTenant.split('.');
  const baseDomainForTenant = hostnamePartsForTenant.length >= 2
    ? hostnamePartsForTenant.slice(-2).join('.')
    : currentHostnameForTenant;
  const isRootDomainForTenant = currentHostnameForTenant === baseDomainForTenant || currentHostnameForTenant === 'localhost';
  const isPlatformSubdomainForTenant = hostnamePartsForTenant[0] === 'platform';
  const currentSubdomainForTenant = hostnamePartsForTenant[0];
  const isBusinessSubdomainForTenant = !isRootDomainForTenant && !isPlatformSubdomainForTenant && currentSubdomainForTenant !== 'api';
 
  // Check if tenant exists for business subdomains
  const { exists: tenantExists, isLoading: tenantLoading } = useTenantExists(
    isBusinessSubdomainForTenant ? currentSubdomainForTenant : null
  );
  const [darkMode, setDarkMode] = useState(() => {
    // Check localStorage first, then system preference
    const saved = localStorage.getItem('darkMode');
    Iif (saved !== null) {
      return JSON.parse(saved);
    }
    return window.matchMedia('(prefers-color-scheme: dark)').matches;
  });
  const updateBusinessMutation = useUpdateBusiness();
  const masqueradeMutation = useMasquerade();
  const logoutMutation = useLogout();
 
  // Apply dark mode class and persist to localStorage
  React.useEffect(() => {
    document.documentElement.classList.toggle('dark', darkMode);
    localStorage.setItem('darkMode', JSON.stringify(darkMode));
  }, [darkMode]);
 
  // Set noindex/nofollow for app subdomains (platform, business subdomains)
  // Only the root domain marketing pages should be indexed
  React.useEffect(() => {
    const hostname = window.location.hostname;
    const parts = hostname.split('.');
    const hasSubdomain = parts.length > 2 || (parts.length === 2 && parts[0] !== 'localhost');
 
    // Check if we're on a subdomain (platform.*, demo.*, etc.)
    const isSubdomain = hostname !== 'localhost' && hostname !== '127.0.0.1' && parts.length > 2;
 
    if (isSubdomain) {
      // Always noindex/nofollow on subdomains (app areas)
      let metaRobots = document.querySelector('meta[name="robots"]');
      if (metaRobots) {
        metaRobots.setAttribute('content', 'noindex, nofollow');
      } else {
        metaRobots = document.createElement('meta');
        metaRobots.setAttribute('name', 'robots');
        metaRobots.setAttribute('content', 'noindex, nofollow');
        document.head.appendChild(metaRobots);
      }
    }
  }, []);
 
  // Handle tokens in URL (from login or masquerade redirect)
  React.useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const accessToken = params.get('access_token');
    const refreshToken = params.get('refresh_token');
 
    Iif (accessToken && refreshToken) {
      // Extract masquerade stack if present (for masquerade banner)
      const masqueradeStackParam = params.get('masquerade_stack');
      if (masqueradeStackParam) {
        try {
          const masqueradeStack = JSON.parse(decodeURIComponent(masqueradeStackParam));
          localStorage.setItem('masquerade_stack', JSON.stringify(masqueradeStack));
        } catch (e) {
          console.error('Failed to parse masquerade stack', e);
        }
      }
 
      // For backward compatibility, also check for original_user parameter
      const originalUserParam = params.get('original_user');
      if (originalUserParam && !masqueradeStackParam) {
        try {
          const originalUser = JSON.parse(decodeURIComponent(originalUserParam));
          // Convert old format to new stack format (single entry)
          const stack = [{
            user_id: originalUser.id,
            username: originalUser.username,
            role: originalUser.role,
            business_id: originalUser.business,
            business_subdomain: originalUser.business_subdomain,
          }];
          localStorage.setItem('masquerade_stack', JSON.stringify(stack));
        } catch (e) {
          console.error('Failed to parse original user', e);
        }
      }
 
      // Set cookies using helper (handles domain correctly)
      setCookie('access_token', accessToken, 7);
      setCookie('refresh_token', refreshToken, 7);
 
      // Clean URL
      const newUrl = window.location.pathname + window.location.hash;
      window.history.replaceState({}, '', newUrl);
 
      // Force reload to ensure auth state is picked up
      window.location.reload();
    }
  }, []);
 
  // Show loading while processing URL tokens (before reload happens)
  Iif (processingUrlTokens) {
    return <LoadingScreen />;
  }
 
  // Loading state
  if (userLoading) {
    return <LoadingScreen />;
  }
 
  // Helper to detect root domain (for marketing site)
  const isRootDomain = (): boolean => {
    const hostname = window.location.hostname;
    // Root domain has no subdomain (just the base domain like smoothschedule.com or lvh.me)
    const parts = hostname.split('.');
    return hostname === 'localhost' || hostname === '127.0.0.1' || parts.length === 2;
  };
 
  // On root domain, ALWAYS show marketing site (even if logged in)
  // Logged-in users will see a "Go to Dashboard" link in the navbar
  if (isRootDomain()) {
    return (
      <Suspense fallback={<LoadingScreen />}>
        <Routes>
          <Route element={<MarketingLayout user={user} />}>
            <Route path="/" element={<HomePage />} />
            <Route path="/features" element={<FeaturesPage />} />
            <Route path="/pricing" element={<PricingPage />} />
            <Route path="/about" element={<AboutPage />} />
            <Route path="/contact" element={<ContactPage />} />
            <Route path="/signup" element={<SignupPage />} />
            <Route path="/privacy" element={<PrivacyPolicyPage />} />
            <Route path="/terms" element={<TermsOfServicePage />} />
          </Route>
          <Route path="/login" element={<MarketingLoginPage />} />
          <Route path="/mfa-verify" element={<MFAVerifyPage />} />
          <Route path="/oauth/callback/:provider" element={<OAuthCallback />} />
          <Route path="/verify-email" element={<VerifyEmail />} />
          <Route path="/accept-invite" element={<AcceptInvitePage />} />
          <Route path="/accept-invite/:token" element={<AcceptInvitePage />} />
          <Route path="/tenant-onboard" element={<TenantOnboardPage />} />
          <Route path="/sign/:token" element={<ContractSigning />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </Suspense>
    );
  }
 
  // Not authenticated - show appropriate page based on subdomain
  Eif (!user) {
    const currentHostname = window.location.hostname;
    const hostnameParts = currentHostname.split('.');
    const baseDomain = hostnameParts.length >= 2
      ? hostnameParts.slice(-2).join('.')
      : currentHostname;
    const isRootDomainForUnauthUser = currentHostname === baseDomain || currentHostname === 'localhost';
    const isPlatformSubdomain = hostnameParts[0] === 'platform';
    const currentSubdomain = hostnameParts[0];
 
    // Check if we're on a business subdomain (not root, not platform, not api)
    const isBusinessSubdomain = !isRootDomainForUnauthUser && !isPlatformSubdomain && currentSubdomain !== 'api';
 
    // For business subdomains, check if tenant exists first
    if (isBusinessSubdomain) {
      // Still loading tenant check - show nothing (blank page)
      Eif (tenantLoading) {
        return null;
      }
 
      // Tenant doesn't exist - show nothing (no response)
      if (!tenantExists) {
        return null;
      }
 
      // Tenant exists - show the tenant landing page with login option
      return (
        <Suspense fallback={<LoadingScreen />}>
          <Routes>
            <Route path="/" element={<TenantLandingPage subdomain={currentSubdomain} />} />
            <Route path="/login" element={<TenantLoginPage subdomain={currentSubdomain} />} />
            <Route path="/mfa-verify" element={<MFAVerifyPage />} />
            <Route path="/oauth/callback/:provider" element={<OAuthCallback />} />
            <Route path="/verify-email" element={<VerifyEmail />} />
            <Route path="/accept-invite" element={<AcceptInvitePage />} />
            <Route path="/accept-invite/:token" element={<AcceptInvitePage />} />
            <Route path="/tenant-onboard" element={<TenantOnboardPage />} />
            <Route path="/sign/:token" element={<ContractSigning />} />
            <Route path="*" element={<Navigate to="/" replace />} />
          </Routes>
        </Suspense>
      );
    }
 
    // For root domain or platform subdomain, show marketing site / login
    return (
      <Suspense fallback={<LoadingScreen />}>
        <Routes>
          <Route element={<MarketingLayout user={user} />}>
            <Route path="/" element={<HomePage />} />
            <Route path="/features" element={<FeaturesPage />} />
            <Route path="/pricing" element={<PricingPage />} />
            <Route path="/about" element={<AboutPage />} />
            <Route path="/contact" element={<ContactPage />} />
            <Route path="/signup" element={<SignupPage />} />
            <Route path="/privacy" element={<PrivacyPolicyPage />} />
            <Route path="/terms" element={<TermsOfServicePage />} />
          </Route>
          <Route path="/login" element={<MarketingLoginPage />} />
          <Route path="/mfa-verify" element={<MFAVerifyPage />} />
          <Route path="/oauth/callback/:provider" element={<OAuthCallback />} />
          <Route path="/verify-email" element={<VerifyEmail />} />
          <Route path="/accept-invite" element={<AcceptInvitePage />} />
          <Route path="/accept-invite/:token" element={<AcceptInvitePage />} />
          <Route path="/tenant-onboard" element={<TenantOnboardPage />} />
          <Route path="/sign/:token" element={<ContractSigning />} />
          <Route path="*" element={<Navigate to="/" replace />} />
        </Routes>
      </Suspense>
    );
  }
 
  // Error state
  if (userError) {
    return <ErrorScreen error={userError as Error} />;
  }
 
  // Subdomain validation for logged-in users
  const currentHostname = window.location.hostname;
  const hostnameParts = currentHostname.split('.');
  const baseDomain = hostnameParts.length >= 2
    ? hostnameParts.slice(-2).join('.')
    : currentHostname;
  const protocol = window.location.protocol;
  const isPlatformDomain = currentHostname === `platform.${baseDomain}`;
  const currentSubdomain = hostnameParts[0];
  const isBusinessSubdomain = !isRootDomain() && !isPlatformDomain && currentSubdomain !== 'api' && currentHostname !== baseDomain;
 
  const isPlatformUser = ['superuser', 'platform_manager', 'platform_support'].includes(user.role);
  const isBusinessUser = ['owner', 'manager', 'staff', 'resource'].includes(user.role);
  const isCustomer = user.role === 'customer';
 
  // RULE: Platform users on business subdomains should be redirected to platform subdomain
  Iif (isPlatformUser && isBusinessSubdomain) {
    const port = window.location.port ? `:${window.location.port}` : '';
    window.location.href = `${protocol}//platform.${baseDomain}${port}/`;
    return <LoadingScreen />;
  }
 
  // RULE: Business users must be on their own business subdomain
  if (isBusinessUser && isBusinessSubdomain && user.business_subdomain && user.business_subdomain !== currentSubdomain) {
    const port = window.location.port ? `:${window.location.port}` : '';
    window.location.href = `${protocol}//${user.business_subdomain}.${baseDomain}${port}/`;
    return <LoadingScreen />;
  }
 
  // RULE: Customers must be on their business subdomain
  if (isCustomer && isPlatformDomain && user.business_subdomain) {
    const port = window.location.port ? `:${window.location.port}` : '';
    window.location.href = `${protocol}//${user.business_subdomain}.${baseDomain}${port}/`;
    return <LoadingScreen />;
  }
 
  if (isCustomer && isBusinessSubdomain && user.business_subdomain && user.business_subdomain !== currentSubdomain) {
    const port = window.location.port ? `:${window.location.port}` : '';
    window.location.href = `${protocol}//${user.business_subdomain}.${baseDomain}${port}/`;
    return <LoadingScreen />;
  }
 
  // Handlers
  const toggleTheme = () => setDarkMode((prev) => !prev);
  const handleSignOut = () => {
    logoutMutation.mutate();
  };
  const handleUpdateBusiness = (updates: Partial<any>) => {
    updateBusinessMutation.mutate(updates);
  };
 
  const handleMasquerade = (targetUser: any) => {
    // Call the masquerade API with the target user's id
    const userId = targetUser.id;
    if (!userId) {
      console.error('Cannot masquerade: no user id available', targetUser);
      return;
    }
    // Ensure userId is a number
    const userPk = typeof userId === 'string' ? parseInt(userId, 10) : userId;
    masqueradeMutation.mutate(userPk);
  };
 
  // Helper to check access based on roles
  const hasAccess = (allowedRoles: string[]) => allowedRoles.includes(user.role);
 
  if (isPlatformUser) {
    return (
      <Suspense fallback={<LoadingScreen />}>
        <Routes>
          <Route
            element={
              <PlatformLayout
                user={user}
                darkMode={darkMode}
                toggleTheme={toggleTheme}
                onSignOut={handleSignOut}
              />
            }
          >
            {(user.role === 'superuser' || user.role === 'platform_manager') && (
              <>
                <Route path="/platform/dashboard" element={<PlatformDashboard />} />
                <Route path="/platform/businesses" element={<PlatformBusinesses onMasquerade={handleMasquerade} />} />
                <Route path="/platform/users" element={<PlatformUsers onMasquerade={handleMasquerade} />} />
                <Route path="/platform/staff" element={<PlatformStaff />} />
              </>
            )}
            <Route path="/platform/support" element={<PlatformSupportPage />} />
            <Route path="/platform/email-addresses" element={<PlatformEmailAddresses />} />
            <Route path="/help/guide" element={<HelpGuide />} />
            <Route path="/help/ticketing" element={<HelpTicketing />} />
            <Route path="/help/api" element={<HelpApiDocs />} />
            <Route path="/help/plugins" element={<HelpPluginDocs />} />
            <Route path="/help/email" element={<HelpEmailSettings />} />
            {user.role === 'superuser' && (
              <Route path="/platform/settings" element={<PlatformSettings />} />
            )}
            <Route path="/platform/profile" element={<ProfileSettings />} />
            <Route path="/verify-email" element={<VerifyEmail />} />
            <Route
              path="*"
              element={
                <Navigate
                  to={
                    user.role === 'superuser' || user.role === 'platform_manager'
                      ? '/platform/dashboard'
                      : '/platform/support'
                  }
                />
              }
            />
          </Route>
        </Routes>
      </Suspense>
    );
  }
 
  // Customer users
  if (user.role === 'customer') {
    // Wait for business data to load
    if (businessLoading) {
      return <LoadingScreen />;
    }
 
    // Handle business not found for customers
    if (!business) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
          <div className="text-center max-w-md p-6">
            <h2 className="text-2xl font-bold text-red-600 dark:text-red-400 mb-4">Business Not Found</h2>
            <p className="text-gray-600 dark:text-gray-400 mb-4">
              Unable to load business data. Please try again.
            </p>
            <button
              onClick={handleSignOut}
              className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
            >
              Sign Out
            </button>
          </div>
        </div>
      );
    }
 
    return (
      <Suspense fallback={<LoadingScreen />}>
        <Routes>
          <Route
            element={
              <CustomerLayout
                business={business}
                user={user}
                darkMode={darkMode}
                toggleTheme={toggleTheme}
              />
            }
          >
            <Route path="/" element={<CustomerDashboard />} />
            <Route path="/book" element={<BookingPage />} />
            <Route path="/payments" element={<CustomerBilling />} />
            <Route path="/support" element={<CustomerSupport />} />
            <Route path="/profile" element={<ProfileSettings />} />
            <Route path="/verify-email" element={<VerifyEmail />} />
            <Route path="*" element={<Navigate to="/" />} />
          </Route>
        </Routes>
      </Suspense>
    );
  }
 
  // Business loading - show loading with user info
  if (businessLoading) {
    return <LoadingScreen />;
  }
 
  // Business error or no business found
  if (businessError || !business) {
    // If user has a business subdomain, redirect them there
    if (user.business_subdomain) {
      window.location.href = buildSubdomainUrl(user.business_subdomain, '/');
      return <LoadingScreen />;
    }
 
    // No business subdomain - show error
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900">
        <div className="text-center max-w-md p-6">
          <h2 className="text-2xl font-bold text-red-600 dark:text-red-400 mb-4">Business Not Found</h2>
          <p className="text-gray-600 dark:text-gray-400 mb-4">
            {businessError instanceof Error ? businessError.message : 'Unable to load business data. Please check your subdomain or try again.'}
          </p>
          <div className="flex gap-4 justify-center">
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
            >
              Reload
            </button>
            <button
              onClick={handleSignOut}
              className="px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700"
            >
              Sign Out
            </button>
          </div>
        </div>
      </div>
    );
  }
 
  // Business users (owner, manager, staff, resource)
  if (['owner', 'manager', 'staff', 'resource'].includes(user.role)) {
    // Check if email verification is required
    if (!user.email_verified) {
      return (
        <Suspense fallback={<LoadingScreen />}>
          <Routes>
            <Route path="/email-verification-required" element={<EmailVerificationRequired />} />
            <Route path="/verify-email" element={<VerifyEmail />} />
            <Route path="*" element={<Navigate to="/email-verification-required" replace />} />
          </Routes>
        </Suspense>
      );
    }
 
    // Check if trial has expired
    const isTrialExpired = business.isTrialExpired || (business.status === 'Trial' && business.trialEnd && new Date(business.trialEnd) < new Date());
 
    // Allowed routes when trial is expired
    const allowedWhenExpired = ['/trial-expired', '/upgrade', '/settings', '/profile'];
    const currentPath = window.location.pathname;
    const isOnAllowedRoute = allowedWhenExpired.some(route => currentPath.startsWith(route));
 
    // If trial expired and not on allowed route, redirect to trial-expired
    if (isTrialExpired && !isOnAllowedRoute) {
      return (
        <Suspense fallback={<LoadingScreen />}>
          <Routes>
            <Route path="/trial-expired" element={<TrialExpired />} />
            <Route path="/upgrade" element={<Upgrade />} />
            <Route path="/profile" element={<ProfileSettings />} />
            {/* Trial-expired users can access billing settings to upgrade */}
            <Route
              path="/settings/*"
              element={hasAccess(['owner']) ? <Navigate to="/upgrade" /> : <Navigate to="/trial-expired" />}
            />
            <Route path="*" element={<Navigate to="/trial-expired" replace />} />
          </Routes>
        </Suspense>
      );
    }
 
    return (
      <Suspense fallback={<LoadingScreen />}>
        <Routes>
          <Route
            element={
              <BusinessLayout
                business={business}
                user={user}
                darkMode={darkMode}
                toggleTheme={toggleTheme}
                onSignOut={handleSignOut}
                updateBusiness={handleUpdateBusiness}
              />
            }
          >
            {/* Trial and Upgrade Routes */}
            <Route path="/trial-expired" element={<TrialExpired />} />
            <Route path="/upgrade" element={<Upgrade />} />
 
            {/* Regular Routes */}
            <Route
              path="/"
              element={user.role === 'resource' ? <ResourceDashboard /> : <Dashboard />}
            />
            <Route path="/scheduler" element={<Scheduler />} />
            <Route path="/tickets" element={<Tickets />} />
            <Route path="/help" element={<HelpComprehensive />} />
            <Route path="/help/guide" element={<HelpGuide />} />
            <Route path="/help/ticketing" element={<HelpTicketing />} />
            <Route path="/help/api" element={<HelpApiDocs />} />
            <Route path="/help/plugins/docs" element={<HelpPluginDocs />} />
            <Route path="/help/email" element={<HelpEmailSettings />} />
            {/* New help pages */}
            <Route path="/help/dashboard" element={<HelpDashboard />} />
            <Route path="/help/scheduler" element={<HelpScheduler />} />
            <Route path="/help/tasks" element={<HelpTasks />} />
            <Route path="/help/customers" element={<HelpCustomers />} />
            <Route path="/help/services" element={<HelpServices />} />
            <Route path="/help/resources" element={<HelpResources />} />
            <Route path="/help/staff" element={<HelpStaff />} />
            <Route path="/help/time-blocks" element={<HelpTimeBlocks />} />
            <Route path="/help/messages" element={<HelpMessages />} />
            <Route path="/help/payments" element={<HelpPayments />} />
            <Route path="/help/contracts" element={<HelpContracts />} />
            <Route path="/help/plugins" element={<HelpPlugins />} />
            <Route path="/help/settings/general" element={<HelpSettingsGeneral />} />
            <Route path="/help/settings/resource-types" element={<HelpSettingsResourceTypes />} />
            <Route path="/help/settings/booking" element={<HelpSettingsBooking />} />
            <Route path="/help/settings/appearance" element={<HelpSettingsAppearance />} />
            <Route path="/help/settings/email" element={<HelpSettingsEmail />} />
            <Route path="/help/settings/domains" element={<HelpSettingsDomains />} />
            <Route path="/help/settings/api" element={<HelpSettingsApi />} />
            <Route path="/help/settings/auth" element={<HelpSettingsAuth />} />
            <Route path="/help/settings/billing" element={<HelpSettingsBilling />} />
            <Route path="/help/settings/quota" element={<HelpSettingsQuota />} />
            <Route
              path="/plugins/marketplace"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <PluginMarketplace />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/plugins/my-plugins"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <MyPlugins />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/plugins/create"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <CreatePlugin />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/tasks"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <Tasks />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/email-templates"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <EmailTemplates />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route path="/support" element={<PlatformSupport />} />
            <Route
              path="/customers"
              element={
                hasAccess(['owner', 'manager', 'staff']) ? (
                  <Customers onMasquerade={handleMasquerade} effectiveUser={user} />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/services"
              element={
                hasAccess(['owner', 'manager', 'staff']) ? (
                  <Services />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/resources"
              element={
                hasAccess(['owner', 'manager', 'staff']) ? (
                  <Resources onMasquerade={handleMasquerade} effectiveUser={user} />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/staff"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <Staff onMasquerade={handleMasquerade} effectiveUser={user} />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/time-blocks"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <TimeBlocks />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/my-availability"
              element={
                hasAccess(['staff', 'resource']) ? (
                  <MyAvailability user={user} />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/contracts"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <Contracts />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/contracts/templates"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <ContractTemplates />
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            <Route
              path="/payments"
              element={
                hasAccess(['owner', 'manager']) ? <Payments /> : <Navigate to="/" />
              }
            />
            <Route
              path="/messages"
              element={
                hasAccess(['owner', 'manager']) ? (
                  <div className="p-8">
                    <h1 className="text-2xl font-bold mb-4">Messages</h1>
                    <p className="text-gray-600">Messages feature coming soon...</p>
                  </div>
                ) : (
                  <Navigate to="/" />
                )
              }
            />
            {/* Settings Routes with Nested Layout */}
            {hasAccess(['owner']) ? (
              <Route path="/settings" element={<SettingsLayout />}>
                <Route index element={<Navigate to="/settings/general" replace />} />
                <Route path="general" element={<GeneralSettings />} />
                <Route path="branding" element={<BrandingSettings />} />
                <Route path="resource-types" element={<ResourceTypesSettings />} />
                <Route path="booking" element={<BookingSettings />} />
                <Route path="email-templates" element={<EmailTemplates />} />
                <Route path="custom-domains" element={<CustomDomainsSettings />} />
                <Route path="api" element={<ApiSettings />} />
                <Route path="authentication" element={<AuthenticationSettings />} />
                <Route path="email" element={<EmailSettings />} />
                <Route path="sms-calling" element={<CommunicationSettings />} />
                <Route path="billing" element={<BillingSettings />} />
                <Route path="quota" element={<QuotaSettings />} />
              </Route>
            ) : (
              <Route path="/settings/*" element={<Navigate to="/" />} />
            )}
            <Route path="/profile" element={<ProfileSettings />} />
            <Route path="/verify-email" element={<VerifyEmail />} />
            <Route path="*" element={<Navigate to="/" />} />
          </Route>
        </Routes>
      </Suspense>
    );
  }
 
  // Fallback
  return <Navigate to="/" />;
};
 
/**
 * Main App Component
 */
const App: React.FC = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <Router>
        <AppContent />
      </Router>
      <Toaster /> {/* Add Toaster component for notifications */}
    </QueryClientProvider>
  );
};
 
export default App;