import { ThemeProvider, useTheme } from './contexts/ThemeContext'
import { WebConfigProvider, useWebConfigContext } from './contexts/WebConfigContext'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import { MusicProvider } from './contexts/MusicContext'
import { clearAllCache } from './utils/cache'
import Navbar from './components/Navbar'
import Announce from './components/announce'
import Footer from './components/footer'
import ScrollToTop from './components/ScrollToTop.jsx'
import DomainStatus from './components/DomainStatus'
import ProtectedAdminRoute from './components/ProtectedAdminRoute'
import LoadingPage from './components/loading_page'
import HelloKittyParticle from './components/HelloKittyParticle'
import ChristmasParticle from './components/ChristmasParticle'
import StarfallParticle from './components/StarfallParticle'
import MimiParticleDisplay from './components/MimiParticleDisplay'
import ChatWidget from './components/ChatWidget'
// import AuthDebugger from './components/AuthDebugger' // Temporarily disabled
import { Routes, Route, useLocation } from 'react-router-dom'
import { lazy, Suspense, useState, useEffect, createContext, useContext } from 'react'

// Lazy load pages for code splitting and faster initial load
const Home = lazy(() => import('./pages/Home'))
const Product = lazy(() => import('./pages/Product'))
const Purchase = lazy(() => import('./pages/purchase'))
const GuestAngpaoPurchase = lazy(() => import('./pages/purchase/GuestAngpao'))
const Topup = lazy(() => import('./pages/Topup'))
const Store = lazy(() => import('./pages/Store'))
const CategoryDetail = lazy(() => import('./pages/CategoryDetail'))
const Auth = lazy(() => import('./pages/auth'))
const History = lazy(() => import('./pages/History'))
const Profile = lazy(() => import('./pages/Profile'))
const MyOrders = lazy(() => import('./pages/MyOrders'))
const MyInstallments = lazy(() => import('./pages/MyInstallments'))
const ReviewPage = lazy(() => import('./pages/Review'))
const TopupHistory = lazy(() => import('./pages/TopupHistory'))
const ProgramStatus = lazy(() => import('./pages/ProgramStatus'))
const Claims = lazy(() => import('./pages/Claims'))
const Minigames = lazy(() => import('./pages/Minigames'))
const MinigameDetail = lazy(() => import('./pages/MinigameDetail'))
const MinigameHistory = lazy(() => import('./pages/MinigameHistory'))
const RedeemCode = lazy(() => import('./pages/RedeemCode'))
const KeyAuth = lazy(() => import('./pages/KeyAuth'))
const NotFound = lazy(() => import('./pages/NotFound'))
const AdminDashboard = lazy(() => import('./pages/admin'))
const AdminStats = lazy(() => import('./pages/admin/Stats'))
const ConfigManagement = lazy(() => import('./pages/admin/ConfigManagement'))
const CustomComponentStudio = lazy(() => import('./pages/admin/CustomComponentStudio'))
const ContactManagement = lazy(() => import('./pages/admin/ContactManagement'))
const StoreConnection = lazy(() => import('./pages/admin/StoreConnection'))
const ProductManagement = lazy(() => import('./pages/admin/ProductManagement'))
const UserManagement = lazy(() => import('./pages/admin/UserManagement'))
const RoleManagement = lazy(() => import('./pages/admin/RoleManagement'))
const OrderManagement = lazy(() => import('./pages/admin/OrderManagement'))
const MinigameManagement = lazy(() => import('./pages/admin/MinigameManagement'))
const MinigamePlayHistory = lazy(() => import('./pages/admin/MinigamePlayHistory'))
const ProgramStatusManagement = lazy(() => import('./pages/admin/ProgramStatusManagement'))
const ClaimManagement = lazy(() => import('./pages/admin/ClaimManagement'))
const RedeemCodeManagement = lazy(() => import('./pages/admin/RedeemCodeManagement'))
const KeyAuthManagement = lazy(() => import('./pages/admin/KeyAuthManagement'))
const ReviewManagement = lazy(() => import('./pages/admin/ReviewManagement'))
const MimiParticleManagement = lazy(() => import('./pages/admin/MimiParticleManagement'))
const InstallmentManagement = lazy(() => import('./pages/admin/InstallmentManagement'))
const AdminChatManagement = lazy(() => import('./pages/admin/AdminChatManagement'))
const TransactionManagement = lazy(() => import('./pages/admin/TransactionManagement'))
const Welcome = lazy(() => import('./pages/Welcome'))

// Preload ทุกหน้าเมื่อเข้าเว็บครั้งแรก (โหลด chunk ไว้ก่อน)
const preloadPageChunks = [
  () => import('./pages/Home'),
  () => import('./pages/Product'),
  () => import('./pages/purchase'),
  () => import('./pages/purchase/GuestAngpao'),
  () => import('./pages/Topup'),
  () => import('./pages/Store'),
  () => import('./pages/CategoryDetail'),
  () => import('./pages/auth'),
  () => import('./pages/History'),
  () => import('./pages/Profile'),
  () => import('./pages/MyOrders'),
  () => import('./pages/MyInstallments'),
  () => import('./pages/Review'),
  () => import('./pages/TopupHistory'),
  () => import('./pages/ProgramStatus'),
  () => import('./pages/Claims'),
  () => import('./pages/Minigames'),
  () => import('./pages/MinigameDetail'),
  () => import('./pages/MinigameHistory'),
  () => import('./pages/RedeemCode'),
  () => import('./pages/KeyAuth'),
  () => import('./pages/NotFound'),
  () => import('./pages/admin'),
  () => import('./pages/admin/Stats'),
  () => import('./pages/admin/ConfigManagement'),
  () => import('./pages/admin/CustomComponentStudio'),
  () => import('./pages/admin/ContactManagement'),
  () => import('./pages/admin/StoreConnection'),
  () => import('./pages/admin/ProductManagement'),
  () => import('./pages/admin/UserManagement'),
  () => import('./pages/admin/RoleManagement'),
  () => import('./pages/admin/OrderManagement'),
  () => import('./pages/admin/MinigameManagement'),
  () => import('./pages/admin/MinigamePlayHistory'),
  () => import('./pages/admin/ProgramStatusManagement'),
  () => import('./pages/admin/ClaimManagement'),
  () => import('./pages/admin/RedeemCodeManagement'),
  () => import('./pages/admin/KeyAuthManagement'),
  () => import('./pages/admin/ReviewManagement'),
  () => import('./pages/admin/MimiParticleManagement'),
  () => import('./pages/admin/InstallmentManagement'),
  () => import('./pages/admin/AdminChatManagement'),
  () => import('./pages/admin/TransactionManagement'),
  () => import('./pages/Welcome')
]

// Loading component for Suspense fallback - uses theme background color
const PageLoader = () => {
  const { theme } = useTheme()
  const backgroundColor = theme?.background_color || '#FFFFFF'
  
  return (
    <div 
      className="flex items-center justify-center"
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: backgroundColor,
        zIndex: 1,
        pointerEvents: 'none'
      }}
    >
      <div 
        className="animate-spin rounded-full h-12 w-12 border-b-2"
        style={{
          borderTopColor: 'transparent',
          borderRightColor: theme?.primary_color || '#8b5cf6',
          borderBottomColor: theme?.primary_color || '#8b5cf6',
          borderLeftColor: theme?.primary_color || '#8b5cf6',
          opacity: 0.5
        }}
      ></div>
    </div>
  )
}
import './App.css'

const PAGE_FADE_MS = 250
const PageTransitionContext = createContext(null)

function AppContent() {
  const { theme, loading: themeLoading } = useTheme()
  const { webConfig, loading: webConfigLoading } = useWebConfigContext()
  const { loading: authLoading } = useAuth()
  const location = useLocation()
  const [displayLocation, setDisplayLocation] = useState(location)
  const [isExiting, setIsExiting] = useState(false)
  const [preloadDone, setPreloadDone] = useState(false)
  const backgroundColor = theme?.background_color || '#FFFFFF'

  // เข้าครั้งแรก: โหลดทุกหน้า (preload chunks) รอไว้ก่อนแล้วค่อยแสดงแอป
  useEffect(() => {
    Promise.all(preloadPageChunks.map((fn) => fn().catch(() => {})))
      .then(() => setPreloadDone(true))
      .catch(() => setPreloadDone(true))
  }, [])

  // เปลี่ยนหน้า: fade opacity down แล้ว fade opacity up ขึ้นหน้าใหม่
  useEffect(() => {
    if (location.key === displayLocation.key) return
    setIsExiting(true)
    const t = setTimeout(() => {
      setDisplayLocation(location)
      setIsExiting(false)
    }, PAGE_FADE_MS)
    return () => clearTimeout(t)
  }, [location, displayLocation.key])

  // ลบ cache ใน localStorage เมื่อรีเฟรชหน้า
  useEffect(() => {
    clearAllCache()
  }, [])

  // Check if current route is admin page
  const isAdminPage = location.pathname.startsWith('/admin')
  
  // Check if all essential data is loaded
  const isInitialLoading = themeLoading || webConfigLoading || authLoading
  
  // Check if we should show LoadingPage (has load_logo and is on home page and not already loaded in this session)
  const shouldShowLoadingPage = webConfig?.load_logo && 
    location.pathname === '/' && 
    !isInitialLoading &&
    sessionStorage.getItem('loadingPageComplete') !== 'true'
  
  // Get background image and opacity from webConfig
  const backgroundImage = webConfig?.background_image
  const backgroundOpacity = webConfig?.background_opacity !== undefined ? webConfig.background_opacity : 1.0

  // Update document title and meta tags when webConfig changes
  useEffect(() => {
    if (webConfig) {
      // Handle font selection
      updateFontSelection(webConfig.font_select)
      
      // Always update title and meta tags with webConfig data (override any default/placeholder values)
      // Check if title needs update (Loading..., empty, or default values)
      const currentTitle = document.title
      const isDefaultTitle = currentTitle === 'Loading...' || 
                            !currentTitle || 
                            currentTitle.trim() === '' ||
                            currentTitle === 'Default Title' ||
                            currentTitle === 'MODELV'
      
      if (webConfig.meta_title && (isDefaultTitle || currentTitle !== webConfig.meta_title)) {
        document.title = webConfig.meta_title
      }
      
      // Always update meta description if webConfig has it (override default/empty values)
      const existingDescription = document.querySelector('meta[name="description"]')?.getAttribute('content')
      const isDefaultDescription = !existingDescription || 
                                  existingDescription.trim() === '' ||
                                  existingDescription === 'Default Description' ||
                                  existingDescription === 'MODELV - Leading Technology Solutions'
      
      if (webConfig.meta_description && (isDefaultDescription || existingDescription !== webConfig.meta_description)) {
        updateMetaTag('description', webConfig.meta_description)
      }
      
      // Update OpenGraph tags
      if (webConfig.meta_title) {
        updateMetaTag('og:title', webConfig.meta_title)
      }
      if (webConfig.meta_description) {
        updateMetaTag('og:description', webConfig.meta_description)
      }
      if (webConfig.site_name) {
        updateMetaTag('og:site_name', webConfig.site_name)
      }
      const metaImage = webConfig.meta_photo || webConfig.site_logo;
      if (metaImage) {
        updateMetaTag('og:image', metaImage)
      }
      
      // Update Twitter Card tags
      if (webConfig.meta_title) {
        updateMetaTag('twitter:title', webConfig.meta_title)
      }
      if (webConfig.meta_description) {
        updateMetaTag('twitter:description', webConfig.meta_description)
      }
      if (metaImage) {
        updateMetaTag('twitter:image', metaImage)
      }
      
      // Update keywords and author
      if (webConfig.meta_keywords) {
        updateMetaTag('keywords', webConfig.meta_keywords)
      }
      if (webConfig.meta_author) {
        updateMetaTag('author', webConfig.meta_author)
      }
      
      // Always update structured data for SEO (this can't be done in index.html)
      updateStructuredData(webConfig)
      
    }
  }, [webConfig, webConfigLoading])

  // Debug: Log particle config (must be before conditional returns)
  useEffect(() => {
    if (webConfig?.particle_id) {
      const shouldShowHelloKitty = webConfig.particle_id.toString().toUpperCase().includes('HELLOKITTY') || 
                                   webConfig.particle_id.toString().toUpperCase().includes('HELLO_KITTY')
      const shouldShowChristmas = webConfig.particle_id.toString().toUpperCase().includes('CHRISTMAS')
      const shouldShowStarfall = webConfig.particle_id.toString().toUpperCase().includes('STARFALL')
      
      console.log('🎄 Particle Debug:', {
        particle_id: webConfig.particle_id,
        particle_id_type: typeof webConfig.particle_id,
        particle_id_string: webConfig.particle_id.toString(),
        shouldShowChristmas: shouldShowChristmas,
        shouldShowHelloKitty: shouldShowHelloKitty,
        shouldShowStarfall: shouldShowStarfall
      })
    }
  }, [webConfig?.particle_id])

  // Helper function to update meta tags (supports both name and property attributes)
  const updateMetaTag = (name, content) => {
    if (!content) return
    
    // Check for both name and property attributes
    let metaTag = document.querySelector(`meta[name="${name}"]`) || document.querySelector(`meta[property="${name}"]`)
    
    if (!metaTag) {
      metaTag = document.createElement('meta')
      // Check if it's an OpenGraph tag (starts with og:) or Twitter tag
      if (name.startsWith('og:') || name.startsWith('twitter:')) {
        metaTag.setAttribute('property', name)
      } else {
        metaTag.setAttribute('name', name)
      }
      document.head.appendChild(metaTag)
    }
    metaTag.setAttribute('content', content)
  }

  // Helper function to update font selection based on webConfig.font_select
  const updateFontSelection = (fontSelect) => {
    if (!fontSelect) return
    
    // Remove existing font links
    const existingFontLinks = document.querySelectorAll('link[href*="fonts.googleapis.com"], link[href*="fonts.gstatic.com"]')
    existingFontLinks.forEach(link => {
      // Only remove font links, not other Google services
      if (link.href.includes('family=')) {
        link.remove()
      }
    })
    
    let fontFamily = ''
    let fontLink = ''
    
    switch (fontSelect.toLowerCase()) {
      case 'prompt':
        fontLink = 'https://fonts.googleapis.com/css2?family=Prompt:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap'
        fontFamily = "'Prompt', sans-serif"
        break
      case 'thairg':
        // Use local Thai RG font
        fontFamily = "'thai-rg', sans-serif"
        break
      case 'sfpro':
        // Use local SF Pro font (from App.css @font-face)
        fontFamily = "'SF Pro Display', -apple-system, BlinkMacSystemFont, sans-serif"
        break
      default:
        // Default to Prompt if font_select is not recognized
        fontLink = 'https://fonts.googleapis.com/css2?family=Prompt:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap'
        fontFamily = "'Prompt', sans-serif"
    }
    
    // Add new font link
    if (fontLink) {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = fontLink
      link.id = 'dynamic-font-link'
      document.head.appendChild(link)
    }
    
    // Update body font family and add CSS class
    if (fontFamily) {
      document.body.style.fontFamily = fontFamily
      
      // Add specific CSS class for Thai RG font
      if (fontSelect.toLowerCase() === 'thairg') {
        document.body.classList.add('th-rg-body')
      } else {
        document.body.classList.remove('th-rg-body')
      }
      
      document.body.style.setProperty('--app-font-family', fontFamily)
      return
    }
    document.body.style.setProperty('--app-font-family', fontFamily)
  }

  // Helper function to update structured data for SEO
  const updateStructuredData = (webConfig) => {
    if (!webConfig) return

    // Remove existing structured data
    const existingScript = document.getElementById('structured-data')
    if (existingScript) {
      existingScript.remove()
    }

    // Create structured data
    const structuredData = {
      "@context": "https://schema.org",
      "@type": "WebSite",
      "name": webConfig.site_name || "Website",
      "description": webConfig.meta_description || "",
      "url": window.location.origin,
      "potentialAction": {
        "@type": "SearchAction",
        "target": {
          "@type": "EntryPoint",
          "urlTemplate": window.location.origin + "/store"
        },
        "query-input": "required name=search_term_string"
      }
    }

    // Add organization info if owner_phone is available
    if (webConfig.owner_phone) {
      structuredData["publisher"] = {
        "@type": "Organization",
        "name": webConfig.site_name || "Website",
        "telephone": webConfig.owner_phone
      }
      const metaImage = webConfig.meta_photo || webConfig.site_logo;
      if (metaImage) {
        structuredData["publisher"]["logo"] = {
          "@type": "ImageObject",
          "url": metaImage
        }
      }
    }

    // Add structured data to document
    const script = document.createElement('script')
    script.id = 'structured-data'
    script.type = 'application/ld+json'
    script.textContent = JSON.stringify(structuredData)
    document.head.appendChild(script)
  }

  // Check if welcome page should be shown
  // Show if: (welcome_toggle is enabled) OR (music_link exists)
  const shouldShowWelcome = webConfig && 
    typeof window !== 'undefined' && 
    localStorage.getItem('welcome_entered') !== 'true' &&
    (
      (webConfig.welcome_toggle === true || webConfig.welcome_toggle === 1) ||
      (webConfig.music_link && webConfig.music_link.trim() !== '')
    )

  // Show loading page if still loading (theme, config, auth)
  // This must be after all hooks to follow Rules of Hooks
  if (isInitialLoading) {
    // If we have load_logo and will show LoadingPage, use simple spinner while loading config
    if (webConfig?.load_logo && location.pathname === '/') {
      const primaryColor = theme?.primary_color || '#3B82F6'
      const backgroundColor = theme?.background_color || '#FFFFFF'
      
      return (
        <div 
          className="fixed inset-0 flex items-center justify-center z-50"
          style={{ backgroundColor: backgroundColor }}
        >
          <div className="flex flex-col items-center space-y-6">
            <div
              className="animate-spin rounded-full border-b-2"
              style={{
                width: '48px',
                height: '48px',
                borderTopColor: 'transparent',
                borderRightColor: primaryColor,
                borderBottomColor: primaryColor,
                borderLeftColor: primaryColor
              }}
            ></div>
          </div>
        </div>
      )
    }
    
    // Default loading spinner
    const primaryColor = theme?.primary_color || '#3B82F6'
    const backgroundColor = theme?.background_color || '#FFFFFF'
    const textColor = theme?.text_color || '#1F2937'
    
    return (
      <div 
        className="fixed inset-0 flex items-center justify-center z-50"
        style={{ backgroundColor: backgroundColor }}
      >
        <div className="flex flex-col items-center space-y-6">
          {/* Spinner */}
          <div
            className="animate-spin rounded-full border-b-2"
            style={{
              width: '48px',
              height: '48px',
              borderTopColor: 'transparent',
              borderRightColor: primaryColor,
              borderBottomColor: primaryColor,
              borderLeftColor: primaryColor
            }}
          ></div>
          
          {/* Loading Text */}
          <p
            className="text-lg font-medium"
            style={{ color: textColor }}
          >
            กำลังเข้าสู่เว็บไซต์
          </p>
        </div>
      </div>
    )
  }

  // หลังจากเข้าเว็บ (theme/config โหลดแล้ว): โหลดทุกหน้าก่อนแล้วค่อยแสดงแอป
  if (!preloadDone) {
    const primaryColor = theme?.primary_color ?? '#3B82F6'
    const bgColor = theme?.background_color ?? '#FFFFFF'
    const textColor = theme?.text_color ?? '#1F2937'
    return (
      <div
        className="fixed inset-0 flex items-center justify-center z-[100]"
        style={{ backgroundColor: bgColor }}
      >
        <div className="flex flex-col items-center space-y-6">
          <div
            className="animate-spin rounded-full border-b-2"
            style={{
              width: '48px',
              height: '48px',
              borderTopColor: 'transparent',
              borderRightColor: primaryColor,
              borderBottomColor: primaryColor,
              borderLeftColor: primaryColor
            }}
          />
          <p className="text-lg font-medium" style={{ color: textColor }}>
            กำลังโหลดทุกหน้า...
          </p>
        </div>
      </div>
    )
  }

  // Show welcome page if music is configured and user hasn't entered yet
  if (shouldShowWelcome) {
    return <Welcome />
  }

  // Check if HelloKitty particle should be shown
  const shouldShowHelloKittyParticle = webConfig?.particle_id && 
    (webConfig.particle_id.toString().toUpperCase().includes('HELLOKITTY') || 
     webConfig.particle_id.toString().toUpperCase().includes('HELLO_KITTY'))

  // Check if Christmas particle should be shown
  const shouldShowChristmasParticle = webConfig?.particle_id && 
    webConfig.particle_id.toString().toUpperCase().includes('CHRISTMAS')

  // Check if Starfall particle should be shown
  const shouldShowStarfallParticle = webConfig?.particle_id && 
    webConfig.particle_id.toString().toUpperCase().includes('STARFALL')

  return (
    <>
      {/* Show LoadingPage if has load_logo and is on home page */}
      {shouldShowLoadingPage && (
        <LoadingPage 
          isVisible={true}
          onComplete={() => {
            // LoadingPage will handle its own fade out
          }}
        />
      )}
      
      {/* Show HelloKitty Particle if enabled */}
      {shouldShowHelloKittyParticle && <HelloKittyParticle />}
      
      {/* Show Christmas Particle if enabled */}
      {shouldShowChristmasParticle && <ChristmasParticle />}
      
      {/* Show Starfall Particle if enabled */}
      {shouldShowStarfallParticle && <StarfallParticle />}
      
      {/* Mimi Particle - รูปเด้งกับขอบจอ (config 43, 126) */}
      <MimiParticleDisplay />
      
      <ScrollToTop />
      <DomainStatus />
      {!isAdminPage && (webConfig?.chat_enabled === 1 || webConfig?.chat_enabled === true) && <ChatWidget />}
      {/* <AuthDebugger /> */} {/* Temporarily disabled */}
      <Suspense fallback={<PageLoader />}>
      <PageTransitionContext.Provider value={displayLocation}>
      <div
        style={{
          minHeight: '100vh',
          backgroundColor: theme?.background_color || theme?.primary_color || '#8b5cf6'
        }}
      >
      <div
        style={{
          opacity: isExiting ? 0 : 1,
          transition: `opacity ${PAGE_FADE_MS}ms ease-in-out`,
          minHeight: '100vh'
        }}
      >
      <Routes location={displayLocation}>
          {/* Admin Routes - Protected with Authentication and Permission Check */}
          <Route path="/admin" element={<ProtectedAdminRoute><AdminDashboard /></ProtectedAdminRoute>} />
        <Route path="/admin/stats" element={<ProtectedAdminRoute><AdminStats /></ProtectedAdminRoute>} />
        <Route path="/admin/config" element={<ProtectedAdminRoute><ConfigManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/config/custom-component/new" element={<ProtectedAdminRoute><CustomComponentStudio /></ProtectedAdminRoute>} />
        <Route path="/admin/config/custom-component/:id" element={<ProtectedAdminRoute><CustomComponentStudio /></ProtectedAdminRoute>} />
        <Route path="/admin/contacts" element={<ProtectedAdminRoute><ContactManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/store-connection" element={<ProtectedAdminRoute><StoreConnection /></ProtectedAdminRoute>} />
        <Route path="/admin/program-statuses" element={<ProtectedAdminRoute><ProgramStatusManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/products" element={<ProtectedAdminRoute><ProductManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/orders" element={<ProtectedAdminRoute><OrderManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/installments" element={<ProtectedAdminRoute><InstallmentManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/claims" element={<ProtectedAdminRoute><ClaimManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/minigames" element={<ProtectedAdminRoute><MinigameManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/minigames/history" element={<ProtectedAdminRoute><MinigamePlayHistory /></ProtectedAdminRoute>} />
        <Route path="/admin/users" element={<ProtectedAdminRoute><UserManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/roles" element={<ProtectedAdminRoute><RoleManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/redeem-codes" element={<ProtectedAdminRoute><RedeemCodeManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/keyauth" element={<ProtectedAdminRoute><KeyAuthManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/reviews" element={<ProtectedAdminRoute><ReviewManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/mimi-particles" element={<ProtectedAdminRoute><MimiParticleManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/chats" element={<ProtectedAdminRoute><AdminChatManagement /></ProtectedAdminRoute>} />
        <Route path="/admin/transactions" element={<ProtectedAdminRoute><TransactionManagement /></ProtectedAdminRoute>} />
        
        {/* Regular Routes - With Navbar/Footer */}
        <Route path="/*" element={
          <MainLayout
            webConfig={webConfig}
            backgroundImage={backgroundImage}
            backgroundColor={backgroundColor}
            backgroundOpacity={backgroundOpacity}
          />
        } />
      </Routes>
      </div>
      </div>
      </PageTransitionContext.Provider>
      </Suspense>
    </>
  )
}

// Layout หน้าเว็บ (Navbar + main + Footer) ใช้ displayLocation จาก context ให้ inner Routes
function MainLayout({ webConfig, backgroundImage, backgroundColor, backgroundOpacity }) {
  const displayLocation = useContext(PageTransitionContext)
  const location = useLocation()
  const locationForInner = displayLocation ?? location

  return (
    <div
      className="flex flex-col relative"
      style={{
        backgroundColor: backgroundImage ? backgroundColor : backgroundColor,
        minHeight: '100vh',
        overflow: 'visible'
      }}
    >
      {backgroundImage && (
        <div
          className="fixed inset-0"
          style={{
            backgroundImage: `url(${backgroundImage})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
            backgroundAttachment: 'fixed',
            opacity: backgroundOpacity,
            zIndex: 0,
            pointerEvents: 'none'
          }}
        />
      )}
      <div className="relative z-10 flex flex-col" style={{ minHeight: '100vh', overflow: 'visible' }}>
        <Announce />
        <Navbar />
        <main className="flex-1 py-5 relative" style={{ paddingTop: webConfig?.annouce_status ? '80px' : '56px', transition: 'padding-top 0.3s ease-in-out', overflow: 'visible', minHeight: 'auto' }}>
          <Routes location={locationForInner}>
            <Route path="/" element={<Home />} />
            <Route path="/product/:productId" element={<div className="w-full px-4"><Product /></div>} />
            <Route path="/purchase" element={<div className="w-full px-4"><Purchase /></div>} />
            <Route path="/purchase/guest" element={<div className="w-full px-4"><GuestAngpaoPurchase /></div>} />
            <Route path="/topup" element={<div className="w-full px-4"><Topup /></div>} />
            <Route path="/store" element={<div className="w-full px-4" style={{ marginTop: webConfig?.annouce_status ? '-80px' : '-56px', paddingTop: 0 }}><Store /></div>} />
            <Route path="/store/category/:categoryId" element={<div className="w-full px-4"><CategoryDetail /></div>} />
            <Route path="/auth" element={<div className="w-full px-4"><Auth /></div>} />
            <Route path="/history" element={<div className="w-full px-2 sm:px-3 lg:px-4"><History /></div>} />
            <Route path="/orders" element={<div className="w-full px-4"><MyOrders /></div>} />
            <Route path="/installments" element={<div className="w-full px-4"><MyInstallments /></div>} />
            <Route path="/my-topup" element={<div className="w-full px-4"><TopupHistory /></div>} />
            <Route path="/program-status" element={<div className="w-full px-2 sm:px-3 lg:px-4"><ProgramStatus /></div>} />
            <Route path="/profile" element={<div className="w-full px-4"><Profile /></div>} />
            <Route path="/review" element={<div className="w-full px-4"><ReviewPage /></div>} />
            <Route path="/claims" element={<div className="w-full px-4"><Claims /></div>} />
            <Route path="/minigames" element={<div className="w-full px-4"><Minigames /></div>} />
            <Route path="/minigames/:id" element={<div className="w-full px-4"><MinigameDetail /></div>} />
            <Route path="/minigame-history" element={<div className="w-full px-4"><MinigameHistory /></div>} />
            <Route path="/redeem-code" element={<div className="w-full px-4"><RedeemCode /></div>} />
            <Route path="/keyauth" element={<div className="w-full px-4"><KeyAuth /></div>} />
            <Route path="*" element={<div className="w-full px-4"><NotFound /></div>} />
          </Routes>
        </main>
        <Footer />
      </div>
    </div>
  )
}

export default function App() {
  return (
    <ThemeProvider>
      <WebConfigProvider>
        <AuthProvider>
          <MusicProvider>
            <AppContent />
          </MusicProvider>
        </AuthProvider>
      </WebConfigProvider>
    </ThemeProvider>
  )
}
