// Activation Page Logic

// DOM Elements
const licenseKey = document.getElementById('licenseKey');
const activateBtn = document.getElementById('activateBtn');
const skipBtn = document.getElementById('skipBtn');
const activationMessage = document.getElementById('activationMessage');
const toastContainer = document.getElementById('toastContainer');

// Format license key as user types
licenseKey.addEventListener('input', function(e) {
    let value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
    
    // Format as MACRO-XXXX-XXXX-XXXX-XXXX
    let formatted = '';
    if (value.length > 0) {
        // Check if it starts with MACRO
        if (!value.startsWith('MACRO')) {
            if ('MACRO'.startsWith(value)) {
                // User is typing MACRO
                formatted = value;
            } else {
                // Auto-prepend MACRO
                formatted = 'MACRO-' + value;
                value = 'MACRO' + value;
            }
        } else {
            // Format with dashes
            const parts = [];
            parts.push(value.slice(0, 5)); // MACRO
            
            for (let i = 5; i < Math.min(value.length, 21); i += 4) {
                parts.push(value.slice(i, i + 4));
            }
            
            formatted = parts.filter(p => p.length > 0).join('-');
        }
    }
    
    e.target.value = formatted;
});

// Activate button click handler
activateBtn.addEventListener('click', async function() {
    const key = licenseKey.value.trim().toUpperCase();
    
    // Validate format
    if (!key) {
        showMessage('Please enter a license key', 'error');
        return;
    }
    
    if (!key.startsWith('MACRO-')) {
        showMessage('License key must start with MACRO-', 'error');
        return;
    }
    
    const parts = key.split('-');
    if (parts.length !== 5) {
        showMessage('Invalid key format. Use: MACRO-XXXX-XXXX-XXXX-XXXX', 'error');
        return;
    }
    
    // Show loading state
    activateBtn.classList.add('loading');
    activateBtn.disabled = true;
    hideMessage();
    
    try {
        // Call activation API
        const response = await fetch('/api/license/activate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                license_key: key
            })
        });
        
        const data = await response.json();
        
        if (response.ok && data.success) {
            // Success!
            showMessage(data.message || 'License activated successfully!', 'success');
            showToast('success', 'Success!', 'License activated - redirecting...');
            
            // Redirect to main app after 2 seconds
            setTimeout(() => {
                window.location.href = '/';
            }, 2000);
        } else {
            // Error
            showMessage(data.error || 'Activation failed. Please try again.', 'error');
            showToast('error', 'Error', data.error || 'Activation failed');
            
            // Re-enable button
            activateBtn.classList.remove('loading');
            activateBtn.disabled = false;
        }
    } catch (error) {
        console.error('Activation error:', error);
        showMessage('Network error. Please check your internet connection.', 'error');
        showToast('error', 'Error', 'Cannot connect to license server');
        
        // Re-enable button
        activateBtn.classList.remove('loading');
        activateBtn.disabled = false;
    }
});

// Skip button click handler
skipBtn.addEventListener('click', function() {
    if (confirm('Proceed without a license? Macro playback will be disabled until you activate a license key.')) {
        showToast('info', 'Unlicensed Mode', 'Macro playback will be disabled');
        
        // Redirect to main app
        setTimeout(() => {
            window.location.href = '/';
        }, 1500);
    }
});

// Allow Enter key to activate
licenseKey.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        activateBtn.click();
    }
});

// Message display functions
function showMessage(text, type) {
    activationMessage.textContent = text;
    activationMessage.className = 'activation-message show ' + type;
}

function hideMessage() {
    activationMessage.classList.remove('show');
}

// Toast notification function
function showToast(type, title, message) {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    
    const icons = {
        success: '<path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/>',
        error: '<circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/>',
        info: '<circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/>'
    };
    
    toast.innerHTML = `
        <svg class="toast-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            ${icons[type] || icons.info}
        </svg>
        <div class="toast-content">
            <div class="toast-title">${title}</div>
            <div class="toast-message">${message}</div>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        toast.style.animation = 'toastSlide 0.3s ease reverse';
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Auto-focus on license input
licenseKey.focus();

