import { Routes, Route, useLocation } from 'react-router-dom'
import { useEffect, useState, useRef, Suspense, lazy } from 'react'
import Navbar from './components/Navbar'
import Footer from './components/Footer'
import Loading from './components/Loading'
import ScrollToTopButton from './components/ScrollToTopButton'
import Lenis from 'lenis'
import { useSiteVisibility } from './context/useSiteVisibility'

// Resilient lazy loader: retries once on transient Vite dev/chunk fetch glitches
function lazyWithRetry(importer) {
  return lazy(async () => {
    try {
      return await importer()
    } catch {
      await new Promise((resolve) => setTimeout(resolve, 180))
      return await importer()
    }
  })
}

// ─── Unified High-Performance Transition Overlay ───────────────────────────
// Runs pure GPU-composited slide transitions:
// - covering: sweeps smoothly across the screen from the right
// - exiting: sweeps out smoothly to the left uncovering the newly mounted route
// - idle: parked cleanly offscreen with display: none to eliminate any layout interference
function TransitionOverlay({ color, delay = 0, phase }) {
  const isIdle = phase === 'idle'
  const isCovering = phase === 'covering'
  const x = isIdle ? '100%' : isCovering ? '0%' : '-101%'

  return (
    <div
      aria-hidden="true"
      style={{
        position: 'fixed',
        inset: 0,
        backgroundColor: color,
        transform: `translate3d(${x}, 0, 0)`,
        transition: isIdle ? 'none' : `transform 0.32s ${delay}ms cubic-bezier(0.22, 1, 0.36, 1)`,
        display: isIdle ? 'none' : 'block',
        zIndex: 99998,
        pointerEvents: 'none',
        willChange: 'transform',
        contain: 'strict',
      }}
    />
  )
}

// Home is static (first paint). The root cause of earlier dynamic-import failures was a
// content blocker blocking the "PrivacyPolicy" filename (now DataNotice), so secondary pages are lazy again.
import Home from './pages/Home.jsx'
import { pageImports, prefetchRoute } from './utils/routePrefetch'

const About = lazyWithRetry(pageImports.About)
const Services = lazyWithRetry(pageImports.Services)
const MediaCenter = lazyWithRetry(pageImports.MediaCenter)
const AstronomicalTools = lazyWithRetry(pageImports.AstronomicalTools)
const Shop = lazyWithRetry(pageImports.Shop)
const DataNotice = lazyWithRetry(pageImports.DataNotice)
const Disclaimer = lazyWithRetry(pageImports.Disclaimer)
const TermsConditions = lazyWithRetry(pageImports.TermsConditions)
const NotFound = lazyWithRetry(pageImports.NotFound)

// Warm the main navigation chunks while the browser is idle so route changes feel instant.
function prefetchMainRoutes() {
  const run = () => ['About', 'Services', 'MediaCenter', 'AstronomicalTools', 'Shop'].forEach((k) => prefetchRoute(k))
  if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(run, { timeout: 2500 })
  else setTimeout(run, 1200)
}

// Secondary / heavy routes lazy-loaded with retry
const GlobalStars = lazyWithRetry(() => import('./components/GlobalStars.jsx'))
const CourseTemplate = lazyWithRetry(() => import('./pages/CourseTemplate.jsx'))
const Checkout = lazyWithRetry(() => import('./pages/Checkout.jsx'))
const ProductDetailPage = lazyWithRetry(() => import('./pages/ProductDetailPage.jsx'))
const AdminLogin = lazyWithRetry(() => import('./pages/admin/AdminLogin.jsx'))
const AdminDashboard = lazyWithRetry(() => import('./pages/admin/AdminDashboard.jsx'))
const AstroCalendar = lazyWithRetry(() => import('./pages/tools/AstroCalendar.jsx'))
const LiveSkyMap = lazyWithRetry(() => import('./pages/tools/LiveSkyMap.jsx'))
const SatelliteTracker = lazyWithRetry(() => import('./pages/tools/SatelliteTracker.jsx'))

// Student pages & middleware
import ProtectedRoute from './components/ProtectedRoute'
const Login = lazyWithRetry(() => import('./pages/Login.jsx'))
const importDashboard = () => import('./pages/Dashboard.jsx')
const importPlayer = () => import('./pages/Player.jsx')
const Dashboard = lazyWithRetry(importDashboard)
const Player = lazyWithRetry(importPlayer)
const VerifyCertificate = lazyWithRetry(() => import('./pages/VerifyCertificate.jsx'))
const InvoicePage = lazyWithRetry(() => import('./pages/InvoicePage.jsx'))

function App() {
  const location = useLocation()
  const { pages } = useSiteVisibility()

  // ── Lenis smooth scroll ─────────────────────────────────────────────────
  useEffect(() => {
    const lenis = new Lenis({
      duration: 0.85,
      easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      smoothWheel: true,
      syncTouch: false,
    })
    window.__lenis = lenis

    let rafId
    const raf = (time) => {
      lenis.raf(time)
      rafId = requestAnimationFrame(raf)
    }
    rafId = requestAnimationFrame(raf)

    return () => {
      cancelAnimationFrame(rafId)
      lenis.destroy()
      window.__lenis = null
    }
  }, [])

  // ── Top progress bar ────────────────────────────────────────────────────
  const [progress, setProgress] = useState(0)

  // ── Overlay state machine: 'idle' | 'covering' | 'exiting' ──────────────
  const [overlayPhase, setOverlayPhase] = useState('idle')
  const isInitialMount = useRef(true)

  // ── Displayed route (swapped when screen is covered) ─────────────────────
  const [displayLocation, setDisplayLocation] = useState(location)

  // Initial mount: smooth reveal on cold page landing
  useEffect(() => {
    prefetchMainRoutes()
  }, [])

  // Load protected page code alongside the session check. This lets the route
  // move directly from the session gate to its data state without a second
  // full-page Suspense skeleton in between.
  useEffect(() => {
    if (location.pathname === '/dashboard') void importDashboard().catch(() => {})
    else if (/^\/(courses|player)\//.test(location.pathname)) void importPlayer().catch(() => {})
  }, [location.pathname])

  // ── On route change: sync progress bar + seamless strip reveal ─────────
  useEffect(() => {
    if (isInitialMount.current) {
      isInitialMount.current = false
      return
    }

    if (location.pathname === displayLocation.pathname && location.search === displayLocation.search) return

    // Immediately scroll top and sync route state
    window.scrollTo(0, 0)
    if (window.__lenis) window.__lenis.scrollTo(0, { immediate: true })

    // Tools & Admin with heavy WebGL/data canvases swap with progress bar without blocking strips
    const shouldSkipStrips = location.pathname.startsWith('/astronomical-tools/')
      || location.pathname.startsWith('/admin')

    if (shouldSkipStrips) {
      setProgress(60)
      setDisplayLocation(location)
      const t1 = setTimeout(() => setProgress(100), 80)
      const t2 = setTimeout(() => setProgress(0), 320)
      return () => {
        clearTimeout(t1)
        clearTimeout(t2)
        setProgress(0)
      }
    }

    // Standard Route Transition:
    // 1. Progress jumps to 70% and strips slide to cover (280ms)
    setProgress(70)
    setOverlayPhase('covering')

    const tCover = setTimeout(() => {
      // 2. Route swapped behind the strips at peak cover, progress hits 100%
      setDisplayLocation(location)
      setProgress(100)
      setOverlayPhase('exiting')

      // 3. Clear progress line smoothly
      const tProgressReset = setTimeout(() => {
        setProgress(0)
      }, 260)

      // 4. Return strips to idle
      const tDone = setTimeout(() => {
        setOverlayPhase('idle')
      }, 420)

      return () => {
        clearTimeout(tProgressReset)
        clearTimeout(tDone)
      }
    }, 280)

    // Hard safety timer to prevent any stuck overlay
    const tSafety = setTimeout(() => {
      setOverlayPhase('idle')
      setProgress(0)
    }, 850)

    return () => {
      clearTimeout(tCover)
      clearTimeout(tSafety)
      setOverlayPhase('idle')
      setProgress(0)
    }
  }, [location])

  const routedLocation = location.pathname.startsWith('/astronomical-tools/')
    || location.pathname.startsWith('/admin')
    ? location
    : displayLocation

  const showGlobalStars = !routedLocation.pathname.startsWith('/courses/')
    && !routedLocation.pathname.startsWith('/player/')

  const showFooter = !routedLocation.pathname.startsWith('/admin')
    && !routedLocation.pathname.startsWith('/courses/')
    && !routedLocation.pathname.startsWith('/player/')
    && routedLocation.pathname !== '/login'

  return (
    <div style={{ position: 'relative', minHeight: '100vh', width: '100%' }}>

      {/* ── Top progress bar (Native CSS transform, GPU accelerated, auto-fades at 100%) ── */}
      <div
        className="fixed top-0 left-0 right-0 h-[3px] z-[99999] pointer-events-none origin-left"
        style={{
          background: 'var(--v3-accent-soft)',
          boxShadow: 'none',
          transform: `scaleX(${progress / 100}) translateZ(0)`,
          opacity: progress > 0 ? 1 : 0,
          transition: progress === 0
            ? 'opacity 0.25s ease-out'
            : progress === 100
              ? 'transform 0.18s cubic-bezier(0.1, 0.9, 0.2, 1), opacity 0.12s ease-in'
              : 'transform 0.28s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.12s ease-in',
          willChange: 'transform, opacity',
        }}
      />

      {/* ── Staggered 3-strip GPU Hardware-Accelerated Transition Overlay ────
          Shared CosmaNeX V3 surfaces and navy accent */}
      <TransitionOverlay color="var(--v3-panel)" delay={0} phase={overlayPhase} />
      <TransitionOverlay color="var(--v3-ink)" delay={40} phase={overlayPhase} />
      <TransitionOverlay color="var(--v3-space)" delay={80} phase={overlayPhase} />

      {/* ── Page shell ───────────────────────────────────────────── */}
      <div className="page-content" style={{ position: 'relative', zIndex: 2 }}>
        {showGlobalStars && (
          <Suspense fallback={null}>
            <GlobalStars />
          </Suspense>
        )}
        <Navbar />
        <ScrollToTopButton />

        <div className="min-h-screen flex flex-col">
            <div className="flex-1">
              <div className={`site-v3-theme ${routedLocation.pathname === '/' ? 'site-v3-home' : 'site-v3-subpage'}`}>
              <Suspense fallback={<Loading />}>
                <Routes location={routedLocation}>
                <Route path="/" element={pages.home ? <Home /> : <NotFound />} />
                <Route path="/about-us" element={pages.about ? <About /> : <NotFound />} />

                {/* Student Access & Portal */}
                <Route path="/login" element={<Login />} />
                <Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />
                <Route path="/courses/:courseId" element={<ProtectedRoute><Player /></ProtectedRoute>} />
                <Route path="/player/:courseId" element={<ProtectedRoute><Player /></ProtectedRoute>} />
                <Route path="/verify-certificate/:verificationId" element={<VerifyCertificate />} />
                <Route path="/verify-certificate" element={<VerifyCertificate />} />
                <Route path="/verify/:verificationId" element={<VerifyCertificate />} />
                <Route path="/verify" element={<VerifyCertificate />} />

                {/* Services */}
                <Route path="/services" element={pages.services ? <Services /> : <NotFound />} />
                <Route path="/programs/:slug" element={pages.services ? <CourseTemplate key={routedLocation.pathname} /> : <NotFound />} />
                <Route path="/course/:slug" element={pages.services ? <CourseTemplate key={routedLocation.pathname} /> : <NotFound />} />

                {/* Media */}
                <Route path="/media" element={pages.media ? <MediaCenter /> : <NotFound />} />
                <Route path="/gallery" element={pages.media ? <MediaCenter /> : <NotFound />} />

                {/* Shop */}
                <Route path="/shop" element={pages.shop ? <Shop /> : <NotFound />} />
                <Route path="/shop/checkout" element={<ProtectedRoute><Checkout /></ProtectedRoute>} />
                <Route path="/shop/product/:id" element={pages.shop ? <ProductDetailPage /> : <NotFound />} />
                <Route path="/invoice" element={<InvoicePage />} />

                {/* Admin */}
                <Route path="/admin" element={<ProtectedRoute allowedRoles={['Admin']} loginPath="/admin/login"><AdminDashboard /></ProtectedRoute>} />
                <Route path="/admin/login" element={<AdminLogin />} />
                <Route path="/admin/dashboard" element={<ProtectedRoute allowedRoles={['Admin']} loginPath="/admin/login"><AdminDashboard /></ProtectedRoute>} />

                {/* Other */}
                <Route path="/astronomical-tools" element={pages.tools ? <AstronomicalTools /> : <NotFound />} />
                <Route path="/astronomical-tools/astro-calendar" element={pages.tools && pages.astroCalendar ? <AstroCalendar /> : <NotFound />} />
                <Route path="/astronomical-tools/live-sky-map" element={pages.tools && pages.liveSkyMap ? <LiveSkyMap /> : <NotFound />} />
                <Route path="/astronomical-tools/satellite-tracker" element={pages.tools && pages.satelliteTracker ? <SatelliteTracker /> : <NotFound />} />
                <Route path="/privacy-policy" element={<DataNotice />} />
                <Route path="/disclaimer" element={<Disclaimer />} />
                <Route path="/terms-and-conditions" element={<TermsConditions />} />

                <Route path="*" element={<NotFound />} />
                </Routes>
              </Suspense>
              </div>
            </div>
            {showFooter && <Footer />}
        </div>
      </div>
    </div>
  )
}

export default App
