import '@vly-ai/integrations';
import { Toaster } from "@/components/ui/sonner";
import { WhatsAppButton } from "@/components/site/WhatsAppButton";
import { RequireAdmin } from "@/components/RequireAdmin";
import { RequireAuth } from "@/components/RequireAuth";
import { VlyToolbar } from "../vly-toolbar-readonly.tsx";
import { ConvexAuthProvider } from "@convex-dev/auth/react";
import { ConvexReactClient } from "convex/react";
import React, { StrictMode, useEffect, lazy, Suspense } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Route, Routes, useLocation } from "react-router";
import { I18nProvider } from "@/lib/i18n";
import "./index.css";

// Lazy load route components for better code splitting
const Landing = lazy(() => import("./pages/Landing.tsx"));
const AuthPage = lazy(() => import("./pages/Auth.tsx"));
const Dashboard = lazy(() => import("./pages/Dashboard.tsx"));
const NotFound = lazy(() => import("./pages/NotFound.tsx"));
const LeadPage = lazy(() => import("./pages/LeadPage.tsx"));
const AiAutomation = lazy(() => import("./pages/AiAutomation.tsx"));
const About = lazy(() => import("./pages/About.tsx"));
const AiAgents = lazy(() => import("./pages/AiAgents.tsx"));
const TechnologyServices = lazy(() => import("./pages/TechnologyServices.tsx"));
const BusinessAutomation = lazy(() => import("./pages/services/BusinessAutomation.tsx"));
const WorkflowAutomation = lazy(() => import("./pages/services/WorkflowAutomation.tsx"));
const CustomAiDevelopment = lazy(() => import("./pages/services/CustomAiDevelopment.tsx"));
const AiIntegrations = lazy(() => import("./pages/services/AiIntegrations.tsx"));
const CloudInfra = lazy(() => import("./pages/services/CloudInfra.tsx"));
const SolutionsPage = lazy(() => import("./pages/Solutions.tsx"));
const IndustriesPage = lazy(() => import("./pages/Industries.tsx"));
const IndustryPage = lazy(() => import("./pages/IndustryPage.tsx"));
const CaseStudies = lazy(() => import("./pages/CaseStudies.tsx"));
const AutomationAssessment = lazy(() => import("./pages/AutomationAssessment.tsx"));
const AiSalesAgent = lazy(() => import("./pages/agents/AiSalesAgent.tsx"));
const AiSupportAgent = lazy(() => import("./pages/agents/AiSupportAgent.tsx"));
const AiWhatsappAgent = lazy(() => import("./pages/agents/AiWhatsappAgent.tsx"));
const AiReceptionist = lazy(() => import("./pages/agents/AiReceptionist.tsx"));
const AiKnowledgeAgent = lazy(() => import("./pages/agents/AiKnowledgeAgent.tsx"));
const AiOperationsAgent = lazy(() => import("./pages/agents/AiOperationsAgent.tsx"));
const AiHrAgent = lazy(() => import("./pages/agents/AiHrAgent.tsx"));
const WebDevelopment = lazy(() => import("./pages/services/WebDevelopment.tsx"));
const SoftwareDevelopment = lazy(() => import("./pages/services/SoftwareDevelopment.tsx"));
const MobileAppDevelopment = lazy(() => import("./pages/services/MobileAppDevelopment.tsx"));
const EcommerceDevelopment = lazy(() => import("./pages/services/EcommerceDevelopment.tsx"));
const Cybersecurity = lazy(() => import("./pages/services/Cybersecurity.tsx"));
const DigitalMarketing = lazy(() => import("./pages/services/DigitalMarketing.tsx"));
const PerformanceMarketing = lazy(() => import("./pages/services/PerformanceMarketing.tsx"));
const GisMapping = lazy(() => import("./pages/services/GisMapping.tsx"));
const LidarProcessing = lazy(() => import("./pages/services/LidarProcessing.tsx"));
const WebHosting = lazy(() => import("./pages/services/WebHosting.tsx"));
const ThreatModelling = lazy(() => import("./pages/cybersecurity/ThreatModelling.tsx"));
const RiskManagement = lazy(() => import("./pages/cybersecurity/RiskManagement.tsx"));
const VulnerabilityManagement = lazy(() => import("./pages/cybersecurity/VulnerabilityManagement.tsx"));
const PenetrationTesting = lazy(() => import("./pages/cybersecurity/PenetrationTesting.tsx"));
const ApplicationSecurity = lazy(() => import("./pages/cybersecurity/ApplicationSecurity.tsx"));
const SecurityArchitecture = lazy(() => import("./pages/cybersecurity/SecurityArchitecture.tsx"));
const SecurityAudits = lazy(() => import("./pages/cybersecurity/SecurityAudits.tsx"));
const IndustrialCybersecurity = lazy(() => import("./pages/cybersecurity/IndustrialCybersecurity.tsx"));
const SecurityMonitoringSiem = lazy(() => import("./pages/cybersecurity/SecurityMonitoringSiem.tsx"));
const EndpointDetection = lazy(() => import("./pages/cybersecurity/EndpointDetection.tsx"));
const RegulatoryCompliance = lazy(() => import("./pages/cybersecurity/RegulatoryCompliance.tsx"));
const AiSolutions = lazy(() => import("./pages/AiSolutions.tsx"));
const Blog = lazy(() => import("./pages/Blog.tsx"));
const Faq = lazy(() => import("./pages/Faq.tsx"));
const Pricing = lazy(() => import("./pages/Pricing.tsx"));
const Store = lazy(() => import("./pages/Store.tsx"));
const Support = lazy(() => import("./pages/Support.tsx"));
const BlogPost = lazy(() => import("./pages/BlogPost.tsx"));
const Privacy = lazy(() => import("./pages/Privacy.tsx"));
const Terms = lazy(() => import("./pages/Terms.tsx"));
const Refunds = lazy(() => import("./pages/Refunds.tsx"));

// Admin panel
const AdminLayout = lazy(() => import("./pages/admin/AdminLayout.tsx"));
const AdminDashboard = lazy(() => import("./pages/admin/AdminDashboard.tsx"));
const AdminLeads = lazy(() => import("./pages/admin/AdminLeads.tsx"));
const AdminQuotes = lazy(() => import("./pages/admin/AdminQuotes.tsx"));
const AdminCustomers = lazy(() => import("./pages/admin/AdminCustomers.tsx"));
const AdminPages = lazy(() => import("./pages/admin/AdminPages.tsx"));
const AdminHomepage = lazy(() => import("./pages/admin/AdminHomepage.tsx"));
const AdminMenus = lazy(() => import("./pages/admin/AdminMenus.tsx"));
const AdminBlog = lazy(() => import("./pages/admin/AdminBlog.tsx"));
const AdminServices = lazy(() => import("./pages/admin/AdminServices.tsx"));
const AdminFaqs = lazy(() => import("./pages/admin/AdminFaqs.tsx"));
const AdminTestimonials = lazy(() => import("./pages/admin/AdminTestimonials.tsx"));
const AdminAgents = lazy(() => import("./pages/admin/AdminAgents.tsx"));
const AdminKnowledge = lazy(() => import("./pages/admin/AdminKnowledge.tsx"));
const AdminConversations = lazy(() => import("./pages/admin/AdminConversations.tsx"));
const AdminProducts = lazy(() => import("./pages/admin/AdminProducts.tsx"));
const AdminOrders = lazy(() => import("./pages/admin/AdminOrders.tsx"));
const AdminCoupons = lazy(() => import("./pages/admin/AdminCoupons.tsx"));
const AdminReviews = lazy(() => import("./pages/admin/AdminReviews.tsx"));
const AdminTickets = lazy(() => import("./pages/admin/AdminTickets.tsx"));
const AdminUsers = lazy(() => import("./pages/admin/AdminUsers.tsx"));
const AdminRoles = lazy(() => import("./pages/admin/AdminRoles.tsx"));
const AdminNotifications = lazy(() => import("./pages/admin/AdminNotifications.tsx"));
const AdminAudit = lazy(() => import("./pages/admin/AdminAudit.tsx"));
const AdminRedirects = lazy(() => import("./pages/admin/AdminRedirects.tsx"));
const AdminBackup = lazy(() => import("./pages/admin/AdminBackup.tsx"));
const AdminSettings = lazy(() => import("./pages/admin/AdminSettings.tsx"));

// Simple loading fallback for route transitions
function RouteLoading() {
  return (
    <div className="min-h-screen flex items-center justify-center">
      <div className="animate-pulse text-muted-foreground">Loading...</div>
    </div>
  );
}

/** Silent error boundary — if VlyToolbar crashes it renders nothing instead of
 *  crashing the whole app (e.g. hook errors in WebContainer environment). */
class ToolbarErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean }
> {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  componentDidCatch(err: Error) {
    console.warn("[VlyToolbar] Caught error, toolbar disabled:", err.message);
  }
  render() {
    return this.state.hasError ? null : this.props.children;
  }
}

/** Hard guard so runtime errors never leave the preview as a blank page. */
class RootErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean; message: string; stack: string }
> {
  state = { hasError: false, message: "", stack: "" };
  static getDerivedStateFromError(error: Error) {
    return {
      hasError: true,
      message: error.message || "Unknown runtime error",
      stack: error.stack || "",
    };
  }
  componentDidCatch(err: Error) {
    console.error("[WebContainer preview] Root crash:", err);
  }
  render() {
    if (this.state.hasError) {
      return (
        <div className="min-h-screen flex items-center justify-center bg-background text-foreground p-6">
          <div className="max-w-lg text-center">
            <p className="text-sm font-semibold">Preview runtime error</p>
            <p className="mt-2 text-xs text-muted-foreground break-words">
              {this.state.message}
            </p>
            {this.state.stack && (
              <pre className="mt-3 text-left text-[10px] leading-4 text-muted-foreground/80 max-h-40 overflow-auto rounded border border-border/60 p-2">
                {this.state.stack}
              </pre>
            )}
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string);



/** Scrolls to the top of the window on every route change. */
function ScrollToTop() {
  const { pathname } = useLocation();
  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);
  return null;
}

function RouteSyncer() {
  const location = useLocation();
  useEffect(() => {
    window.parent.postMessage(
      { type: "iframe-route-change", path: location.pathname },
      "*",
    );
  }, [location.pathname]);

  useEffect(() => {
    function handleMessage(event: MessageEvent) {
      if (event.data?.type === "navigate") {
        if (event.data.direction === "back") window.history.back();
        if (event.data.direction === "forward") window.history.forward();
      }
    }
    window.addEventListener("message", handleMessage);
    return () => window.removeEventListener("message", handleMessage);
  }, []);

  return null;
}


createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <RootErrorBoundary>
      <ToolbarErrorBoundary>
        <VlyToolbar />
      </ToolbarErrorBoundary>
      <ConvexAuthProvider client={convex}>
        <I18nProvider>
        <BrowserRouter>
          <ScrollToTop />
          <RouteSyncer />
          <Suspense fallback={<RouteLoading />}>
            <Routes>
              <Route path="/" element={<Landing />} />
              <Route path="/consult" element={<LeadPage mode="consultation" />} />
              <Route path="/quote" element={<LeadPage mode="quote" />} />
              <Route path="/contact" element={<LeadPage mode="contact" />} />
              <Route path="/ai-automation" element={<AiAutomation />} />
              <Route path="/ai-agents" element={<AiAgents />} />
              <Route path="/business-automation" element={<BusinessAutomation />} />
              <Route path="/workflow-automation" element={<WorkflowAutomation />} />
              <Route path="/custom-ai-development" element={<CustomAiDevelopment />} />
              <Route path="/ai-integrations" element={<AiIntegrations />} />
              <Route path="/ai-sales-agent" element={<AiSalesAgent />} />
              <Route path="/ai-customer-support-agent" element={<AiSupportAgent />} />
              <Route path="/ai-whatsapp-agent" element={<AiWhatsappAgent />} />
              <Route path="/ai-receptionist" element={<AiReceptionist />} />
              <Route path="/ai-knowledge-agent" element={<AiKnowledgeAgent />} />
              <Route path="/ai-operations-agent" element={<AiOperationsAgent />} />
              <Route path="/ai-hr-agent" element={<AiHrAgent />} />
              <Route path="/solutions" element={<SolutionsPage />} />
              <Route path="/solutions/cybersecurity" element={<Cybersecurity />} />
              <Route path="/solutions/software-development" element={<SoftwareDevelopment />} />
              <Route path="/solutions/web-development" element={<WebDevelopment />} />
              <Route path="/solutions/mobile-app-development" element={<MobileAppDevelopment />} />
              <Route path="/solutions/ecommerce-development" element={<EcommerceDevelopment />} />
              <Route path="/solutions/cloud" element={<CloudInfra />} />
              <Route path="/solutions/gis" element={<GisMapping />} />
              <Route path="/solutions/lidar" element={<LidarProcessing />} />
              <Route path="/solutions/digital-marketing" element={<DigitalMarketing />} />
              <Route path="/solutions/performance-marketing" element={<PerformanceMarketing />} />
              <Route path="/solutions/hosting" element={<WebHosting />} />
              <Route path="/industries" element={<IndustriesPage />} />
              <Route path="/industries/:slug" element={<IndustryPage />} />
              <Route path="/case-studies" element={<CaseStudies />} />
              <Route path="/automation-assessment" element={<AutomationAssessment />} />
              <Route path="/services/ai-automation" element={<AiAutomation />} />
              <Route path="/services/ai-agents" element={<AiAgents />} />
              <Route path="/services/ai-solutions" element={<AiSolutions />} />
              <Route path="/services/technology-services" element={<TechnologyServices />} />
              <Route path="/services/web-development" element={<WebDevelopment />} />
              <Route path="/services/software-development" element={<SoftwareDevelopment />} />
              <Route path="/services/mobile-app-development" element={<MobileAppDevelopment />} />
              <Route path="/services/ecommerce-development" element={<EcommerceDevelopment />} />
              <Route path="/services/cybersecurity" element={<Cybersecurity />} />
              <Route path="/services/cybersecurity/threat-modelling" element={<ThreatModelling />} />
              <Route path="/services/cybersecurity/risk-management" element={<RiskManagement />} />
              <Route path="/services/cybersecurity/vulnerability-management" element={<VulnerabilityManagement />} />
              <Route path="/services/cybersecurity/penetration-testing" element={<PenetrationTesting />} />
              <Route path="/services/cybersecurity/application-security" element={<ApplicationSecurity />} />
              <Route path="/services/cybersecurity/security-architecture" element={<SecurityArchitecture />} />
              <Route path="/services/cybersecurity/security-audits-compliance" element={<SecurityAudits />} />
              <Route path="/services/cybersecurity/industrial-cybersecurity" element={<IndustrialCybersecurity />} />
              <Route path="/services/cybersecurity/security-monitoring-siem" element={<SecurityMonitoringSiem />} />
              <Route path="/services/cybersecurity/endpoint-detection-response" element={<EndpointDetection />} />
              <Route path="/services/cybersecurity/regulatory-compliance" element={<RegulatoryCompliance />} />
              <Route path="/services/digital-marketing" element={<DigitalMarketing />} />
              <Route path="/services/gis-mapping" element={<GisMapping />} />
              <Route path="/services/lidar-data-processing" element={<LidarProcessing />} />
              <Route path="/services/web-hosting-infrastructure" element={<WebHosting />} />
              <Route path="/about" element={<About />} />
              <Route path="/blog" element={<Blog />} />
              <Route path="/blog/:slug" element={<BlogPost />} />
              <Route path="/faq" element={<Faq />} />
              <Route path="/pricing" element={<Pricing />} />
              <Route path="/store" element={<Store />} />
              <Route path="/support" element={<Support />} />
              <Route path="/privacy" element={<Privacy />} />
              <Route path="/terms" element={<Terms />} />
              <Route path="/refunds" element={<Refunds />} />
              <Route
                path="/auth"
                element={<AuthPage redirectAfterAuth="/dashboard" />}
              />
              <Route
                path="/dashboard"
                element={
                  <RequireAuth>
                    <Dashboard />
                  </RequireAuth>
                }
              />
              <Route
                path="/admin"
                element={
                  <RequireAdmin>
                    <AdminLayout />
                  </RequireAdmin>
                }
              >
                <Route index element={<AdminDashboard />} />
                <Route path="leads" element={<AdminLeads />} />
                <Route path="quotes" element={<AdminQuotes />} />
                <Route path="customers" element={<AdminCustomers />} />
                <Route path="pages" element={<AdminPages />} />
                <Route path="homepage" element={<AdminHomepage />} />
                <Route path="menus" element={<AdminMenus />} />
                <Route path="blog" element={<AdminBlog />} />
                <Route path="services" element={<AdminServices />} />
                <Route path="faqs" element={<AdminFaqs />} />
                <Route path="testimonials" element={<AdminTestimonials />} />
                <Route path="agents" element={<AdminAgents />} />
                <Route path="knowledge" element={<AdminKnowledge />} />
                <Route path="conversations" element={<AdminConversations />} />
                <Route path="products" element={<AdminProducts />} />
                <Route path="orders" element={<AdminOrders />} />
                <Route path="coupons" element={<AdminCoupons />} />
                <Route path="reviews" element={<AdminReviews />} />
                <Route path="tickets" element={<AdminTickets />} />
                <Route path="users" element={<AdminUsers />} />
                <Route path="roles" element={<AdminRoles />} />
                <Route path="notifications" element={<AdminNotifications />} />
                <Route path="audit" element={<AdminAudit />} />
                <Route path="redirects" element={<AdminRedirects />} />
                <Route path="backup" element={<AdminBackup />} />
                <Route path="settings" element={<AdminSettings />} />
              </Route>
              <Route path="*" element={<NotFound />} />
            </Routes>
          </Suspense>
        </BrowserRouter>
        <Toaster />
        <WhatsAppButton />
        </I18nProvider>
      </ConvexAuthProvider>
    </RootErrorBoundary>
  </StrictMode>,
);
