
// 'use client'
// import React, {
//   useEffect,
//   createContext,
//   useContext,
//   useState,
//   ReactNode,
//   useMemo,
// } from 'react'
// import { colorVarsToDarken, themes } from './themes'
// import { getDarkenAmount, darkenToRgba } from './darkenUtils'

// /* -------------------------------------------------------------------------- */
// /*                                 TYPES                                      */
// /* -------------------------------------------------------------------------- */
// export type ThemeVariant = 'standard' | 'minimal'

// export type ThemeName =
//   | 'light'
//   | 'dark'
//   | 'dark-blue'
//   | 'light-gray'
//   | 'pastel-green'
//   | 'warm-orange'
//   | 'frosted-glass'
//   | 'midnight-purple'
//   | 'cyber-metal'

// interface ThemeConfig {
//   [key: string]: any
// }

// interface Variable {
//   name: string
//   value: any
// }

// interface ProjectData {
//   theme_config?: {
//     colors?: Record<string, string>
//     typography?: Record<string, string>
//     [key: string]: any
//   }
//   components?: Record<string, any>
//   default_variation?: ThemeVariant
//   variables?: Variable[]
//   assets?: Asset[]
//   name?: string
//   project_id?: string
//   version?: number
//   updated_at?: string
//   trustedDomains?: Array<{
//     domain: string
//     status: string
//     isDefault?: boolean
//   }>
// }

// interface ThemeProviderProps {
//   theme: ThemeName
//   projectId?: string
//   funcss?: string
//   minHeight?: string
//   children: ReactNode
//   project?: ProjectData | null // New prop: directly provide project data
// }

// /* -------------------------------------------------------------------------- */
// /*                              THEME CONTEXT                                 */
// /* -------------------------------------------------------------------------- */
// interface ThemeContextType {
//   variant: ThemeVariant
//   setVariant: React.Dispatch<React.SetStateAction<ThemeVariant>>
//   themeConfig: ThemeConfig
//   projectData: ProjectData | null
//   isLoading: boolean
//   isInitialLoad: boolean
//   error: string | null
// }

// const ThemeContext = createContext<ThemeContextType>({
//   variant: 'standard',
//   setVariant: () => {},
//   themeConfig: {},
//   projectData: null,
//   isLoading: true,
//   isInitialLoad: true,
//   error: null,
// })

// export const useTheme = (): ThemeContextType => {
//   const context = useContext(ThemeContext)
//   if (!context) {
//     throw new Error('useTheme must be used within ThemeProvider')
//   }
//   return context
// }

// export const useVariant = () => {
//   const { variant, setVariant } = useTheme()
//   return { variant, setVariant }
// }

// /* -------------------------------------------------------------------------- */
// /*                          ORIGIN VALIDATION                                 */
// /* -------------------------------------------------------------------------- */

// const getCurrentOrigin = (): string => {
//   if (typeof window === 'undefined') return ''
  
//   // For local development, return localhost
//   if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
//     return 'localhost'
//   }
  
//   // For production, return the domain without protocol and www
//   let domain = window.location.hostname
//   domain = domain.replace(/^www\./, '')
//   return domain
// }

// const validateOriginAccess = async (projectId: string): Promise<boolean> => {
//   if (!projectId) {
//     console.error('❌ No project ID provided for origin validation')
//     return false
//   }

//   const currentOrigin = getCurrentOrigin()
//   console.log(`🔍 Validating origin access for: ${currentOrigin}`)

//   try {
//     // Load project data from CDN to check trusted domains
//     const projectData = await loadThemeFromCDN(projectId)
    
//     if (!projectData) {
//       console.error('❌ Project not found or inaccessible')
//       return false
//     }

//     const trustedDomains = projectData.trustedDomains || []
    
//     // Check if current origin is in trusted domains
//     const hasAccess = trustedDomains.some(domain => {
//       const trustedDomain = domain.domain.toLowerCase()
//       const currentDomain = currentOrigin.toLowerCase()
      
//       // Exact match or subdomain match
//       return currentDomain === trustedDomain || 
//              currentDomain.endsWith('.' + trustedDomain) ||
//              (trustedDomain === 'localhost' && currentOrigin === 'localhost')
//     })

//     if (!hasAccess) {
//       console.error(`❌ Access denied: Origin "${currentOrigin}" is not in trusted domains`)
//       console.log('📋 Trusted domains:', trustedDomains.map(d => d.domain))
//       return false
//     }

//     return true

//   } catch (error) {
//     console.error('❌ Error during origin validation:', error)
//     return false
//   }
// }

// /* -------------------------------------------------------------------------- */
// /*                          LOCAL FILE MANAGEMENT                             */
// /* -------------------------------------------------------------------------- */

// const loadLocalTheme = async (): Promise<ProjectData | null> => {
//   try {
//     const response = await fetch('/funui.json', {
//       cache: 'no-cache',
//     })
    
//     if (response.ok) {
//       const data = await response.json()
//       return data
//     }
//   } catch (error) {
//     console.log('ℹ️ No local theme file found')
//   }
//   return null
// }

// /* -------------------------------------------------------------------------- */
// /*                          CDN THEME LOADER                                  */
// /* -------------------------------------------------------------------------- */

// const loadThemeFromCDN = async (projectId: string): Promise<ProjectData | null> => {
//   if (!projectId) {
//     console.error('❌ No project ID provided for CDN loading')
//     return null
//   }

//   // Try Firebase Storage public URL
//   try {
//     const publicUrl = `https://firebasestorage.googleapis.com/v0/b/funui-4bcd1.firebasestorage.app/o/themes%2F${projectId}.json?alt=media`
    
//     const response = await fetch(publicUrl, {
//       cache: 'no-cache',
//     })
    
//     if (response.ok) {
//       const data = await response.json()
//       return data
//     } else {
//       console.error('❌ Firebase Storage fetch failed:', response.status, response.statusText)
//     }
//   } catch (error) {
//     console.error('❌ Error loading from Firebase Storage:', error)
//   }

//   return null
// }

// /* -------------------------------------------------------------------------- */
// /*                          CSS VARIABLE APPLIER                              */
// /* -------------------------------------------------------------------------- */

// const applyTypographyVariables = (typography: Record<string, string>, root: HTMLElement) => {
//   if (!typography) return

//   Object.entries(typography).forEach(([key, value]) => {
//     const cssVarName = `--${key.replace(/_/g, '-')}`
//     root.style.setProperty(cssVarName, value)
//   })
// }

// const applyColorVariables = (colors: Record<string, string>, root: HTMLElement) => {
//   if (!colors) return

//   Object.entries(colors).forEach(([key, value]) => {
//     const cssVarName = `--${key.replace(/_/g, '-')}`
//     root.style.setProperty(cssVarName, value)
//   })
// }

// const applyThemeConfig = (themeConfig: Record<string, any>, root: HTMLElement) => {
//   if (!themeConfig) return

//   if (themeConfig.colors) {
//     applyColorVariables(themeConfig.colors, root)
//   }

//   if (themeConfig.typography) {
//     applyTypographyVariables(themeConfig.typography, root)
//   }

//   Object.entries(themeConfig).forEach(([key, value]) => {
//     if (key !== 'colors' && key !== 'typography' && typeof value === 'string') {
//       const cssVarName = `--${key.replace(/_/g, '-')}`
//       root.style.setProperty(cssVarName, value)
//     }
//   })
// }

// /* -------------------------------------------------------------------------- */
// /*                          VARIABLES HELPER                                  */
// /* -------------------------------------------------------------------------- */

// let cachedProjectData: ProjectData | null = null

// export const getVariable = (name: string): { name: string; value: any } | undefined => {
//   if (!cachedProjectData?.variables) {
//     console.warn('No variables available. Make sure ThemeProvider is mounted.')
//     return undefined
//   }

//   const variable = cachedProjectData.variables.find(v => v.name === name)
//   return variable
// }

// export const getAllVariables = (): Variable[] => {
//   return cachedProjectData?.variables || []
// }

// /* -------------------------------------------------------------------------- */
// /*                                COMPONENT                                   */
// /* -------------------------------------------------------------------------- */
// const ThemeProvider: React.FC<ThemeProviderProps> = ({
//   theme,
//   children,
//   funcss = '',
//   minHeight = '100vh',
//   projectId,
//   project: providedProject, // New prop
// }) => {
//   const [variant, setVariant] = useState<ThemeVariant>('standard')
//   const [themeConfig, setThemeConfig] = useState<ThemeConfig>({})
//   const [projectData, setProjectData] = useState<ProjectData | null>(null)
//   const [isLoading, setIsLoading] = useState(true)
//   const [isInitialLoad, setIsInitialLoad] = useState(true)
//   const [error, setError] = useState<string | null>(null)
//   const [currentVersion, setCurrentVersion] = useState<number | null>(null)

//   /* -------------------------- Apply base theme --------------------------- */
//   useEffect(() => {
//     const root = document.documentElement
//     const selectedTheme = themes[theme] || themes.light

//     Object.entries(selectedTheme).forEach(([key, value]) => {
//       root.style.setProperty(key, value)
//     })

//     if (
//       ['dark', 'dark-blue', 'midnight-purple', 'cyber-metal'].includes(theme)
//     ) {
//       colorVarsToDarken.forEach((varName) => {
//         const original = getComputedStyle(root)
//           .getPropertyValue(varName)
//           .trim()
//         if (original) {
//           const darkAmount = getDarkenAmount(varName)
//           const rgba = darkenToRgba(original, darkAmount, 0.9)
//           root.style.setProperty(varName, rgba)
//         }
//       })
//     }
//   }, [theme])

//   /* ---------------------- Theme Loading Logic ----------------------- */
//   useEffect(() => {
//     if (typeof window === 'undefined') {
//       setIsLoading(false)
//       setIsInitialLoad(false)
//       return
//     }

//     const root = document.documentElement
//     let pollTimer: NodeJS.Timeout

//     const loadTheme = async () => {
//       try {
//         let finalTheme: ProjectData | null = null
//         let finalVersion: number | null = null

//         // If project data is provided directly, use it and skip all loading
//         if (providedProject) {
//           console.log('✅ Using provided project data directly')
//           finalTheme = providedProject
//           finalVersion = providedProject.version || 0
//         } else {
//           // Otherwise, follow the normal loading flow
//           // First, try to load local theme
//           const localTheme = await loadLocalTheme()
//           const localVersion = localTheme?.version || 0

//           if (projectId) {
//             // Validate origin access for CDN
//             const hasAccess = await validateOriginAccess(projectId)
            
//             if (hasAccess) {
//               // Try to load from CDN
//               const cdnTheme = await loadThemeFromCDN(projectId)
//               const cdnVersion = cdnTheme?.version || 0

//               if (cdnTheme) {
//                 // CDN theme available - use it
//                 finalTheme = cdnTheme
//                 finalVersion = cdnVersion
                
//                 if (cdnVersion !== localVersion) {
//                   console.log(`🔄 Version mismatch: Local(${localVersion}) vs CDN(${cdnVersion})`)
//                   console.log('ℹ️ Using CDN version. Please update your local funui.json file manually.')
//                 }

//               } else if (localTheme) {
//                 // CDN not available but we have local theme
//                 console.log('⚠️ CDN unavailable, using local theme')
//                 finalTheme = localTheme
//                 finalVersion = localVersion
//               } else {
//                 // No theme available anywhere
//                 console.warn('⚠️ No theme found (CDN unavailable and no local theme)')
//                 setError('Theme not found')
//               }
//             } else {
//               // Origin validation failed
//               if (localTheme) {
//                 console.log('⚠️ Origin validation failed, using local theme')
//                 finalTheme = localTheme
//                 finalVersion = localVersion
//               } else {
//                 console.error('❌ Origin validation failed and no local theme available')
//                 setError('Access denied and no local theme available')
//               }
//             }
//           } else {
//             // No project ID provided - only use local theme
//             console.log('ℹ️ No project ID provided, using local theme only')
//             if (localTheme) {
//               finalTheme = localTheme
//               finalVersion = localVersion
//               console.log('✅ Theme loaded from local file')
//             } else {
//               console.log('ℹ️ No local theme file found - using base theme only')
//               // No error here - it's valid to use only base theme
//             }
//           }
//         }

//         // Apply the theme if we have one
//         if (finalTheme && (!currentVersion || finalVersion !== currentVersion)) {
//           applyThemeData(finalTheme, root)
//           setCurrentVersion(finalVersion)
//           setError(null)
//         } else if (finalTheme) {
//           console.log('✓ Theme up to date')
//         }

//       } catch (err) {
//         console.error('❌ Error loading theme:', err)
//         setError('Failed to load theme')
//       } finally {
//         setIsLoading(false)
//         setIsInitialLoad(false)
//       }
//     }

//     // Initial load
//     loadTheme()

//     // Only poll for updates if we have a project ID AND no provided project
//     if (projectId && !providedProject) {
//       pollTimer = setInterval(() => {
//         loadTheme()
//       }, 5 * 60 * 1000)
//     }

//     return () => {
//       if (pollTimer) {
//         clearInterval(pollTimer)
//       }
//     }
//   }, [projectId, currentVersion, theme, providedProject]) // Added providedProject to dependencies

//   const applyThemeData = (data: ProjectData, root: HTMLElement) => {
//     const themeConfig = data.theme_config ?? {}
//     const newVariant = data.default_variation || 'standard'

//     setVariant(newVariant)
//     setThemeConfig(themeConfig)
//     setProjectData(data)
    
//     // Cache for variable access
//     cachedProjectData = data
    
//     // Cache for asset access
//     cachedAssets = data.assets || []

//     // Apply all theme config to CSS variables
//     applyThemeConfig(themeConfig, root)
//   }

//   const contextValue = useMemo(
//     () => ({
//       variant,
//       setVariant,
//       themeConfig,
//       projectData,
//       isLoading,
//       isInitialLoad,
//       error,
//     }),
//     [variant, themeConfig, projectData, isLoading, isInitialLoad, error]
//   )

//   return (
//     <ThemeContext.Provider value={contextValue}>
//       <div
//         className={`theme-${theme} ${funcss}`}
//         style={{
//           backgroundColor: 'var(--page-bg)',
//           color: 'var(--text-color)',
//           minHeight: minHeight,
//           transition: isInitialLoad ? 'none' : 'background-color 0.3s ease, color 0.3s ease',
//         }}
//       >
//         {children}
//       </div>
//     </ThemeContext.Provider>
//   )
// }

// export default ThemeProvider

// /* -------------------------------------------------------------------------- */
// /*                              HELPER HOOKS                                  */
// /* -------------------------------------------------------------------------- */

// export const useThemeValue = (key: string): string | undefined => {
//   const { themeConfig } = useTheme()
//   return themeConfig[key]
// }

// export const useComponentConfig = (componentName: string): any => {
//   const { projectData } = useTheme()
//   return projectData?.components?.[componentName] || {}
// }

// export const useColors = (): Record<string, string> => {
//   const { projectData } = useTheme()
//   return projectData?.theme_config?.colors || {}
// }

// export const useTypography = (): Record<string, string> => {
//   const { projectData } = useTheme()
//   return projectData?.theme_config?.typography || {}
// }

// export const useThemeConfig = (): Record<string, any> => {
//   const { projectData } = useTheme()
//   return projectData?.theme_config || {}
// }

// export const useProjectData = (): ProjectData | null => {
//   const { projectData } = useTheme()
//   return projectData
// }

// export const useColor = (colorName: string): string | undefined => {
//   const colors = useColors()
//   return colors[colorName]
// }

// export const useTypographyValue = (property: string): string | undefined => {
//   const typography = useTypography()
//   return typography[property]
// }

// export const useComponentVariant = (componentName: string, variantName: string = 'default'): any => {
//   const componentConfig = useComponentConfig(componentName)
//   return componentConfig[variantName] || {}
// }

// // Hook to access variables
// export const useVariables = (): Variable[] => {
//   const { projectData } = useTheme()
//   return projectData?.variables || []
// }

// // Hook to get a specific variable
// export const useVariable = (name: string): any => {
//   const variables = useVariables()
//   const variable = variables.find(v => v.name === name)
//   return variable?.value
// }

// /* -------------------------------------------------------------------------- */
// /*                              ASSETS HELPER                                 */
// /* -------------------------------------------------------------------------- */

// interface Asset {
//   name: string
//   url: string
//   file_type: string
// }

// let cachedAssets: Asset[] = []

// export const getAsset = (name: string): Asset | undefined => {
//   if (!cachedAssets.length) {
//     console.warn('No assets available. Make sure ThemeProvider is mounted and assets are loaded.')
//     return undefined
//   }

//   const asset = cachedAssets.find(a => a.name === name)
//   return asset
// }

// export const getAllAssets = (): Asset[] => {
//   return cachedAssets
// }

// export const getAssetValue = (name: string): string | undefined => {
//   const asset = getAsset(name)
//   return asset?.url
// }

// export const getAssetType = (name: string): string | undefined => {
//   const asset = getAsset(name)
//   return asset?.file_type
// }

// export const getAssetInfo = (name: string): { value: string; type: string; name: string } | undefined => {
//   const asset = getAsset(name)
//   if (!asset) return undefined
  
//   return {
//     value: asset.url,
//     type: asset.file_type,
//     name: asset.name
//   }
// }

// // Hook to access all assets
// export const useAssets = (): Asset[] => {
//   const { projectData } = useTheme()
//   return projectData?.assets || []
// }

// // Hook to get a specific asset
// export const useAsset = (name: string): Asset | undefined => {
//   const assets = useAssets()
//   const asset = assets.find(a => a.name === name)
//   return asset
// }

// // Hook to get asset URL (most common use case)
// export const useAssetValue = (name: string): string | undefined => {
//   const asset = useAsset(name)
//   return asset?.url
// }

// // Hook to get asset type
// export const useAssetType = (name: string): string | undefined => {
//   const asset = useAsset(name)
//   return asset?.file_type
// }

// // Hook to get complete asset info
// export const useAssetInfo = (name: string): { value: string; type: string; name: string } | undefined => {
//   const asset = useAsset(name)
//   if (!asset) return undefined
  
//   return {
//     value: asset.url,
//     type: asset.file_type,
//     name: asset.name
//   }
// }

// // Hook to filter assets by type
// export const useAssetsByType = (type: string): Asset[] => {
//   const assets = useAssets()
//   return assets.filter(asset => asset.file_type === type)
// }

// // Hook to get image assets
// export const useImageAssets = (): Asset[] => {
//   return useAssetsByType('image')
// }

// // Hook to get video assets
// export const useVideoAssets = (): Asset[] => {
//   return useAssetsByType('video')
// }

// // Hook to get audio assets
// export const useAudioAssets = (): Asset[] => {
//   return useAssetsByType('audio')
// }

// // Hook to get document assets
// export const useDocumentAssets = (): Asset[] => {
//   return useAssetsByType('document')
// }

// // 'use client'
// // import React, {
// //   useEffect,
// //   createContext,
// //   useContext,
// //   useState,
// //   ReactNode,
// //   useMemo,
// // } from 'react'
// // import { colorVarsToDarken, themes } from './themes'
// // import { getDarkenAmount, darkenToRgba } from './darkenUtils'

// // /* -------------------------------------------------------------------------- */
// // /*                                 TYPES                                      */
// // /* -------------------------------------------------------------------------- */
// // export type ThemeVariant = 'standard' | 'minimal'

// // export type ThemeName =
// //   | 'light'
// //   | 'dark'
// //   | 'dark-blue'
// //   | 'light-gray'
// //   | 'pastel-green'
// //   | 'warm-orange'
// //   | 'frosted-glass'
// //   | 'midnight-purple'
// //   | 'cyber-metal'

// // interface ThemeConfig {
// //   [key: string]: any
// // }

// // interface Variable {
// //   name: string
// //   value: any
// // }

// // interface ProjectData {
// //   theme_config?: {
// //     colors?: Record<string, string>
// //     typography?: Record<string, string>
// //     [key: string]: any
// //   }
// //   components?: Record<string, any>
// //   default_variation?: ThemeVariant
// //   variables?: Variable[]
// //   assets?: Asset[]
// //   name?: string
// //   project_id?: string
// //   version?: number
// //   updated_at?: string
// //   trustedDomains?: Array<{
// //     domain: string
// //     status: string
// //     isDefault?: boolean
// //   }>
// // }

// // interface ThemeProviderProps {
// //   theme: ThemeName
// //   projectId?: string
// //   funcss?: string
// //   minHeight?: string
// //   children: ReactNode
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                              THEME CONTEXT                                 */
// // /* -------------------------------------------------------------------------- */
// // interface ThemeContextType {
// //   variant: ThemeVariant
// //   setVariant: React.Dispatch<React.SetStateAction<ThemeVariant>>
// //   themeConfig: ThemeConfig
// //   projectData: ProjectData | null
// //   isLoading: boolean
// //   isInitialLoad: boolean
// //   error: string | null
// // }

// // const ThemeContext = createContext<ThemeContextType>({
// //   variant: 'standard',
// //   setVariant: () => {},
// //   themeConfig: {},
// //   projectData: null,
// //   isLoading: true,
// //   isInitialLoad: true,
// //   error: null,
// // })

// // export const useTheme = (): ThemeContextType => {
// //   const context = useContext(ThemeContext)
// //   if (!context) {
// //     throw new Error('useTheme must be used within ThemeProvider')
// //   }
// //   return context
// // }

// // export const useVariant = () => {
// //   const { variant, setVariant } = useTheme()
// //   return { variant, setVariant }
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                          ORIGIN VALIDATION                                 */
// // /* -------------------------------------------------------------------------- */

// // const getCurrentOrigin = (): string => {
// //   if (typeof window === 'undefined') return ''
  
// //   // For local development, return localhost
// //   if (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1') {
// //     return 'localhost'
// //   }
  
// //   // For production, return the domain without protocol and www
// //   let domain = window.location.hostname
// //   domain = domain.replace(/^www\./, '')
// //   return domain
// // }

// // const validateOriginAccess = async (projectId: string): Promise<boolean> => {
// //   if (!projectId) {
// //     console.error('❌ No project ID provided for origin validation')
// //     return false
// //   }

// //   const currentOrigin = getCurrentOrigin()
// //   console.log(`🔍 Validating origin access for: ${currentOrigin}`)

// //   try {
// //     // Load project data from CDN to check trusted domains
// //     const projectData = await loadThemeFromCDN(projectId)
    
// //     if (!projectData) {
// //       console.error('❌ Project not found or inaccessible')
// //       return false
// //     }

// //     const trustedDomains = projectData.trustedDomains || []
    
// //     // Check if current origin is in trusted domains
// //     const hasAccess = trustedDomains.some(domain => {
// //       const trustedDomain = domain.domain.toLowerCase()
// //       const currentDomain = currentOrigin.toLowerCase()
      
// //       // Exact match or subdomain match
// //       return currentDomain === trustedDomain || 
// //              currentDomain.endsWith('.' + trustedDomain) ||
// //              (trustedDomain === 'localhost' && currentOrigin === 'localhost')
// //     })

// //     if (!hasAccess) {
// //       console.error(`❌ Access denied: Origin "${currentOrigin}" is not in trusted domains`)
// //       console.log('📋 Trusted domains:', trustedDomains.map(d => d.domain))
// //       return false
// //     }

// //     return true

// //   } catch (error) {
// //     console.error('❌ Error during origin validation:', error)
// //     return false
// //   }
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                          LOCAL FILE MANAGEMENT                             */
// // /* -------------------------------------------------------------------------- */

// // const loadLocalTheme = async (): Promise<ProjectData | null> => {
// //   try {
// //     const response = await fetch('/funui.json', {
// //       cache: 'no-cache',
// //     })
    
// //     if (response.ok) {
// //       const data = await response.json()
// //       return data
// //     }
// //   } catch (error) {
// //     console.log('ℹ️ No local theme file found')
// //   }
// //   return null
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                          CDN THEME LOADER                                  */
// // /* -------------------------------------------------------------------------- */

// // const loadThemeFromCDN = async (projectId: string): Promise<ProjectData | null> => {
// //   if (!projectId) {
// //     console.error('❌ No project ID provided for CDN loading')
// //     return null
// //   }

// //   // Try Firebase Storage public URL
// //   try {
// //     const publicUrl = `https://firebasestorage.googleapis.com/v0/b/funui-4bcd1.firebasestorage.app/o/themes%2F${projectId}.json?alt=media`
    
// //     const response = await fetch(publicUrl, {
// //       cache: 'no-cache',
// //     })
    
// //     if (response.ok) {
// //       const data = await response.json()
// //       return data
// //     } else {
// //       console.error('❌ Firebase Storage fetch failed:', response.status, response.statusText)
// //     }
// //   } catch (error) {
// //     console.error('❌ Error loading from Firebase Storage:', error)
// //   }

// //   return null
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                          CSS VARIABLE APPLIER                              */
// // /* -------------------------------------------------------------------------- */

// // const applyTypographyVariables = (typography: Record<string, string>, root: HTMLElement) => {
// //   if (!typography) return

// //   Object.entries(typography).forEach(([key, value]) => {
// //     const cssVarName = `--${key.replace(/_/g, '-')}`
// //     root.style.setProperty(cssVarName, value)
// //   })
// // }

// // const applyColorVariables = (colors: Record<string, string>, root: HTMLElement) => {
// //   if (!colors) return

// //   Object.entries(colors).forEach(([key, value]) => {
// //     const cssVarName = `--${key.replace(/_/g, '-')}`
// //     root.style.setProperty(cssVarName, value)
// //   })
// // }

// // const applyThemeConfig = (themeConfig: Record<string, any>, root: HTMLElement) => {
// //   if (!themeConfig) return

// //   if (themeConfig.colors) {
// //     applyColorVariables(themeConfig.colors, root)
// //   }

// //   if (themeConfig.typography) {
// //     applyTypographyVariables(themeConfig.typography, root)
// //   }

// //   Object.entries(themeConfig).forEach(([key, value]) => {
// //     if (key !== 'colors' && key !== 'typography' && typeof value === 'string') {
// //       const cssVarName = `--${key.replace(/_/g, '-')}`
// //       root.style.setProperty(cssVarName, value)
// //     }
// //   })
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                          VARIABLES HELPER                                  */
// // /* -------------------------------------------------------------------------- */

// // let cachedProjectData: ProjectData | null = null

// // export const getVariable = (name: string): { name: string; value: any } | undefined => {
// //   if (!cachedProjectData?.variables) {
// //     console.warn('No variables available. Make sure ThemeProvider is mounted.')
// //     return undefined
// //   }

// //   const variable = cachedProjectData.variables.find(v => v.name === name)
// //   return variable
// // }

// // export const getAllVariables = (): Variable[] => {
// //   return cachedProjectData?.variables || []
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                                COMPONENT                                   */
// // /* -------------------------------------------------------------------------- */
// // const ThemeProvider: React.FC<ThemeProviderProps> = ({
// //   theme,
// //   children,
// //   funcss = '',
// //   minHeight = '100vh',
// //   projectId,
// // }) => {
// //   const [variant, setVariant] = useState<ThemeVariant>('standard')
// //   const [themeConfig, setThemeConfig] = useState<ThemeConfig>({})
// //   const [projectData, setProjectData] = useState<ProjectData | null>(null)
// //   const [isLoading, setIsLoading] = useState(true)
// //   const [isInitialLoad, setIsInitialLoad] = useState(true)
// //   const [error, setError] = useState<string | null>(null)
// //   const [currentVersion, setCurrentVersion] = useState<number | null>(null)

// //   /* -------------------------- Apply base theme --------------------------- */
// //   useEffect(() => {
// //     const root = document.documentElement
// //     const selectedTheme = themes[theme] || themes.light

// //     Object.entries(selectedTheme).forEach(([key, value]) => {
// //       root.style.setProperty(key, value)
// //     })

// //     if (
// //       ['dark', 'dark-blue', 'midnight-purple', 'cyber-metal'].includes(theme)
// //     ) {
// //       colorVarsToDarken.forEach((varName) => {
// //         const original = getComputedStyle(root)
// //           .getPropertyValue(varName)
// //           .trim()
// //         if (original) {
// //           const darkAmount = getDarkenAmount(varName)
// //           const rgba = darkenToRgba(original, darkAmount, 0.9)
// //           root.style.setProperty(varName, rgba)
// //         }
// //       })
// //     }
// //   }, [theme])

// //   /* ---------------------- Theme Loading Logic ----------------------- */
// //   useEffect(() => {
// //     if (typeof window === 'undefined') {
// //       setIsLoading(false)
// //       setIsInitialLoad(false)
// //       return
// //     }

// //     const root = document.documentElement
// //     let pollTimer: NodeJS.Timeout

// //     const loadTheme = async () => {
// //       try {
        
// //         let finalTheme: ProjectData | null = null
// //         let finalVersion: number | null = null

// //         // First, try to load local theme
// //         const localTheme = await loadLocalTheme()
// //         const localVersion = localTheme?.version || 0

// //         if (projectId) {
// //           // Validate origin access for CDN
// //           const hasAccess = await validateOriginAccess(projectId)
          
// //           if (hasAccess) {
// //             // Try to load from CDN
// //             const cdnTheme = await loadThemeFromCDN(projectId)
// //             const cdnVersion = cdnTheme?.version || 0

// //             if (cdnTheme) {
// //               // CDN theme available - use it
// //               finalTheme = cdnTheme
// //               finalVersion = cdnVersion
              
// //               if (cdnVersion !== localVersion) {
// //                 console.log(`🔄 Version mismatch: Local(${localVersion}) vs CDN(${cdnVersion})`)
// //                 console.log('ℹ️ Using CDN version. Please update your local funui.json file manually.')
// //               }

// //             } else if (localTheme) {
// //               // CDN not available but we have local theme
// //               console.log('⚠️ CDN unavailable, using local theme')
// //               finalTheme = localTheme
// //               finalVersion = localVersion
// //             } else {
// //               // No theme available anywhere
// //               console.warn('⚠️ No theme found (CDN unavailable and no local theme)')
// //               setError('Theme not found')
// //             }
// //           } else {
// //             // Origin validation failed
// //             if (localTheme) {
// //               console.log('⚠️ Origin validation failed, using local theme')
// //               finalTheme = localTheme
// //               finalVersion = localVersion
// //             } else {
// //               console.error('❌ Origin validation failed and no local theme available')
// //               setError('Access denied and no local theme available')
// //             }
// //           }
// //         } else {
// //           // No project ID provided - only use local theme
// //           console.log('ℹ️ No project ID provided, using local theme only')
// //           if (localTheme) {
// //             finalTheme = localTheme
// //             finalVersion = localVersion
// //             console.log('✅ Theme loaded from local file')
// //           } else {
// //             console.log('ℹ️ No local theme file found - using base theme only')
// //             // No error here - it's valid to use only base theme
// //           }
// //         }

// //         // Apply the theme if we have one
// //         if (finalTheme && (!currentVersion || finalVersion !== currentVersion)) {
// //           applyThemeData(finalTheme, root)
// //           setCurrentVersion(finalVersion)
// //           setError(null)
// //         } else if (finalTheme) {
// //           console.log('✓ Theme up to date')
// //         }

// //       } catch (err) {
// //         console.error('❌ Error loading theme:', err)
// //         setError('Failed to load theme')
// //       } finally {
// //         setIsLoading(false)
// //         setIsInitialLoad(false)
// //       }
// //     }

// //     // Initial load
// //     loadTheme()

// //     // Only poll for updates if we have a project ID
// //     if (projectId) {
// //       pollTimer = setInterval(() => {
// //         loadTheme()
// //       }, 5 * 60 * 1000)
// //     }

// //     return () => {
// //       if (pollTimer) {
// //         clearInterval(pollTimer)
// //       }
// //     }
// //   }, [projectId, currentVersion, theme])

// //   const applyThemeData = (data: ProjectData, root: HTMLElement) => {
// //     const themeConfig = data.theme_config ?? {}
// //     const newVariant = data.default_variation || 'standard'

// //     setVariant(newVariant)
// //     setThemeConfig(themeConfig)
// //     setProjectData(data)
    
// //     // Cache for variable access
// //     cachedProjectData = data
    
// //     // Cache for asset access
// //     cachedAssets = data.assets || []

// //     // Apply all theme config to CSS variables
// //     applyThemeConfig(themeConfig, root)
// //   }

// //   const contextValue = useMemo(
// //     () => ({
// //       variant,
// //       setVariant,
// //       themeConfig,
// //       projectData,
// //       isLoading,
// //       isInitialLoad,
// //       error,
// //     }),
// //     [variant, themeConfig, projectData, isLoading, isInitialLoad, error]
// //   )

// //   return (
// //     <ThemeContext.Provider value={contextValue}>
// //       <div
// //         className={`theme-${theme} ${funcss}`}
// //         style={{
// //           backgroundColor: 'var(--page-bg)',
// //           color: 'var(--text-color)',
// //           minHeight: minHeight,
// //           transition: isInitialLoad ? 'none' : 'background-color 0.3s ease, color 0.3s ease',
// //         }}
// //       >
// //         {children}
// //       </div>
// //     </ThemeContext.Provider>
// //   )
// // }

// // export default ThemeProvider

// // /* -------------------------------------------------------------------------- */
// // /*                              HELPER HOOKS                                  */
// // /* -------------------------------------------------------------------------- */

// // export const useThemeValue = (key: string): string | undefined => {
// //   const { themeConfig } = useTheme()
// //   return themeConfig[key]
// // }

// // export const useComponentConfig = (componentName: string): any => {
// //   const { projectData } = useTheme()
// //   return projectData?.components?.[componentName] || {}
// // }

// // export const useColors = (): Record<string, string> => {
// //   const { projectData } = useTheme()
// //   return projectData?.theme_config?.colors || {}
// // }

// // export const useTypography = (): Record<string, string> => {
// //   const { projectData } = useTheme()
// //   return projectData?.theme_config?.typography || {}
// // }

// // export const useThemeConfig = (): Record<string, any> => {
// //   const { projectData } = useTheme()
// //   return projectData?.theme_config || {}
// // }

// // export const useProjectData = (): ProjectData | null => {
// //   const { projectData } = useTheme()
// //   return projectData
// // }

// // export const useColor = (colorName: string): string | undefined => {
// //   const colors = useColors()
// //   return colors[colorName]
// // }

// // export const useTypographyValue = (property: string): string | undefined => {
// //   const typography = useTypography()
// //   return typography[property]
// // }

// // export const useComponentVariant = (componentName: string, variantName: string = 'default'): any => {
// //   const componentConfig = useComponentConfig(componentName)
// //   return componentConfig[variantName] || {}
// // }

// // // Hook to access variables
// // export const useVariables = (): Variable[] => {
// //   const { projectData } = useTheme()
// //   return projectData?.variables || []
// // }

// // // Hook to get a specific variable
// // export const useVariable = (name: string): any => {
// //   const variables = useVariables()
// //   const variable = variables.find(v => v.name === name)
// //   return variable?.value
// // }

// // /* -------------------------------------------------------------------------- */
// // /*                              ASSETS HELPER                                 */
// // /* -------------------------------------------------------------------------- */

// // interface Asset {
// //   name: string
// //   url: string
// //   file_type: string
// // }

// // let cachedAssets: Asset[] = []

// // export const getAsset = (name: string): Asset | undefined => {
// //   if (!cachedAssets.length) {
// //     console.warn('No assets available. Make sure ThemeProvider is mounted and assets are loaded.')
// //     return undefined
// //   }

// //   const asset = cachedAssets.find(a => a.name === name)
// //   return asset
// // }

// // export const getAllAssets = (): Asset[] => {
// //   return cachedAssets
// // }

// // export const getAssetValue = (name: string): string | undefined => {
// //   const asset = getAsset(name)
// //   return asset?.url
// // }

// // export const getAssetType = (name: string): string | undefined => {
// //   const asset = getAsset(name)
// //   return asset?.file_type
// // }

// // export const getAssetInfo = (name: string): { value: string; type: string; name: string } | undefined => {
// //   const asset = getAsset(name)
// //   if (!asset) return undefined
  
// //   return {
// //     value: asset.url,
// //     type: asset.file_type,
// //     name: asset.name
// //   }
// // }

// // // Hook to access all assets
// // export const useAssets = (): Asset[] => {
// //   const { projectData } = useTheme()
// //   return projectData?.assets || []
// // }

// // // Hook to get a specific asset
// // export const useAsset = (name: string): Asset | undefined => {
// //   const assets = useAssets()
// //   const asset = assets.find(a => a.name === name)
// //   return asset
// // }

// // // Hook to get asset URL (most common use case)
// // export const useAssetValue = (name: string): string | undefined => {
// //   const asset = useAsset(name)
// //   return asset?.url
// // }

// // // Hook to get asset type
// // export const useAssetType = (name: string): string | undefined => {
// //   const asset = useAsset(name)
// //   return asset?.file_type
// // }

// // // Hook to get complete asset info
// // export const useAssetInfo = (name: string): { value: string; type: string; name: string } | undefined => {
// //   const asset = useAsset(name)
// //   if (!asset) return undefined
  
// //   return {
// //     value: asset.url,
// //     type: asset.file_type,
// //     name: asset.name
// //   }
// // }

// // // Hook to filter assets by type
// // export const useAssetsByType = (type: string): Asset[] => {
// //   const assets = useAssets()
// //   return assets.filter(asset => asset.file_type === type)
// // }

// // // Hook to get image assets
// // export const useImageAssets = (): Asset[] => {
// //   return useAssetsByType('image')
// // }

// // // Hook to get video assets
// // export const useVideoAssets = (): Asset[] => {
// //   return useAssetsByType('video')
// // }

// // // Hook to get audio assets
// // export const useAudioAssets = (): Asset[] => {
// //   return useAssetsByType('audio')
// // }

// // // Hook to get document assets
// // export const useDocumentAssets = (): Asset[] => {
// //   return useAssetsByType('document')
// // }