import React, { createContext, useContext, useState, useEffect } from 'react';
import axios from 'axios';
import { BrandingConfig } from '../types';

interface BrandingContextType {
    branding: BrandingConfig | null;
    loading: boolean;
    refreshBranding: () => Promise<void>;
}

const defaultBranding: BrandingConfig = {
    appName: 'CloudCore',
    appLogo: 'https://cdn-icons-png.flaticon.com/512/5968/5968204.png',
    footerText: '© 2026 CloudCore. All rights reserved.',
    loginTitle: 'Welcome Back',
    loginSubtitle: 'Manage your cloud infrastructure with ease.'
};

const BrandingContext = createContext<BrandingContextType | undefined>(undefined);

export const BrandingProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [branding, setBranding] = useState<BrandingConfig | null>(null);
    const [loading, setLoading] = useState(true);

    const fetchBranding = async () => {
        try {
            // Use the public config endpoint
            const response = await fetch('/api/config/branding');
            const slidesResponse = await fetch('/api/config/login_slider');

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            let slides = [];

            if (slidesResponse.ok) {
                const slidesData = await slidesResponse.json();
                if (!slidesData.error) {
                    slides = slidesData;
                }
            }

            setBranding({ ...data, loginSlides: slides });
        } catch (error) {
            console.error('Failed to fetch branding config:', error);
            // Fallback to default if API fails (e.g., first run before seed)
            setBranding(defaultBranding);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchBranding();
    }, []);

    return (
        <BrandingContext.Provider value={{ branding, loading, refreshBranding: fetchBranding }}>
            {children}
        </BrandingContext.Provider>
    );
};

export const useBranding = () => {
    const context = useContext(BrandingContext);
    if (context === undefined) {
        throw new Error('useBranding must be used within a BrandingProvider');
    }
    return context;
};
