// API Client for making requests to the backend
class APIClient {
    constructor() {
        this.baseURL = '/api';
    }

    async makeRequest(endpoint, options = {}) {
        const config = {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        };

        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, config);
            const data = await response.json();

            if (!response.ok) {
                // Create enhanced error with response data for better error handling
                const error = new Error(data.error || data.message || `HTTP ${response.status}`);
                error.status = response.status;
                error.data = data;
                throw error;
            }

            return data;
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    }

    async get(endpoint) {
        return this.makeRequest(endpoint, {
            method: 'GET'
        });
    }

    async post(endpoint, data) {
        return this.makeRequest(endpoint, {
            method: 'POST',
            body: JSON.stringify(data)
        });
    }

    async put(endpoint, data) {
        return this.makeRequest(endpoint, {
            method: 'PUT',
            body: JSON.stringify(data)
        });
    }

    async patch(endpoint, data) {
        return this.makeRequest(endpoint, {
            method: 'PATCH',
            body: JSON.stringify(data)
        });
    }

    async delete(endpoint) {
        return this.makeRequest(endpoint, {
            method: 'DELETE'
        });
    }

    async postFormData(endpoint, formData) {
        // Don't set Content-Type header - browser will set it with boundary for multipart/form-data
        const config = {
            method: 'POST',
            body: formData
        };

        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, config);
            const data = await response.json();

            if (!response.ok) {
                const error = new Error(data.error || data.message || `HTTP ${response.status}`);
                error.status = response.status;
                error.data = data;
                throw error;
            }

            return data;
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    }

    async putFormData(endpoint, formData) {
        // Don't set Content-Type header - browser will set it with boundary for multipart/form-data
        const config = {
            method: 'PUT',
            body: formData
        };

        try {
            const response = await fetch(`${this.baseURL}${endpoint}`, config);
            const data = await response.json();

            if (!response.ok) {
                const error = new Error(data.error || data.message || `HTTP ${response.status}`);
                error.status = response.status;
                error.data = data;
                throw error;
            }

            return data;
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    }

    // Health check
    async checkHealth() {
        return this.get('/health');
    }

    // Test Represent API connection
    async testRepresent() {
        return this.get('/test-represent');
    }

    // Get representatives by postal code
    async getRepresentativesByPostalCode(postalCode) {
        const cleanPostalCode = postalCode.replace(/\s/g, '').toUpperCase();
        return this.get(`/representatives/by-postal/${cleanPostalCode}`);
    }

    // Refresh representatives for postal code
    async refreshRepresentatives(postalCode) {
        const cleanPostalCode = postalCode.replace(/\s/g, '').toUpperCase();
        return this.post(`/representatives/refresh-postal/${cleanPostalCode}`);
    }

    // Send email to representative
    async sendEmail(emailData) {
        return this.post('/emails/send', emailData);
    }

    // Preview email before sending
    async previewEmail(emailData) {
        return this.post('/emails/preview', emailData);
    }
}

// Create global instance
window.apiClient = new APIClient();