import CategoryData from "../Common/CategoryData";

class URLStateManager {
    static encodeFilters(filters) {
        const params = new URLSearchParams();

        // Encode categories (convert IDs to slugs)
        if (filters.categories && filters.categories.length > 0) {
            const categoryData = CategoryData.getInstance();
            const slugs = categoryData.getSlugsFromIds(filters.categories);
            if (slugs.length > 0) {
                params.set('categories', slugs.join(','));
            }
        }

        // Encode tags (store as IDs for now - could convert to slugs later if needed)
        if (filters.tags && filters.tags.length > 0) {
            params.set('tags', filters.tags.join(','));
        }

        // Encode attributes
        if (filters.attributes && Object.keys(filters.attributes).length > 0) {
            Object.entries(filters.attributes).forEach(([key, values]) => {
                if (values && values.length > 0) {
                    params.set(key, values.join(','));
                }
            });
        }

        // Encode price range
        if (filters.priceRange) {
            if (filters.priceRange.min !== null && filters.priceRange.min !== undefined) {
                params.set('price_min', filters.priceRange.min);
            }
            if (filters.priceRange.max !== null && filters.priceRange.max !== undefined) {
                params.set('price_max', filters.priceRange.max);
            }
        }

        // Encode search query
        if (filters.query && filters.query.trim() !== '') {
            params.set('q', filters.query);
        }

        return params;
    }

    static decodeFilters() {
        const params = new URLSearchParams(window.location.search);
        const filters = {
            categories: [],
            tags: [],
            attributes: {},
            priceRange: null,
            query: ''
        };

        // Decode categories (convert slugs to IDs)
        if (params.has('categories')) {
            const categoriesStr = params.get('categories');
            const slugs = categoriesStr.split(',').map(s => s.trim()).filter(s => s.length > 0);
            const categoryData = CategoryData.getInstance();
            filters.categories = categoryData.getIdsFromSlugs(slugs);
        }

        // Decode tags (stored as IDs)
        if (params.has('tags')) {
            const tagsStr = params.get('tags');
            filters.tags = tagsStr.split(',')
                .map(id => parseInt(id.trim(), 10))
                .filter(id => !isNaN(id));
        }

        // Decode price range
        if (params.has('price_min') || params.has('price_max')) {
            filters.priceRange = {
                min: params.has('price_min') ? parseFloat(params.get('price_min')) : null,
                max: params.has('price_max') ? parseFloat(params.get('price_max')) : null
            };
        }

        // Decode search query
        if (params.has('q')) {
            filters.query = params.get('q');
        }

        // Decode attributes (all params that start with pa_)
        for (const [key, value] of params.entries()) {
            if (key.startsWith('pa_')) {
                filters.attributes[key] = value.split(',');
            }
        }

        return filters;
    }

    static updateURL(filters, replaceState = false) {
        const params = URLStateManager.encodeFilters(filters);
        const queryString = params.toString();

        const newURL = queryString
            ? `${window.location.pathname}?${queryString}`
            : window.location.pathname;

        if (replaceState) {
            window.history.replaceState({ filters }, '', newURL);
        } else {
            window.history.pushState({ filters }, '', newURL);
        }
    }

    static hasFiltersInURL() {
        const params = new URLSearchParams(window.location.search);
        return params.toString().length > 0;
    }

    static clearURL() {
        window.history.pushState({}, '', window.location.pathname);
    }
}

export default URLStateManager;
