/* global wp */
/**
 * ProRank SEO - Main Admin App
 *
 * This is the main entry point for the ProRank SEO admin interface.
 * It handles routing between different admin pages and provides global contexts.
 *
 * Free build only: premium pages are not loaded in this app bundle.
 */

import React, { useState, useEffect, lazy, Suspense } from 'react';
import { __ } from '@wordpress/i18n';
import { Spinner } from '@wordpress/components';

// Initialize WordPress URL helpers (must be loaded early)
import './utils/urls';

// Setup apiFetch middleware
import setupApiFetch from './utils/setupApiFetch';

// Context Providers
import { LicenseProvider } from './contexts/LicenseContext';
import { NotificationProvider } from './contexts/NotificationContext';
import { UserPreferencesProvider } from './contexts/UserPreferencesContext';

// Global Components
import ToastContainer from './components/ToastContainer';
import ErrorBoundary from './components/ErrorBoundary';
import CommandPalette from './components/CommandPalette';

// Shared admin styles and prefixed Tailwind utilities must ship with the main
// app entry so routed pages keep both the base shell and utility layout rules.
import './styles/main.css';

// Always loaded pages
import Dashboard from './pages/Dashboard';

// Lazy load heavy pages to reduce initial bundle size
const OnPageSEO = lazy(() => import(/* webpackMode: "eager" */ './pages/OnPageSEO'));
const Performance = lazy(() => import(/* webpackMode: "eager" */ './pages/Performance'));
const TechnicalSEO = lazy(() => import(/* webpackMode: "eager" */ './pages/TechnicalSEO'));
const Support = lazy(() => import(/* webpackMode: "eager" */ './pages/Support'));
const ImportExport = lazy(() => import(/* webpackMode: "eager" */ './pages/ImportExport'));
const InternalLinking = lazy(() => import(/* webpackMode: "eager" */ './pages/InternalLinking'));
const BulkEdit = lazy(() => import(/* webpackMode: "eager" */ './pages/BulkEdit'));

// Explicitly import the folder entry to avoid accidentally resolving to
// `pages/SiteAudit.jsx` (legacy shim) when present.
const SiteAudit = lazy(() => import(/* webpackMode: "eager" */ './pages/SiteAudit/index.jsx'));

// App shell overrides extend the shared admin stylesheet above.
import './styles/app-shell-overrides.css';

// Loading component for lazy loaded pages
const PageLoader = () => (
  <div
    style={{
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      minHeight: '400px',
      flexDirection: 'column',
      gap: '16px',
    }}
  >
    <Spinner />
    <p>{__('Loading page…', 'prorank-seo')}</p>
  </div>
);

/**
 * Main App Component
 */
const App = () => {
  const [currentPage, setCurrentPage] = useState('');
  const [isReady, setIsReady] = useState(false);

  // Setup apiFetch on mount
  useEffect(() => {
    setupApiFetch();
  }, []);

  useEffect(() => {
    // Get the current page from URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const page = urlParams.get('page');
    const tab = urlParams.get('tab');
    const pageValue = page || '';

    if (pageValue === 'prorank-seo') {
      // The unified dashboard uses `tab` as its section router.
      setCurrentPage(tab || 'dashboard');
    } else if (pageValue.startsWith('prorank-')) {
      // Dedicated admin pages keep their own page slug even when they have
      // secondary `tab` parameters for in-page navigation.
      const subPage = pageValue.replace('prorank-', '');
      setCurrentPage(subPage);
    } else {
      setCurrentPage('dashboard');
    }

    setIsReady(true);
  }, []);


  /**
   * Render the appropriate page component based on current page
   * Following IA v9.4 structure
   *
   * Premium-only pages always redirect to Dashboard in free build
   */
  const renderPage = () => {
    switch (currentPage) {
      case 'dashboard':
      case '':
        return <Dashboard />;

      case 'on-page-seo':
        // Check if we're on the internal-linking tab
        const onPageUrlParams = new URLSearchParams(window.location.search);
        const onPageTab = onPageUrlParams.get('tab');
        if (onPageTab === 'internal-linking') {
          return <InternalLinking />;
        }
        return <OnPageSEO />;

      case 'performance':
        return <Performance />;

      case 'technical-seo':
        return <TechnicalSEO />;

      // Premium pages - redirect to Dashboard in free build
      case 'local-seo':
        return <Dashboard />;

      case 'woocommerce':
      case 'ecommerce-seo':
        return <Dashboard />;

      case 'analytics':
        return <Dashboard />;

      case 'ai-tools':
        return <Dashboard />;

      case 'site-audit':
        if (!SiteAudit) return <Dashboard />;
        // Check if we're on the import-export tab
        const urlParams = new URLSearchParams(window.location.search);
        const tab = urlParams.get('tab');
        if (tab === 'import-export') {
          return <ImportExport />;
        }
        return <SiteAudit />;

      case 'agency-hub':
        return <Dashboard />;

      case 'support':
        return <Support />;

      // Specific sub-pages
      case 'tools':
      case 'import-export':
        return <ImportExport />;

      case 'social':
        return <Dashboard />; // Using Dashboard temporarily as Social component doesn't exist

      case 'internal-linking':
        return <InternalLinking />;

      case 'bulk-edit':
        return <BulkEdit />;

      default:
        // If page not found, show dashboard
        return <Dashboard />;
    }
  };

  if (!isReady) {
    return (
      <div className="prorank-loading">
        <span className="spinner is-active"></span>
        <span className="prorank-loading-text">{__('Loading ProRank SEO…', 'prorank-seo')}</span>
      </div>
    );
  }

  return (
    <ErrorBoundary>
      <LicenseProvider>
        <NotificationProvider>
          <UserPreferencesProvider>
            <div className="prorank-admin-app prorankAdmin" data-page={currentPage}>
              <div className="prorank-admin-content">
                <Suspense fallback={<PageLoader />}>{renderPage()}</Suspense>
              </div>

              <ToastContainer />

              {/* Global Command Palette */}
              <CommandPalette />
            </div>
          </UserPreferencesProvider>
        </NotificationProvider>
      </LicenseProvider>
    </ErrorBoundary>
  );
};

// Export for potential use in other files
export default App;
