import React, { createContext, useContext, ReactNode, useEffect } from 'react';

interface AppContextType {
  isStandalone: boolean;
  exitFullscreen?: () => void;
}

const AppContext = createContext<AppContextType | undefined>(undefined);

export function AppProvider({
  children,
  isStandalone,
  exitFullscreen
}: {
  children: ReactNode;
  isStandalone: boolean;
  exitFullscreen?: () => void;
}) {
  useEffect(() => {
    // Fetch and apply appearance settings (colors)
    const loadAppearance = async () => {
      try {
        const restUrl = (window as any).WNW_CONFIG?.restUrl || '';
        const response = await fetch(`${restUrl}/appearance/settings`);
        if (response.ok) {
          const result = await response.json();
          // API returns { success: true, data: { general: { colors: {...} } } }
          const colors = result.data?.general?.colors;
          if (colors) {
            const root = document.documentElement;
            // Inject all color settings as CSS variables
            if (colors.primary) root.style.setProperty('--wn-primary', colors.primary);
            if (colors.secondary) root.style.setProperty('--wn-secondary', colors.secondary);
            if (colors.accent) root.style.setProperty('--wn-accent', colors.accent);
            if (colors.text) root.style.setProperty('--wn-text', colors.text);
            if (colors.background) root.style.setProperty('--wn-background', colors.background);
            if (colors.gradientStart) root.style.setProperty('--wn-gradient-start', colors.gradientStart);
            if (colors.gradientEnd) root.style.setProperty('--wn-gradient-end', colors.gradientEnd);
          }
        }
      } catch (e) {
        console.error('Failed to load appearance settings', e);
      }
    };
    loadAppearance();
  }, []);

  return (
    <AppContext.Provider value={{ isStandalone, exitFullscreen }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  const context = useContext(AppContext);
  if (context === undefined) {
    throw new Error('useApp must be used within an AppProvider');
  }
  return context;
}
