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

// Define the shape of our content based on content.json
interface HeroContent {
    badge: string;
    title1: string;
    title2: string;
    subtitle: string;
    button1: string;
    button2: string;
}

interface AboutContent {
    heading: string;
    name1: string;
    name2: string;
    bio1: string;
    quote: string;
    bio2: string;
    image: string;
}

interface BookContent {
    coverImage: string;
}

interface FooterContent {
    contact: {
        name: string;
        phone: string;
        email: string;
    };
    social: {
        instagram: string;
        twitter: string;
        facebook: string;
    };
}

interface ContentData {
    hero: HeroContent;
    about: AboutContent;
    book: BookContent;
    footer: FooterContent;
}

interface ContentContextType {
    content: ContentData | null;
    loading: boolean;
    error: string | null;
    updateContent: (newContent: ContentData) => Promise<void>;
    refreshContent: () => Promise<void>;
}

const ContentContext = createContext<ContentContextType | undefined>(undefined);

export const ContentProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [content, setContent] = useState<ContentData | null>(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);

    const fetchContent = async () => {
        try {
            setLoading(true);
            const response = await fetch('http://localhost:3001/api/content');
            if (!response.ok) throw new Error('Failed to fetch content');
            const data = await response.json();
            setContent(data);
            setError(null);
        } catch (err) {
            console.error(err);
            setError('Failed to load content');
        } finally {
            setLoading(false);
        }
    };

    const updateContent = async (newContent: ContentData) => {
        try {
            const response = await fetch('http://localhost:3001/api/content', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(newContent),
            });
            if (!response.ok) throw new Error('Failed to update content');
            setContent(newContent);
        } catch (err) {
            console.error(err);
            throw err;
        }
    };

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

    return (
        <ContentContext.Provider value={{ content, loading, error, updateContent, refreshContent: fetchContent }}>
            {children}
        </ContentContext.Provider>
    );
};

export const useContent = () => {
    const context = useContext(ContentContext);
    if (context === undefined) {
        throw new Error('useContent must be used within a ContentProvider');
    }
    return context;
};
