/**
 * ZAI Bridge License Manager - Frontend JavaScript
 * Handles license validation, status display, and user interactions
 */

class LicenseManager {
    constructor() {
        this.apiBaseUrl = 'http://localhost:8080/api';
        this.currentLicense = null;
        this.connectionStatus = 'checking';
        this.refreshInterval = null;
        
        this.initializeElements();
        this.bindEvents();
        this.checkConnection();
        this.loadSavedLicense();
    }

    initializeElements() {
        // Input elements
        this.licenseKeyInput = document.getElementById('licenseKey');
        this.validateBtn = document.getElementById('validateBtn');
        this.inputFeedback = document.getElementById('inputFeedback');
        
        // Status elements
        this.connectionStatus = document.getElementById('connectionStatus');
        this.licenseStatusSection = document.getElementById('licenseStatusSection');
        this.licenseTier = document.getElementById('licenseTier');
        this.licenseId = document.getElementById('licenseId');
        this.licenseStatus = document.getElementById('licenseStatus');
        this.licenseExpiry = document.getElementById('licenseExpiry');
        this.licenseFeatures = document.getElementById('licenseFeatures');
        this.deviceUsage = document.getElementById('deviceUsage');
        this.deviceUsageFill = document.getElementById('deviceUsageFill');
        this.deviceList = document.getElementById('deviceList');
        
        // Statistics elements
        this.totalSessions = document.getElementById('totalSessions');
        this.totalConversations = document.getElementById('totalConversations');
        this.totalMessages = document.getElementById('totalMessages');
        this.lastUsed = document.getElementById('lastUsed');
        
        // Action buttons
        this.pasteBtn = document.getElementById('pasteBtn');
        this.importBtn = document.getElementById('importBtn');
        this.refreshBtn = document.getElementById('refreshBtn');
        this.exportBtn = document.getElementById('exportBtn');
        this.clearBtn = document.getElementById('clearBtn');
        this.supportBtn = document.getElementById('supportBtn');
        this.docsBtn = document.getElementById('docsBtn');
        
        // Modal and overlay elements
        this.loadingOverlay = document.getElementById('loadingOverlay');
        this.notificationToast = document.getElementById('notificationToast');
        this.modalOverlay = document.getElementById('modalOverlay');
        this.modalTitle = document.getElementById('modalTitle');
        this.modalMessage = document.getElementById('modalMessage');
        this.modalConfirm = document.getElementById('modalConfirm');
        this.modalCancel = document.getElementById('modalCancel');
        this.modalClose = document.getElementById('modalClose');
    }

    bindEvents() {
        // License input events
        this.validateBtn.addEventListener('click', () => this.validateLicense());
        this.licenseKeyInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.validateLicense();
        });
        this.licenseKeyInput.addEventListener('input', () => this.validateLicenseFormat());
        
        // Action button events
        this.pasteBtn.addEventListener('click', () => this.pasteFromClipboard());
        this.importBtn.addEventListener('click', () => this.importFromFile());
        this.refreshBtn.addEventListener('click', () => this.refreshLicenseStatus());
        this.exportBtn.addEventListener('click', () => this.exportLicense());
        this.clearBtn.addEventListener('click', () => this.clearLicense());
        this.supportBtn.addEventListener('click', () => this.openSupport());
        this.docsBtn.addEventListener('click', () => this.openDocumentation());
        
        // Modal events
        this.modalClose.addEventListener('click', () => this.hideModal());
        this.modalCancel.addEventListener('click', () => this.hideModal());
        this.modalOverlay.addEventListener('click', (e) => {
            if (e.target === this.modalOverlay) this.hideModal();
        });
    }

    async checkConnection() {
        try {
            const response = await fetch(`${this.apiBaseUrl}/status`);
            if (response.ok) {
                this.updateConnectionStatus('connected');
                // Auto-load license status if connected
                this.refreshLicenseStatus();
            } else {
                this.updateConnectionStatus('disconnected');
            }
        } catch (error) {
            this.updateConnectionStatus('disconnected');
            console.log('Connection check failed - server may not be running');
        }

        // Check connection every 30 seconds
        setTimeout(() => this.checkConnection(), 30000);
    }

    updateConnectionStatus(status) {
        this.connectionStatus = status;
        const statusElement = document.getElementById('connectionStatus');
        const icon = statusElement.querySelector('i');
        const text = statusElement.querySelector('span');
        
        statusElement.className = `status-indicator ${status}`;
        
        switch (status) {
            case 'connected':
                icon.className = 'fas fa-circle';
                text.textContent = 'Connected';
                break;
            case 'disconnected':
                icon.className = 'fas fa-circle';
                text.textContent = 'Disconnected';
                break;
            default:
                icon.className = 'fas fa-circle';
                text.textContent = 'Checking...';
        }
    }

    validateLicenseFormat() {
        const licenseKey = this.licenseKeyInput.value.trim();
        
        if (!licenseKey) {
            this.clearInputFeedback();
            return;
        }
        
        // Basic format validation
        const isValidFormat = /^ZAI-[A-Z0-9]{4,}-[A-Z0-9]{4,}-[A-Z0-9]{4,}/.test(licenseKey) ||
                             /^ZAI-TEST-[A-Z0-9-]+/.test(licenseKey);
        
        if (isValidFormat) {
            this.showInputFeedback('Format looks valid', 'success', 'fas fa-check');
        } else {
            this.showInputFeedback('Invalid license format', 'error', 'fas fa-exclamation-triangle');
        }
    }

    async validateLicense() {
        const licenseKey = this.licenseKeyInput.value.trim();
        
        if (!licenseKey) {
            this.showInputFeedback('Please enter a license key', 'error', 'fas fa-exclamation-triangle');
            return;
        }
        
        this.showLoading('Validating license...');
        this.validateBtn.disabled = true;
        
        try {
            const response = await fetch(`${this.apiBaseUrl}/license/validate`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ licenseKey })
            });
            
            const result = await response.json();
            
            if (result.success && result.license) {
                this.currentLicense = result.license;
                this.saveLicense(licenseKey);
                this.showLicenseStatus();
                this.showInputFeedback('License validated successfully!', 'success', 'fas fa-check');
                this.showNotification('License validated successfully!', 'success');
                this.startAutoRefresh();
            } else {
                this.showInputFeedback(result.error || 'License validation failed', 'error', 'fas fa-exclamation-triangle');
                this.showNotification(result.error || 'License validation failed', 'error');
            }
        } catch (error) {
            console.error('License validation error:', error);
            this.showInputFeedback('Connection error. Please try again.', 'error', 'fas fa-exclamation-triangle');
            this.showNotification('Connection error. Please try again.', 'error');
        } finally {
            this.hideLoading();
            this.validateBtn.disabled = false;
        }
    }

    showLicenseStatus() {
        if (!this.currentLicense) return;
        
        // Show license status section
        this.licenseStatusSection.style.display = 'block';
        
        // Update license information
        this.licenseTier.textContent = this.currentLicense.tier || 'UNKNOWN';
        this.licenseId.textContent = this.currentLicense.licenseId || 'N/A';
        this.licenseStatus.textContent = this.currentLicense.status || 'Unknown';
        this.licenseExpiry.textContent = this.currentLicense.expiresAt ? 
            new Date(this.currentLicense.expiresAt).toLocaleDateString() : 'Lifetime';
        
        // Update features
        this.updateFeatures(this.currentLicense.features || []);
        
        // Update device usage
        this.updateDeviceUsage(this.currentLicense);
        
        // Update statistics
        this.updateStatistics(this.currentLicense.usage || {});
    }

    updateFeatures(features) {
        this.licenseFeatures.innerHTML = '';
        features.forEach(feature => {
            const tag = document.createElement('span');
            tag.className = 'feature-tag';
            tag.textContent = feature.replace(/_/g, ' ').toUpperCase();
            this.licenseFeatures.appendChild(tag);
        });
    }

    updateDeviceUsage(license) {
        const devicesUsed = license.devices ? license.devices.length : 0;
        const maxDevices = license.tierConfig ? license.tierConfig.maxDevices : 1;
        const usagePercent = (devicesUsed / maxDevices) * 100;
        
        this.deviceUsage.textContent = `${devicesUsed}/${maxDevices}`;
        this.deviceUsageFill.style.width = `${usagePercent}%`;
        
        // Update device list
        this.deviceList.innerHTML = '';
        if (license.devices) {
            license.devices.forEach(device => {
                const deviceItem = document.createElement('div');
                deviceItem.className = 'device-item';
                deviceItem.innerHTML = `
                    <div class="device-info">
                        <div class="device-name">${device.deviceName || 'Unknown Device'}</div>
                        <div class="device-details">Last seen: ${new Date(device.lastSeen).toLocaleDateString()}</div>
                    </div>
                `;
                this.deviceList.appendChild(deviceItem);
            });
        }
    }

    updateStatistics(usage) {
        this.totalSessions.textContent = usage.totalSessions || 0;
        this.totalConversations.textContent = usage.totalConversations || 0;
        this.totalMessages.textContent = usage.totalMessages || 0;
        this.lastUsed.textContent = usage.lastUsed ? 
            new Date(usage.lastUsed).toLocaleDateString() : 'Never';
    }

    async pasteFromClipboard() {
        try {
            const text = await navigator.clipboard.readText();
            this.licenseKeyInput.value = text.trim();
            this.validateLicenseFormat();
            this.showNotification('License pasted from clipboard', 'success');
        } catch (error) {
            this.showNotification('Failed to read from clipboard', 'error');
        }
    }

    importFromFile() {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.txt,.json';
        input.onchange = (e) => {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const content = e.target.result;
                        let licenseKey = content.trim();
                        
                        // Try to parse as JSON first
                        try {
                            const json = JSON.parse(content);
                            licenseKey = json.licenseKey || json.token || licenseKey;
                        } catch (e) {
                            // Not JSON, use as plain text
                        }
                        
                        this.licenseKeyInput.value = licenseKey;
                        this.validateLicenseFormat();
                        this.showNotification('License imported from file', 'success');
                    } catch (error) {
                        this.showNotification('Failed to import license file', 'error');
                    }
                };
                reader.readAsText(file);
            }
        };
        input.click();
    }

    async refreshLicenseStatus() {
        if (!this.currentLicense) return;
        
        this.refreshBtn.disabled = true;
        const icon = this.refreshBtn.querySelector('i');
        icon.classList.add('fa-spin');
        
        try {
            const response = await fetch(`${this.apiBaseUrl}/license/status`);
            const result = await response.json();
            
            if (result.success && result.license) {
                this.currentLicense = result.license;
                this.showLicenseStatus();
                this.showNotification('License status refreshed', 'success');
            }
        } catch (error) {
            this.showNotification('Failed to refresh license status', 'error');
        } finally {
            this.refreshBtn.disabled = false;
            icon.classList.remove('fa-spin');
        }
    }

    exportLicense() {
        if (!this.currentLicense) {
            this.showNotification('No license to export', 'warning');
            return;
        }
        
        const exportData = {
            licenseKey: this.licenseKeyInput.value,
            license: this.currentLicense,
            exportedAt: new Date().toISOString()
        };
        
        const blob = new Blob([JSON.stringify(exportData, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `zai-license-${this.currentLicense.licenseId}.json`;
        a.click();
        URL.revokeObjectURL(url);
        
        this.showNotification('License exported successfully', 'success');
    }

    clearLicense() {
        this.showModal(
            'Clear License',
            'Are you sure you want to clear the current license? This will remove all license data.',
            () => {
                this.currentLicense = null;
                this.licenseKeyInput.value = '';
                this.licenseStatusSection.style.display = 'none';
                this.clearInputFeedback();
                this.clearSavedLicense();
                this.stopAutoRefresh();
                this.showNotification('License cleared successfully', 'success');
                this.hideModal();
            }
        );
    }

    openSupport() {
        window.open('https://zai-platform.com/support', '_blank');
    }

    openDocumentation() {
        window.open('https://docs.zai-platform.com/bridge', '_blank');
    }

    // Utility methods
    showInputFeedback(message, type, icon) {
        this.inputFeedback.innerHTML = `<i class="${icon}"></i> ${message}`;
        this.inputFeedback.className = `input-feedback ${type}`;
    }

    clearInputFeedback() {
        this.inputFeedback.innerHTML = '';
        this.inputFeedback.className = 'input-feedback';
    }

    showLoading(message = 'Loading...') {
        this.loadingOverlay.querySelector('p').textContent = message;
        this.loadingOverlay.classList.add('show');
    }

    hideLoading() {
        this.loadingOverlay.classList.remove('show');
    }

    showNotification(message, type = 'info') {
        const toast = this.notificationToast;
        const icon = toast.querySelector('.toast-icon');
        const messageEl = toast.querySelector('.toast-message');
        
        // Set icon based on type
        const icons = {
            success: 'fas fa-check-circle',
            error: 'fas fa-exclamation-circle',
            warning: 'fas fa-exclamation-triangle',
            info: 'fas fa-info-circle'
        };
        
        icon.className = `toast-icon ${icons[type]}`;
        messageEl.textContent = message;
        toast.className = `notification-toast ${type} show`;
        
        // Auto hide after 5 seconds
        setTimeout(() => {
            toast.classList.remove('show');
        }, 5000);
    }

    showModal(title, message, onConfirm) {
        this.modalTitle.textContent = title;
        this.modalMessage.textContent = message;
        this.modalOverlay.classList.add('show');
        
        this.modalConfirm.onclick = onConfirm;
    }

    hideModal() {
        this.modalOverlay.classList.remove('show');
        this.modalConfirm.onclick = null;
    }

    saveLicense(licenseKey) {
        localStorage.setItem('zai_license_key', licenseKey);
        localStorage.setItem('zai_license_data', JSON.stringify(this.currentLicense));
    }

    loadSavedLicense() {
        const savedKey = localStorage.getItem('zai_license_key');
        const savedData = localStorage.getItem('zai_license_data');
        
        if (savedKey && savedData) {
            try {
                this.licenseKeyInput.value = savedKey;
                this.currentLicense = JSON.parse(savedData);
                this.showLicenseStatus();
                this.validateLicenseFormat();
                this.startAutoRefresh();
            } catch (error) {
                console.error('Failed to load saved license:', error);
                this.clearSavedLicense();
            }
        }
    }

    clearSavedLicense() {
        localStorage.removeItem('zai_license_key');
        localStorage.removeItem('zai_license_data');
    }

    startAutoRefresh() {
        this.stopAutoRefresh();
        this.refreshInterval = setInterval(() => {
            this.refreshLicenseStatus();
        }, 300000); // Refresh every 5 minutes
    }

    stopAutoRefresh() {
        if (this.refreshInterval) {
            clearInterval(this.refreshInterval);
            this.refreshInterval = null;
        }
    }
}

// Initialize the license manager when the page loads
document.addEventListener('DOMContentLoaded', () => {
    new LicenseManager();
});
