// API Configuration
const API_BASE_URL = 'http://localhost:12004/api';

// Authentication token management
let authToken = localStorage.getItem('authToken');

// API helper function
async function apiCall(endpoint, options = {}) {
    const url = `${API_BASE_URL}${endpoint}`;
    const config = {
        headers: {
            'Content-Type': 'application/json',
            ...(authToken && { 'Authorization': `Bearer ${authToken}` }),
            ...options.headers
        },
        ...options
    };

    try {
        const response = await fetch(url, config);
        const data = await response.json();

        if (!response.ok) {
            throw new Error(data.error || 'API request failed');
        }

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

// Authentication API
export const authAPI = {
    async register(name, email, password) {
        const data = await apiCall('/auth/register', {
            method: 'POST',
            body: JSON.stringify({ name, email, password })
        });
        authToken = data.token;
        localStorage.setItem('authToken', authToken);
        return data;
    },

    async login(email, password) {
        const data = await apiCall('/auth/login', {
            method: 'POST',
            body: JSON.stringify({ email, password })
        });
        authToken = data.token;
        localStorage.setItem('authToken', authToken);
        return data;
    },

    async logout() {
        await apiCall('/auth/logout', { method: 'POST' });
        authToken = null;
        localStorage.removeItem('authToken');
    },

    async getProfile() {
        return await apiCall('/auth/profile');
    }
};

// Mood tracking API
export const moodAPI = {
    async trackMood(moodType, intensity, notes) {
        return await apiCall('/mood/track', {
            method: 'POST',
            body: JSON.stringify({ moodType, intensity, notes })
        });
    },

    async getMoodHistory() {
        return await apiCall('/mood/history');
    }
};

// Thought record API
export const thoughtAPI = {
    async saveThoughtRecord(thoughtData) {
        return await apiCall('/thoughts', {
            method: 'POST',
            body: JSON.stringify(thoughtData)
        });
    },

    async getThoughtRecords() {
        return await apiCall('/thoughts');
    },

    async updateThoughtRecord(id, thoughtData) {
        return await apiCall(`/thoughts/${id}`, {
            method: 'PUT',
            body: JSON.stringify(thoughtData)
        });
    },

    async deleteThoughtRecord(id) {
        return await apiCall(`/thoughts/${id}`, {
            method: 'DELETE'
        });
    }
};

// Gratitude API
export const gratitudeAPI = {
    async saveGratitudeEntry(entry) {
        return await apiCall('/gratitude', {
            method: 'POST',
            body: JSON.stringify(entry)
        });
    },

    async getGratitudeEntries() {
        return await apiCall('/gratitude');
    },

    async updateGratitudeEntry(id, entry) {
        return await apiCall(`/gratitude/${id}`, {
            method: 'PUT',
            body: JSON.stringify(entry)
        });
    },

    async deleteGratitudeEntry(id) {
        return await apiCall(`/gratitude/${id}`, {
            method: 'DELETE'
        });
    }
};

// Progress API
export const progressAPI = {
    async getProgressStats() {
        return await apiCall('/dashboard/stats');
    },

    async getProgressHistory(days = 30) {
        return await apiCall(`/progress?days=${days}`);
    }
};

// Exercise API
export const exerciseAPI = {
    async logSession(type, duration) {
        return await apiCall('/exercises', {
            method: 'POST',
            body: JSON.stringify({ exerciseType: type, duration })
        });
    }
};

// Notification API
export const notificationAPI = {
    async getNotifications() {
        return await apiCall('/notifications');
    },

    async markAsRead(notificationId) {
        return await apiCall(`/notifications/${notificationId}/read`, {
            method: 'PUT'
        });
    },

    async deleteNotification(notificationId) {
        return await apiCall(`/notifications/${notificationId}`, {
            method: 'DELETE'
        });
    },

    async addNotification(notification) {
        return await apiCall('/notifications', {
            method: 'POST',
            body: JSON.stringify(notification)
        });
    }
};

// Check if user is authenticated
export function isAuthenticated() {
    return !!authToken;
}

// Initialize API with token check
export function initializeAPI() {
    if (!authToken) {
        // Redirect to login or show login modal
        console.log('User not authenticated');
        return false;
    }
    return true;
}