(function( $ ) {
    'use strict';

    window.SwFacetWpUser = (function () {
        const API_BASE = '/wp-json/sw-facetwp/v1';
        const DEFAULT_HEADERS = {
            'Content-Type': 'application/json',
            'X-WP-Nonce': swFacetWpUser?.nonce || ''
        };

        async function request(endpoint, method = 'GET', data = null) {
            const options = {
                method,
                headers: DEFAULT_HEADERS
            };

            if (data) {
                options.body = JSON.stringify(data);
            }

            try {
                const res = await fetch(`${API_BASE}${endpoint}`, options);

                if (!res.ok) throw res;

                const json = await res.json();

                return { success: true, data: json.data };
            } catch (err) {
                return handle_error(err);
            }
        }

        async function handle_error(err) {
            let errorData = { message: 'Unknown error occurred.' };

            if (err.json) {
                try {
                    errorData = await err.json();
                } catch (_) {}
            }

            console.error('SwFacetWpRemote API error:', errorData);

            return { success: false, error: errorData };
        }

        return {
            save_favorite_property: (property_id) =>
                request('/favorites', 'POST', { property_id }),

            get_favorite_properties: () =>
                request('/favorites'),

            remove_favorite_property: (property_id) =>
                request(`/favorites/${property_id}`, 'DELETE'),

            save_search: (title, url) =>
                request('/searches', 'POST', { title, url }),

            get_saved_searches: () =>
                request('/searches'),

            delete_saved_search: (index) =>
                request(`/searches/${index}`, 'DELETE'),
        };
    })();

})( jQuery );
