// config-manager.js - Simplified version with only Daily Message Limit

class ConfigManager {
    constructor() {
        this.currentConfig = {};
        this.init();
    }

    init() {
        this.attachEventListeners();
        this.loadConfig();
    }

    attachEventListeners() {
        // Refresh config button
        const refreshBtn = document.getElementById('refresh-config-btn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => this.loadConfig());
        }

        // Save config button
        const saveBtn = document.getElementById('save-config-btn');
        if (saveBtn) {
            saveBtn.addEventListener('click', () => this.saveConfig());
        }

        // Form input change handlers
        const formInputs = document.querySelectorAll('#config-form input');
        formInputs.forEach(input => {
            input.addEventListener('change', () => this.handleFormChange());
        });
    }

    async loadConfig() {
        try {
            const response = await fetch('/api/admin/config');
            
            if (!response.ok) {
                throw new Error('Failed to load config');
            }

            const data = await response.json();
            
            if (data.success) {
                this.currentConfig = data.config;
                this.updateUI();
                this.showToast('Configuration loaded successfully', 'success');
            } else {
                throw new Error(data.message || 'Failed to load config');
            }
        } catch (error) {
            console.error('Error loading config:', error);
            
            // Fallback to mock data for development
            this.currentConfig = {
                DAILY_MESSAGE_LIMIT: 9
            };
            this.updateUI();
            this.showToast('Using default configuration', 'warning');
        }
    }

    updateUI() {
        // Update form fields
        const dailyLimitInput = document.getElementById('daily-message-limit');
        if (dailyLimitInput) {
            dailyLimitInput.value = this.currentConfig.DAILY_MESSAGE_LIMIT || '';
        }
    }

    handleFormChange() {
        // Update config object from form inputs
        const dailyLimit = document.getElementById('daily-message-limit').value;

        if (dailyLimit) {
            this.currentConfig.DAILY_MESSAGE_LIMIT = parseInt(dailyLimit);
        }
    }

    async saveConfig() {
        try {
            // Validate that we have a daily message limit
            if (!this.currentConfig.DAILY_MESSAGE_LIMIT || this.currentConfig.DAILY_MESSAGE_LIMIT < 1) {
                this.showToast('Please enter a valid daily message limit (minimum 1)', 'error');
                return;
            }

            const response = await fetch('/api/admin/config', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(this.currentConfig)
            });

            if (!response.ok) {
                throw new Error('Failed to save config');
            }

            const data = await response.json();
            
            if (data.success) {
                this.showToast('Configuration saved successfully!', 'success');
                this.loadConfig(); // Reload to confirm changes
            } else {
                throw new Error(data.message || 'Failed to save config');
            }
        } catch (error) {
            console.error('Error saving config:', error);
            this.showToast('Error saving configuration: ' + error.message, 'error');
        }
    }

    showToast(message, type = 'info') {
        // Use the existing toast function if available
        if (typeof showToast === 'function') {
            showToast(message);
        } else {
            // Fallback toast implementation
            console.log(`Toast (${type}): ${message}`);
            
            // Create a simple toast if the main one doesn't exist
            let toast = document.getElementById('config-toast');
            if (!toast) {
                toast = document.createElement('div');
                toast.id = 'config-toast';
                toast.className = 'fixed bottom-4 right-4 z-50 px-6 py-3 rounded-md shadow-lg text-white';
                document.body.appendChild(toast);
            }

            // Set color based on type
            const colors = {
                success: 'bg-green-500',
                error: 'bg-red-500',
                warning: 'bg-yellow-500',
                info: 'bg-blue-500'
            };

            toast.className = `fixed bottom-4 right-4 z-50 px-6 py-3 rounded-md shadow-lg text-white ${colors[type] || colors.info}`;
            toast.textContent = message;
            toast.style.display = 'block';

            setTimeout(() => {
                toast.style.display = 'none';
            }, 3000);
        }
    }
}

// Initialize the config manager when the DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
    // Only initialize if the config section exists
    if (document.getElementById('config-section')) {
        window.configManager = new ConfigManager();
    }
});

// Add config section to navigation
document.addEventListener('DOMContentLoaded', function() {
    // Add config section to the sections object
    if (typeof sections !== 'undefined') {
        sections['config'] = document.getElementById('config-section');
    }
});