/**
 * Ad Manager JavaScript Module
 * Handles real-time metrics updates, variant selection, and interactive UI components
 */

class AdManager {
    constructor() {
        this.metricsUpdateInterval = null;
        this.updateFrequency = 30000; // 30 seconds
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.initializeMetricsPolling();
        this.initializeVariantSelection();
        this.initializeCharts();
    }

    /**
     * Setup event listeners for various UI interactions
     */
    setupEventListeners() {
        // Variant selection checkboxes
        document.querySelectorAll('.variant-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', this.handleVariantSelection.bind(this));
        });

        // Launch variants button
        const launchBtn = document.getElementById('launchVariantsBtn');
        if (launchBtn) {
            launchBtn.addEventListener('click', this.launchSelectedVariants.bind(this));
        }

        // Pause variants button
        const pauseBtn = document.getElementById('pauseVariantsBtn');
        if (pauseBtn) {
            pauseBtn.addEventListener('click', this.pauseSelectedVariants.bind(this));
        }

        // Select all variants checkbox
        const selectAllCheckbox = document.getElementById('selectAllVariants');
        if (selectAllCheckbox) {
            selectAllCheckbox.addEventListener('change', this.toggleAllVariants.bind(this));
        }

        // Refresh metrics button
        const refreshBtn = document.getElementById('refreshMetricsBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', this.refreshMetrics.bind(this));
        }
    }

    /**
     * Initialize real-time metrics polling
     */
    initializeMetricsPolling() {
        const adId = this.getAdIdFromUrl();
        if (!adId) return;

        // Initial load
        this.fetchMetrics(adId);

        // Set up polling
        this.metricsUpdateInterval = setInterval(() => {
            this.fetchMetrics(adId);
        }, this.updateFrequency);
    }

    /**
     * Fetch metrics from API
     */
    async fetchMetrics(adId) {
        try {
            const response = await fetch(`/brand/ads/${adId}/metrics`, {
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

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

            const data = await response.json();
            this.updateMetricsDisplay(data);
        } catch (error) {
            console.error('Error fetching metrics:', error);
            this.showNotification('Failed to update metrics', 'error');
        }
    }

    /**
     * Update metrics display with new data
     */
    updateMetricsDisplay(data) {
        if (!data.success || !data.variants) return;

        data.variants.forEach(variant => {
            const variantCard = document.querySelector(`[data-variant-id="${variant.variant_id}"]`);
            if (!variantCard) return;

            // Update impressions
            const impressionsEl = variantCard.querySelector('.metric-impressions');
            if (impressionsEl) {
                impressionsEl.textContent = this.formatNumber(variant.metrics.impressions);
            }

            // Update clicks
            const clicksEl = variantCard.querySelector('.metric-clicks');
            if (clicksEl) {
                clicksEl.textContent = this.formatNumber(variant.metrics.clicks);
            }

            // Update conversions
            const conversionsEl = variantCard.querySelector('.metric-conversions');
            if (conversionsEl) {
                conversionsEl.textContent = this.formatNumber(variant.metrics.conversions);
            }

            // Update CTR
            const ctrEl = variantCard.querySelector('.metric-ctr');
            if (ctrEl) {
                ctrEl.textContent = variant.metrics.ctr + '%';
                this.updateMetricBadge(ctrEl, variant.metrics.ctr, 1.0);
            }

            // Update conversion rate
            const convRateEl = variantCard.querySelector('.metric-conversion-rate');
            if (convRateEl) {
                convRateEl.textContent = variant.metrics.conversion_rate + '%';
            }

            // Add pulse animation to indicate update
            variantCard.classList.add('metrics-updated');
            setTimeout(() => {
                variantCard.classList.remove('metrics-updated');
            }, 1000);
        });

        // Update last updated timestamp
        const timestampEl = document.getElementById('metricsLastUpdated');
        if (timestampEl) {
            timestampEl.textContent = new Date().toLocaleTimeString();
        }
    }

    /**
     * Update metric badge color based on performance
     */
    updateMetricBadge(element, value, threshold) {
        element.classList.remove('bg-success', 'bg-warning', 'bg-secondary');
        
        if (value >= threshold * 1.5) {
            element.classList.add('bg-success');
        } else if (value >= threshold) {
            element.classList.add('bg-warning');
        } else {
            element.classList.add('bg-secondary');
        }
    }

    /**
     * Initialize variant selection functionality
     */
    initializeVariantSelection() {
        this.updateSelectionCount();
    }

    /**
     * Handle individual variant selection
     */
    handleVariantSelection(event) {
        this.updateSelectionCount();
        this.updateSelectAllCheckbox();
    }

    /**
     * Toggle all variants selection
     */
    toggleAllVariants(event) {
        const isChecked = event.target.checked;
        document.querySelectorAll('.variant-checkbox').forEach(checkbox => {
            checkbox.checked = isChecked;
        });
        this.updateSelectionCount();
    }

    /**
     * Update select all checkbox state
     */
    updateSelectAllCheckbox() {
        const selectAllCheckbox = document.getElementById('selectAllVariants');
        if (!selectAllCheckbox) return;

        const checkboxes = document.querySelectorAll('.variant-checkbox');
        const checkedCount = document.querySelectorAll('.variant-checkbox:checked').length;
        
        selectAllCheckbox.checked = checkedCount === checkboxes.length;
        selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
    }

    /**
     * Update selection count display
     */
    updateSelectionCount() {
        const count = document.querySelectorAll('.variant-checkbox:checked').length;
        const countEl = document.getElementById('selectedVariantsCount');
        
        if (countEl) {
            countEl.textContent = count;
        }

        // Enable/disable action buttons based on selection
        const launchBtn = document.getElementById('launchVariantsBtn');
        const pauseBtn = document.getElementById('pauseVariantsBtn');
        
        if (launchBtn) launchBtn.disabled = count === 0;
        if (pauseBtn) pauseBtn.disabled = count === 0;
    }

    /**
     * Launch selected variants
     */
    launchSelectedVariants() {
        const selectedIds = this.getSelectedVariantIds();
        
        if (selectedIds.length === 0) {
            this.showNotification('Please select at least one variant to launch', 'warning');
            return;
        }

        if (confirm(`Launch ${selectedIds.length} selected variant(s)?`)) {
            this.submitVariantAction('launch', selectedIds);
        }
    }

    /**
     * Pause selected variants
     */
    pauseSelectedVariants() {
        const selectedIds = this.getSelectedVariantIds();
        
        if (selectedIds.length === 0) {
            this.showNotification('Please select at least one variant to pause', 'warning');
            return;
        }

        if (confirm(`Pause ${selectedIds.length} selected variant(s)?`)) {
            this.submitVariantAction('pause', selectedIds);
        }
    }

    /**
     * Get selected variant IDs
     */
    getSelectedVariantIds() {
        const checkboxes = document.querySelectorAll('.variant-checkbox:checked');
        return Array.from(checkboxes).map(cb => cb.value);
    }

    /**
     * Submit variant action (launch/pause)
     */
    submitVariantAction(action, variantIds) {
        const adId = this.getAdIdFromUrl();
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/brand/ads/${adId}/${action}-variants`;

        // Add CSRF token
        const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '_token';
        csrfInput.value = csrfToken;
        form.appendChild(csrfInput);

        // Add variant IDs
        variantIds.forEach(id => {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'variant_ids[]';
            input.value = id;
            form.appendChild(input);
        });

        document.body.appendChild(form);
        form.submit();
    }

    /**
     * Refresh metrics manually
     */
    async refreshMetrics() {
        const adId = this.getAdIdFromUrl();
        if (!adId) return;

        const refreshBtn = document.getElementById('refreshMetricsBtn');
        if (refreshBtn) {
            refreshBtn.disabled = true;
            refreshBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Refreshing...';
        }

        await this.fetchMetrics(adId);

        if (refreshBtn) {
            refreshBtn.disabled = false;
            refreshBtn.innerHTML = '<i class="fas fa-sync me-2"></i>Refresh';
        }

        this.showNotification('Metrics updated successfully', 'success');
    }

    /**
     * Initialize charts if Chart.js is available
     */
    initializeCharts() {
        if (typeof Chart === 'undefined') return;

        // Charts are initialized in the blade template
        // This method can be extended for dynamic chart updates
    }

    /**
     * Get ad ID from current URL
     */
    getAdIdFromUrl() {
        const pathParts = window.location.pathname.split('/');
        const adsIndex = pathParts.indexOf('ads');
        return adsIndex !== -1 && pathParts[adsIndex + 1] ? pathParts[adsIndex + 1] : null;
    }

    /**
     * Format number with commas
     */
    formatNumber(num) {
        return new Intl.NumberFormat().format(num);
    }

    /**
     * Show notification to user
     */
    showNotification(message, type = 'info') {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = `alert alert-${type} alert-dismissible fade show position-fixed top-0 end-0 m-3`;
        notification.style.zIndex = '9999';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;

        document.body.appendChild(notification);

        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            notification.remove();
        }, 5000);
    }

    /**
     * Cleanup when page is unloaded
     */
    destroy() {
        if (this.metricsUpdateInterval) {
            clearInterval(this.metricsUpdateInterval);
        }
    }
}

// Initialize Ad Manager when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    window.adManager = new AdManager();
});

// Cleanup on page unload
window.addEventListener('beforeunload', () => {
    if (window.adManager) {
        window.adManager.destroy();
    }
});

// Export for use in other modules
export default AdManager;