import React, { useEffect, useRef, useState } from 'react';
import {
  HashRouter as Router,
  Routes,
  Route,
  useLocation,
  useNavigate,
} from 'react-router-dom';
import { LuMenu } from 'react-icons/lu';

import { recomaze_ai_personalization_env } from './env';
import { SidebarProvider, useSidebar } from './context/sidebar.context';
import Support from './pages/Support';
import Settings from './pages/Settings';
import SideBar from './components/layout/SideBar';
import Customization from './pages/Customization';
import ImportProducts from './pages/ImportProducts';
import { useAppStateContext } from './context/user.data.context';
import Pricing from './pages/Pricing';
import AgenticFeedPage from './pages/AgenticFeed';
import AiVisibility from './pages/AiVisibility';
import AiVisibilityContents from './pages/AiVisibilityContents';
import AiVisibilityPageTemplates from './pages/AiVisibilityPageTemplates';
import ProductImprovements from './pages/ProductImprovements';
import LlmTxtPage from './pages/LlmTxt';
import AgentAnalytics from './pages/AgentAnalytics';
import KnowledgeBase from './pages/KnowledgeBase';
import ContentGenerator from './pages/ContentGenerator';
import ContentChecker from './pages/ContentChecker';
import OptimizedTextPages from './pages/OptimizedTextPages';
import PromptTemplatesPage from './pages/PromptTemplatesPage';
import Campaigns from './pages/Campaigns';
import CampaignCreate from './pages/CampaignCreate';
import CampaignDetail from './pages/CampaignDetail';
import CatalogQuality from './pages/CatalogQuality';
import Connectors from './pages/Connectors';
import Dashboard from './pages/Dashboard';
import CompanyId from './pages/CompanyId';
import SignupMirror from './pages/SignupMirror';
import LaunchDiscount from './pages/LaunchDiscount';
import OnboardingChain from './pages/OnboardingChain';
import { useAccessControl } from './hooks/useAccessControl';
import { signupMirrorRedirect } from './lib/signup-mirror/access';
import PreviewBanner from './components/PreviewBanner';
import { updatePreviewMode } from './service/user/user.service';
import VerificationModal from './components/VerificationModal';
import ErrorBoundary from './components/ErrorBoundary';
import { CopilotPanel } from './components/copilot/CopilotPanel';
import StoreContextAnnounceModal from './components/visibility/StoreContextAnnounceModal';
import { canSeeBetaVisibilityFeatures } from './components/visibility/beta-access';
import { listBrands } from './service/visibility/visibility.service';

const BARE_ROUTES = ['/signup-mirror', '/launch-discount', '/onboarding-chain'];

const MobileTopBar = (): JSX.Element => {
  const { setMobileOpen } = useSidebar();
  const logo = recomaze_ai_personalization_env?.plugin_icon;

  return (
    <div className="sticky top-0 z-30 flex items-center gap-2 border-b border-gray-200 bg-white px-4 py-2 lg:hidden">
      <button
        type="button"
        onClick={() => setMobileOpen(true)}
        aria-label="Open navigation"
        className="inline-flex h-9 w-9 items-center justify-center rounded-lg border border-gray-200 text-gray-700 outline-none focus:outline-none"
      >
        <LuMenu className="h-5 w-5" aria-hidden />
      </button>
      {logo ? (
        <img src={logo} alt="Recomaze" className="h-6 w-6 rounded" />
      ) : null}
      <span className="text-sm font-semibold text-gray-900">Recomaze</span>
    </div>
  );
};

// Everything that needs router hooks (useLocation / useNavigate) lives here,
// inside <Router>. This is also where the Signup Mirror resume redirect fires
// and where the full-screen onboarding routes bypass the app chrome.
const AppShell = (): JSX.Element => {
  const { token, clientId, user, setUser } = useAppStateContext();
  const { canAccessAllRoutes, canSeeBulkUpload } = useAccessControl(user);
  const location = useLocation();
  const navigate = useNavigate();
  const resumedRef = useRef(false);

  useEffect(() => {
    if (resumedRef.current || !user) return;
    if (location.pathname !== '/' && location.pathname !== '/dashboard') return;
    const target = signupMirrorRedirect(user);
    if (target) {
      resumedRef.current = true;
      navigate(target, { replace: true });
    }
  }, [user, location.pathname, navigate]);

  const [announceBrandId, setAnnounceBrandId] = useState<string | null>(null);
  const canSeeVisibility = Boolean(
    clientId && canSeeBetaVisibilityFeatures(clientId)
  );
  useEffect(() => {
    if (!token || !clientId || !canSeeVisibility) return;
    let cancelled = false;
    listBrands(clientId, token)
      .then(list => {
        if (!cancelled) setAnnounceBrandId(list.brands[0]?.brand_id ?? null);
      })
      .catch(() => {});
    return () => {
      cancelled = true;
    };
  }, [token, clientId, canSeeVisibility]);

  const handleActivatePreview = async () => {
    if (!token) return;
    try {
      await updatePreviewMode({ token, preview_mode: true });
      if (user) setUser({ ...user, preview_mode: true });
    } catch (error) {
      console.error('Error enabling preview mode:', error);
    }
  };

  const handleDeactivatePreview = async () => {
    if (!token) return;
    try {
      await updatePreviewMode({ token, preview_mode: false });
      if (user) setUser({ ...user, preview_mode: false });
    } catch (error) {
      console.error('Error disabling preview mode:', error);
    }
  };

  // Full-screen onboarding routes: no sidebar, no banners, no copilot.
  if (BARE_ROUTES.includes(location.pathname)) {
    return (
      <ErrorBoundary>
        <Routes>
          <Route path="/signup-mirror" element={<SignupMirror />} />
          <Route path="/launch-discount" element={<LaunchDiscount />} />
          <Route path="/onboarding-chain" element={<OnboardingChain />} />
        </Routes>
      </ErrorBoundary>
    );
  }

  return (
    <div
      id="recomaze-app-container"
      // No w-full here: on a fixed element `width: 100%` wins over `right: 0`,
      // which pushed the shell (and the copilot with it) off the right edge.
      className="relative flex overflow-hidden bg-white"
      // Pinned to the viewport (position: fixed) by the admin stylesheet in
      // Recomaze_Admin::enqueue_styles, so scrolling the WordPress admin menu
      // never drags the app off-screen. The app owns its own scroll: main
      // scrolls internally and the copilot stays a real right-hand column.
    >
      <SideBar />
      <div className="flex min-w-0 flex-1 flex-col overflow-hidden">
        <MobileTopBar />
        <main
          id="main"
          className="min-w-0 flex-1 overflow-y-auto overflow-x-hidden pb-16"
        >
          <VerificationModal />
          <div className="mx-auto w-full max-w-[1600px] px-6 pt-6 md:px-10 md:pt-10">
            <PreviewBanner
              token={token}
              domain={recomaze_ai_personalization_env?.domain ?? null}
              previewMode={user?.preview_mode ?? false}
              documentationReady={user?.first_documentation_created ?? false}
              onActivatePreview={handleActivatePreview}
              onDeactivatePreview={handleDeactivatePreview}
            />
          </div>
          {!canAccessAllRoutes ? (
            <Routes>
              <Route path="/" element={<Pricing />}></Route>
            </Routes>
          ) : (
            <ErrorBoundary>
              <Routes>
                <Route path="/" element={<Dashboard />} />
                <Route path="/dashboard" element={<Dashboard />} />
                <Route path="/customization" element={<Customization />} />
                <Route path="/catalog-quality" element={<CatalogQuality />} />
                <Route path="/agent-analytics" element={<AgentAnalytics />} />
                <Route path="/agentic-feed" element={<AgenticFeedPage />} />
                <Route path="/connectors" element={<Connectors />} />
                <Route path="/company-id" element={<CompanyId />} />
                <Route path="/ai-visibility" element={<AiVisibility />} />
                <Route
                  path="/ai-visibility/contents"
                  element={<AiVisibilityContents />}
                />
                <Route
                  path="/ai-visibility/page-templates"
                  element={<AiVisibilityPageTemplates />}
                />
                <Route path="/llm" element={<LlmTxtPage />} />
                <Route
                  path="/product-improvements"
                  element={
                    canSeeBulkUpload ? <ProductImprovements /> : <Pricing />
                  }
                />
                <Route
                  path="/content-generator"
                  element={<ContentGenerator />}
                />
                <Route
                  path="/content-generator/prompt-templates"
                  element={<PromptTemplatesPage />}
                />
                <Route
                  path="/content-generator/content-checker"
                  element={<ContentChecker />}
                />
                <Route
                  path="/content-generator/optimized-pages"
                  element={<OptimizedTextPages />}
                />
                <Route path="/campaigns" element={<Campaigns />} />
                <Route path="/campaigns/create" element={<CampaignCreate />} />
                <Route path="/campaigns/:id" element={<CampaignDetail />} />
                <Route path="/knowledge-base" element={<KnowledgeBase />} />
                <Route path="/pricing" element={<Pricing />} />
                <Route path="/import" element={<ImportProducts />} />
                <Route path="/settings" element={<Settings />} />
                <Route path="/support" element={<Support />} />
              </Routes>
            </ErrorBoundary>
          )}
        </main>
      </div>
      {token && clientId ? (
        <CopilotPanel token={token} clientId={clientId} />
      ) : null}
      {token && clientId && canSeeVisibility ? (
        <StoreContextAnnounceModal
          clientId={clientId}
          token={token}
          brandId={announceBrandId}
        />
      ) : null}
    </div>
  );
};

const App = (): JSX.Element => {
  const {
    token,
    clientId,
    user,
    setToken,
    setClientId,
    fetchUser,
    setCanUseWpApi,
  } = useAppStateContext();

  useEffect(() => {
    if (!token && recomaze_ai_personalization_env?.auth?.token)
      setToken(recomaze_ai_personalization_env?.auth?.token);
    if (!clientId && recomaze_ai_personalization_env?.auth?.client_id)
      setClientId(recomaze_ai_personalization_env?.auth?.client_id);
    if (!user && token) fetchUser();
    if (!recomaze_ai_personalization_env?.can_use_wp_api) setCanUseWpApi(false);
  }, [token, clientId]);

  return (
    <Router>
      <SidebarProvider>
        <AppShell />
      </SidebarProvider>
    </Router>
  );
};

export default App;
