/**
 * Termin-Kalender REST API Wrapper
 * 
 * Replaces legacy $.ajax calls with native fetch() Promises.
 * Exposes methods globally under window.TerminKalender.API
 */
document.addEventListener('DOMContentLoaded', function () {
    window.TerminKalender = window.TerminKalender || {};
    
    // Fallback if data object is missing
    const data = window.terminKalenderData || {};
    const baseUrl = data.rest_url || '';
    const nonce = data.rest_nonce || '';

    window.TerminKalender.API = {
        
        /**
         * Generic fetch wrapper handling WP nonces and JSON parsing
         */
        request: async function(endpoint, options = {}) {
            const url = baseUrl + endpoint;
            
            const fetchOptions = {
                method: options.method || 'GET',
                headers: {
                    'X-WP-Nonce': nonce,
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            };

            if (options.body) {
                // If it's URLSearchParams, let the browser set the content type
                if (options.body instanceof URLSearchParams) {
                    delete fetchOptions.headers['Content-Type'];
                    fetchOptions.body = options.body;
                } else {
                    fetchOptions.body = JSON.stringify(options.body);
                }
            }

            try {
                const response = await fetch(url, fetchOptions);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const result = await response.json();
                return result;
            } catch (error) {
                console.error('Termin-Kalender API fetch error:', error);
                throw error;
            }
        },

        // -------------------------------------------------------------
        // EVENT ENDPOINTS
        // -------------------------------------------------------------
        
        getEvents: function(startStr, endStr, loadArchive = 0) {
            const params = new URLSearchParams({
                start: startStr,
                end: endStr,
                archive: loadArchive
            });
            return this.request('events?' + params.toString());
        },

        saveEvent: function(eventData) {
            // For x-www-form-urlencoded format matching the old jQuery $.ajax behavior
            let params = new URLSearchParams();
            for (let key in eventData) {
                if (eventData[key] !== null && eventData[key] !== undefined) {
                    // Boolean true/false needs to be stringified for params
                    if (typeof eventData[key] === 'boolean') {
                        params.append(key, eventData[key] ? 'true' : 'false');
                    } else {
                        params.append(key, eventData[key]);
                    }
                }
            }
            return this.request('events', {
                method: 'POST',
                body: params
            });
        },

        deleteEvent: function(eventId) {
            return this.request('events/' + eventId, {
                method: 'DELETE'
            });
        },

        // -------------------------------------------------------------
        // CATEGORY ENDPOINTS
        // -------------------------------------------------------------
        
        getCategories: function() {
            return this.request('categories');
        },

        saveCategory: function(categoryData) {
            let params = new URLSearchParams();
            for (let key in categoryData) {
                if (categoryData[key] !== null && categoryData[key] !== undefined) {
                    params.append(key, categoryData[key]);
                }
            }
            return this.request('categories', {
                method: 'POST',
                body: params
            });
        },

        deleteCategory: function(categoryId) {
            return this.request('categories/' + categoryId, {
                method: 'DELETE'
            });
        }
    };
});
