// Offline API Implementation using LocalStorage
// This replaces the server-based API for the offline APK build

// --- Local Database Helper ---
const db = {
    get(key) {
        const data = localStorage.getItem(`mindshift_${key}`);
        return data ? JSON.parse(data) : [];
    },
    set(key, data) {
        localStorage.setItem(`mindshift_${key}`, JSON.stringify(data));
    },
    add(key, item) {
        const data = this.get(key);
        item.id = Date.now().toString();
        item.created_at = new Date().toISOString();
        // Add user_id if logged in
        const user = getCurrentUser();
        if (user) item.user_id = user.id;
        
        data.push(item);
        this.set(key, data);
        return item;
    },
    update(key, id, updates) {
        const data = this.get(key);
        const index = data.findIndex(item => item.id === id);
        if (index !== -1) {
            data[index] = { ...data[index], ...updates };
            this.set(key, data);
            return data[index];
        }
        return null;
    },
    remove(key, id) {
        const data = this.get(key);
        const newData = data.filter(item => item.id !== id);
        this.set(key, newData);
    }
};

function getCurrentUser() {
    const userStr = localStorage.getItem('mindshift_currentUser');
    return userStr ? JSON.parse(userStr) : null;
}

// --- Authentication API ---
export const authAPI = {
    async register(name, email, password) {
        // Simulate network delay
        await new Promise(r => setTimeout(r, 500));
        
        const users = db.get('users');
        if (users.find(u => u.email === email)) {
            throw new Error('Email already exists');
        }
        
        const newUser = { id: Date.now().toString(), name, email, password }; // In real app, hash password!
        users.push(newUser);
        db.set('users', users);
        
        localStorage.setItem('mindshift_currentUser', JSON.stringify(newUser));
        return { token: 'offline-token', user: newUser };
    },

    async login(email, password) {
        await new Promise(r => setTimeout(r, 500));
        
        const users = db.get('users');
        const user = users.find(u => u.email === email && u.password === password);
        
        if (!user) {
            throw new Error('Invalid credentials');
        }
        
        localStorage.setItem('mindshift_currentUser', JSON.stringify(user));
        return { token: 'offline-token', user };
    },

    async logout() {
        localStorage.removeItem('mindshift_currentUser');
    },

    async getProfile() {
        return getCurrentUser();
    }
};

// --- Mood API ---
export const moodAPI = {
    async trackMood(moodType, intensity, notes) {
        return db.add('moods', { mood_type: moodType, intensity, notes });
    },

    async getMoodHistory() {
        const user = getCurrentUser();
        if (!user) return [];
        const moods = db.get('moods').filter(m => m.user_id === user.id);
        return moods.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    }
};

// --- Thought Record API ---
export const thoughtAPI = {
    async saveThoughtRecord(thoughtData) {
        // Map frontend keys to DB keys if needed, but for offline we can store as is
        return db.add('thoughts', thoughtData);
    },

    async getThoughtRecords() {
        const user = getCurrentUser();
        if (!user) return [];
        const thoughts = db.get('thoughts').filter(t => t.user_id === user.id);
        return thoughts.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    },
    
    async updateThoughtRecord(id, data) {
        return db.update('thoughts', id, data);
    },
    
    async deleteThoughtRecord(id) {
        return db.remove('thoughts', id);
    }
};

// --- Gratitude API ---
export const gratitudeAPI = {
    async saveGratitudeEntry(entry) {
        // Entry object comes as { entries: [], date: ... }
        // We'll store individual entries or the whole block.
        // Let's store the block to match frontend expectation
        return db.add('gratitude', entry);
    },

    async getGratitudeEntries() {
        const user = getCurrentUser();
        if (!user) return [];
        const entries = db.get('gratitude').filter(g => g.user_id === user.id);
        return entries.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
    }
};

// --- Progress API ---
export const progressAPI = {
    async getProgressStats() {
        const user = getCurrentUser();
        if (!user) return { today: {}, week: {}, totals: {} };

        const moods = db.get('moods').filter(m => m.user_id === user.id);
        const gratitude = db.get('gratitude').filter(g => g.user_id === user.id);
        const exercises = db.get('exercises').filter(e => e.user_id === user.id);
        
        const today = new Date().toISOString().split('T')[0];
        const todayMoods = moods.filter(m => m.created_at.startsWith(today));
        
        // Calculate stats
        const todayAvg = todayMoods.length > 0 
            ? todayMoods.reduce((sum, m) => sum + parseInt(m.intensity), 0) / todayMoods.length 
            : 0;

        return {
            today: { mood_score: todayAvg.toFixed(1) },
            totals: {
                totalSessions: exercises.length,
                totalGratitude: gratitude.length
            },
            week: { avgMood: 0 } // simplified for offline
        };
    },

    async getProgressHistory(days = 7) {
        const user = getCurrentUser();
        if (!user) return [];
        
        const moods = db.get('moods').filter(m => m.user_id === user.id);
        // Group by date and avg score
        const history = [];
        for (let i = 0; i < days; i++) {
            const date = new Date();
            date.setDate(date.getDate() - i);
            const dateStr = date.toISOString().split('T')[0];
            
            const dayMoods = moods.filter(m => m.created_at.startsWith(dateStr));
            const score = dayMoods.length > 0 
                ? dayMoods.reduce((sum, m) => sum + parseInt(m.intensity), 0) / dayMoods.length 
                : 0;
            
            history.push({ date: dateStr, mood_score: score });
        }
        return history;
    }
};

// --- Exercise API ---
export const exerciseAPI = {
    async logSession(type, duration) {
        return db.add('exercises', { exercise_type: type, duration });
    }
};

// --- Notification API ---
export const notificationAPI = {
    async getNotifications() {
        const user = getCurrentUser();
        if (!user) return [];
        return db.get('notifications').filter(n => n.user_id === user.id);
    },

    async markAsRead(id) {
        return db.update('notifications', id, { read: true });
    },

    async deleteNotification(id) {
        return db.remove('notifications', id);
    },

    async addNotification(notification) {
        return db.add('notifications', notification);
    }
};

export function isAuthenticated() {
    return !!getCurrentUser();
}

export function initializeAPI() {
    return true;
}
