import AppData from "./AppData";

class CategoryData {
    _categories = [];
    _slugToIdMap = {};
    _idToSlugMap = {};
    _idToNameMap = {};
    _loaded = false;

    async load() {
        const appData = AppData.getInstance();
        const categoryUrl = appData._category_url;

        if (!categoryUrl) {
            console.error('Category URL not available');
            return;
        }

        try {
            const response = await fetch(categoryUrl);
            if (!response.ok) {
                throw new Error(`Failed to load categories: ${response.statusText}`);
            }

            const data = await response.json();
            this._categories = Array.isArray(data) ? data : (data.categories || []);

            // Build slug/ID mapping
            this._buildMappings(this._categories);
            this._loaded = true;
        } catch (error) {
            console.error('Error loading categories:', error);
        }
    }

    _buildMappings(categories) {
        categories.forEach(category => {
            const id = category.id;
            const slug = category.slug;
            const name = category.name;

            if (id && slug) {
                this._slugToIdMap[slug] = id;
                this._idToSlugMap[id] = slug;
            }

            if (id && name) {
                this._idToNameMap[id] = name;
            }

            // Handle nested categories if they exist
            if (category.children && category.children.length > 0) {
                this._buildMappings(category.children);
            }
        });
    }

    getIdFromSlug(slug) {
        return this._slugToIdMap[slug] || null;
    }

    getSlugFromId(id) {
        return this._idToSlugMap[id] || null;
    }

    getSlugsFromIds(ids) {
        return ids.map(id => this.getSlugFromId(id)).filter(slug => slug !== null);
    }

    getIdsFromSlugs(slugs) {
        return slugs.map(slug => this.getIdFromSlug(slug)).filter(id => id !== null);
    }

    getCategoryNameById(id) {
        return this._idToNameMap[id] || null;
    }

    getCategoryNamesFromIds(ids) {
        return ids.map(id => this.getCategoryNameById(id)).filter(name => name !== null);
    }

    isLoaded() {
        return this._loaded;
    }

    static getInstance() {
        if (!window._categoryDataInstance) {
            window._categoryDataInstance = new CategoryData();
        }
        return window._categoryDataInstance;
    }
}

// Make globally accessible for ProductCard and other components
if (typeof window !== 'undefined') {
    window.CategoryData = CategoryData;
}

export default CategoryData;
