/**
 * ===========================================
 * FLOWBOT DCI - MAIN JAVASCRIPT
 * ===========================================
 * Frontend functionality and utilities
 */

(function() {
    'use strict';

    // App namespace
    window.FlowbotDCI = window.FlowbotDCI || {};

    /**
     * Initialize the application
     */
    FlowbotDCI.init = function() {
        this.initTerminalScroll();
        this.initProgressAnimations();
        this.initFormValidation();
        console.log('FlowbotDCI initialized');
    };

    /**
     * Auto-scroll terminal to bottom
     */
    FlowbotDCI.initTerminalScroll = function() {
        const terminal = document.querySelector('.terminal');
        if (terminal) {
            terminal.scrollTop = terminal.scrollHeight;

            // Watch for new content
            const observer = new MutationObserver(function() {
                terminal.scrollTop = terminal.scrollHeight;
            });

            observer.observe(terminal, { childList: true, subtree: true });
        }
    };

    /**
     * Animate progress bars on load
     */
    FlowbotDCI.initProgressAnimations = function() {
        const progressBars = document.querySelectorAll('.progress-bar-fill');

        progressBars.forEach(function(bar) {
            const targetWidth = bar.style.width;
            bar.style.width = '0%';

            setTimeout(function() {
                bar.style.width = targetWidth;
            }, 100);
        });
    };

    /**
     * Form validation
     */
    FlowbotDCI.initFormValidation = function() {
        const form = document.querySelector('form');
        if (!form) return;

        form.addEventListener('submit', function(e) {
            const textarea = form.querySelector('textarea[name="urls"]');
            if (textarea && !textarea.value.trim()) {
                e.preventDefault();
                FlowbotDCI.showAlert('Please enter at least one URL', 'warning');
                textarea.focus();
                return false;
            }

            // Show loading state
            const submitBtn = form.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.textContent = 'Processing...';
            }
        });
    };

    /**
     * Show alert message
     */
    FlowbotDCI.showAlert = function(message, type) {
        type = type || 'info';

        const alertDiv = document.createElement('div');
        alertDiv.className = 'alert alert-' + type;
        alertDiv.textContent = message;

        const container = document.querySelector('.card') || document.body;
        container.insertBefore(alertDiv, container.firstChild);

        // Auto-remove after 5 seconds
        setTimeout(function() {
            alertDiv.remove();
        }, 5000);
    };

    // =========================================
    // UI-003: Loading State Helpers
    // =========================================

    /**
     * Show loading spinner on an element
     * @param {HTMLElement|string} element - Element or selector
     * @param {string} text - Optional loading text
     */
    FlowbotDCI.showLoading = function(element, text) {
        if (typeof element === 'string') {
            element = document.querySelector(element);
        }
        if (!element) return;

        element.classList.add('loading');
        element.setAttribute('data-loading', 'true');

        // Create loading overlay for cards
        if (element.classList.contains('glass-card')) {
            const overlay = document.createElement('div');
            overlay.className = 'loading-overlay';
            overlay.innerHTML = '<div class="loading-spinner large"></div>' +
                (text ? '<div class="loading-text">' + FlowbotDCI.escapeHtml(text) + '</div>' : '');
            element.style.position = 'relative';
            element.appendChild(overlay);
        }
    };

    /**
     * Hide loading spinner on an element
     * @param {HTMLElement|string} element - Element or selector
     */
    FlowbotDCI.hideLoading = function(element) {
        if (typeof element === 'string') {
            element = document.querySelector(element);
        }
        if (!element) return;

        element.classList.remove('loading');
        element.removeAttribute('data-loading');

        // Remove loading overlay
        const overlay = element.querySelector('.loading-overlay');
        if (overlay) {
            overlay.remove();
        }
    };

    /**
     * Show loading state on a button
     * @param {HTMLElement|string} button - Button element or selector
     * @param {string} text - Optional button text while loading
     */
    FlowbotDCI.buttonLoading = function(button, text) {
        if (typeof button === 'string') {
            button = document.querySelector(button);
        }
        if (!button) return;

        button.classList.add('loading');
        button.disabled = true;
        button.setAttribute('data-original-text', button.textContent);
        if (text) {
            button.textContent = text;
        }
    };

    /**
     * Reset button from loading state
     * @param {HTMLElement|string} button - Button element or selector
     */
    FlowbotDCI.buttonReset = function(button) {
        if (typeof button === 'string') {
            button = document.querySelector(button);
        }
        if (!button) return;

        button.classList.remove('loading');
        button.disabled = false;
        const originalText = button.getAttribute('data-original-text');
        if (originalText) {
            button.textContent = originalText;
            button.removeAttribute('data-original-text');
        }
    };

    /**
     * Create inline loading indicator
     * @param {string} text - Loading text
     * @returns {HTMLElement}
     */
    FlowbotDCI.createInlineLoader = function(text) {
        const loader = document.createElement('span');
        loader.className = 'inline-loading';
        loader.innerHTML = '<span class="loading-spinner small"></span>' +
            '<span>' + FlowbotDCI.escapeHtml(text || 'Loading...') + '</span>';
        return loader;
    };

    /**
     * Show skeleton loading placeholders
     * @param {HTMLElement|string} container - Container element
     * @param {number} rows - Number of skeleton rows
     */
    FlowbotDCI.showSkeleton = function(container, rows) {
        if (typeof container === 'string') {
            container = document.querySelector(container);
        }
        if (!container) return;

        rows = rows || 5;
        let html = '';
        for (let i = 0; i < rows; i++) {
            html += '<div class="skeleton-row">' +
                '<div class="skeleton skeleton-cell"></div>' +
                '<div class="skeleton skeleton-cell"></div>' +
                '<div class="skeleton skeleton-cell"></div>' +
                '</div>';
        }
        container.innerHTML = html;
    };

    /**
     * Escape HTML to prevent XSS
     * @param {string} text - Text to escape
     * @returns {string}
     */
    FlowbotDCI.escapeHtml = function(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    };

    // =========================================
    // UI-004: Toast Notification System
    // =========================================

    // Toast icons by type
    var toastIcons = {
        success: '&#10003;', // Checkmark
        error: '&#10007;',   // X mark
        warning: '&#9888;',  // Warning triangle
        info: '&#8505;'      // Info icon
    };

    // Default toast titles by type
    var toastTitles = {
        success: 'Success',
        error: 'Error',
        warning: 'Warning',
        info: 'Info'
    };

    /**
     * Create toast container if it doesn't exist
     */
    function getToastContainer() {
        var container = document.querySelector('.toast-container');
        if (!container) {
            container = document.createElement('div');
            container.className = 'toast-container';
            document.body.appendChild(container);
        }
        return container;
    }

    /**
     * Show a toast notification
     * @param {Object} options - Toast options
     * @param {string} options.message - Toast message (required)
     * @param {string} options.type - Toast type: success, error, warning, info (default: info)
     * @param {string} options.title - Custom title (optional)
     * @param {number} options.duration - Duration in ms (default: 5000, 0 for permanent)
     * @param {boolean} options.showProgress - Show progress bar (default: true)
     * @param {boolean} options.closable - Show close button (default: true)
     * @returns {HTMLElement} - The toast element
     */
    FlowbotDCI.toast = function(options) {
        if (typeof options === 'string') {
            options = { message: options };
        }

        var type = options.type || 'info';
        var title = options.title || toastTitles[type];
        var message = options.message || '';
        var duration = options.duration !== undefined ? options.duration : 5000;
        var showProgress = options.showProgress !== false;
        var closable = options.closable !== false;

        var container = getToastContainer();

        // Create toast element
        var toast = document.createElement('div');
        toast.className = 'toast ' + type;

        // Build toast HTML
        var html = '<div class="toast-icon">' + toastIcons[type] + '</div>' +
            '<div class="toast-content">' +
            '<div class="toast-title">' + FlowbotDCI.escapeHtml(title) + '</div>' +
            '<div class="toast-message">' + FlowbotDCI.escapeHtml(message) + '</div>' +
            '</div>';

        if (closable) {
            html += '<button class="toast-close">&times;</button>';
        }

        if (showProgress && duration > 0) {
            html += '<div class="toast-progress" style="width: 100%;"></div>';
        }

        toast.innerHTML = html;
        container.appendChild(toast);

        // Animate in
        requestAnimationFrame(function() {
            toast.classList.add('show');
        });

        // Handle close button
        if (closable) {
            var closeBtn = toast.querySelector('.toast-close');
            closeBtn.addEventListener('click', function() {
                closeToast(toast);
            });
        }

        // Auto-dismiss with progress bar
        if (duration > 0) {
            var progressBar = toast.querySelector('.toast-progress');
            if (progressBar) {
                progressBar.style.transitionDuration = duration + 'ms';
                requestAnimationFrame(function() {
                    progressBar.style.width = '0%';
                });
            }

            setTimeout(function() {
                closeToast(toast);
            }, duration);
        }

        return toast;
    };

    /**
     * Close a toast
     * @param {HTMLElement} toast - The toast element to close
     */
    function closeToast(toast) {
        if (!toast || toast.classList.contains('hide')) return;

        toast.classList.remove('show');
        toast.classList.add('hide');

        setTimeout(function() {
            if (toast.parentNode) {
                toast.parentNode.removeChild(toast);
            }
        }, 300);
    }

    /**
     * Shorthand methods for different toast types
     */
    FlowbotDCI.toast.success = function(message, options) {
        options = options || {};
        options.message = message;
        options.type = 'success';
        return FlowbotDCI.toast(options);
    };

    FlowbotDCI.toast.error = function(message, options) {
        options = options || {};
        options.message = message;
        options.type = 'error';
        options.duration = options.duration || 8000; // Errors stay longer
        return FlowbotDCI.toast(options);
    };

    FlowbotDCI.toast.warning = function(message, options) {
        options = options || {};
        options.message = message;
        options.type = 'warning';
        return FlowbotDCI.toast(options);
    };

    FlowbotDCI.toast.info = function(message, options) {
        options = options || {};
        options.message = message;
        options.type = 'info';
        return FlowbotDCI.toast(options);
    };

    /**
     * Clear all toasts
     */
    FlowbotDCI.toast.clear = function() {
        var container = document.querySelector('.toast-container');
        if (container) {
            var toasts = container.querySelectorAll('.toast');
            toasts.forEach(function(toast) {
                closeToast(toast);
            });
        }
    };

    /**
     * Format time (seconds to HH:MM:SS)
     */
    FlowbotDCI.formatTime = function(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const secs = Math.floor(seconds % 60);

        return [
            hours.toString().padStart(2, '0'),
            minutes.toString().padStart(2, '0'),
            secs.toString().padStart(2, '0')
        ].join(':');
    };

    /**
     * Format number with thousands separator
     */
    FlowbotDCI.formatNumber = function(num) {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    };

    /**
     * Copy text to clipboard
     */
    FlowbotDCI.copyToClipboard = function(text) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(function() {
                FlowbotDCI.showAlert('Copied to clipboard!', 'success');
            });
        } else {
            // Fallback for older browsers
            const textarea = document.createElement('textarea');
            textarea.value = text;
            document.body.appendChild(textarea);
            textarea.select();
            document.execCommand('copy');
            document.body.removeChild(textarea);
            FlowbotDCI.showAlert('Copied to clipboard!', 'success');
        }
    };

    /**
     * Refresh page with delay
     */
    FlowbotDCI.refresh = function(delay) {
        delay = delay || 0;
        setTimeout(function() {
            window.location.reload();
        }, delay);
    };

    /**
     * API request helper
     */
    FlowbotDCI.api = function(endpoint, options) {
        options = options || {};
        options.headers = options.headers || {};
        options.headers['Content-Type'] = 'application/json';

        return fetch(endpoint, options)
            .then(function(response) {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            });
    };

    /**
     * Initialize terminal filters (Dashboard v2.0)
     */
    FlowbotDCI.initTerminalFilters = function() {
        const filters = document.querySelectorAll('.terminal-filter');
        const logLines = document.querySelectorAll('.terminal-body .log-line');

        if (!filters.length) return;

        filters.forEach(function(filter) {
            filter.addEventListener('click', function() {
                const type = this.dataset.filter;

                // Update active state
                filters.forEach(function(f) {
                    f.classList.remove('active');
                });
                this.classList.add('active');

                // Filter logs
                logLines.forEach(function(line) {
                    if (type === 'all' || line.dataset.type === type) {
                        line.style.display = 'flex';
                    } else {
                        line.style.display = 'none';
                    }
                });

                // Scroll to bottom after filtering
                const terminalBody = document.querySelector('.terminal-body');
                if (terminalBody) {
                    terminalBody.scrollTop = terminalBody.scrollHeight;
                }
            });
        });
    };

    /**
     * Animate counter values (Dashboard v2.0)
     */
    FlowbotDCI.animateValue = function(element, start, end, duration) {
        if (!element) return;

        const range = end - start;
        const increment = range / (duration / 16);
        let current = start;

        const timer = setInterval(function() {
            current += increment;
            if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
                element.textContent = FlowbotDCI.formatNumber(end);
                clearInterval(timer);
            } else {
                element.textContent = FlowbotDCI.formatNumber(Math.floor(current));
            }
        }, 16);
    };

    /**
     * Initialize tooltips (Dashboard v2.0)
     */
    FlowbotDCI.initTooltips = function() {
        const elements = document.querySelectorAll('[data-tooltip]');

        elements.forEach(function(el) {
            el.addEventListener('mouseenter', function(e) {
                const text = this.getAttribute('data-tooltip');
                if (!text) return;

                const tooltip = document.createElement('div');
                tooltip.className = 'tooltip-popup';
                tooltip.textContent = text;
                tooltip.style.left = (e.clientX + 15) + 'px';
                tooltip.style.top = (e.clientY + 10) + 'px';
                document.body.appendChild(tooltip);
                this._tooltip = tooltip;
            });

            el.addEventListener('mousemove', function(e) {
                if (this._tooltip) {
                    this._tooltip.style.left = (e.clientX + 15) + 'px';
                    this._tooltip.style.top = (e.clientY + 10) + 'px';
                }
            });

            el.addEventListener('mouseleave', function() {
                if (this._tooltip) {
                    this._tooltip.remove();
                    this._tooltip = null;
                }
            });
        });
    };

    /**
     * Initialize segmented progress bar interactions (Dashboard v2.0)
     */
    FlowbotDCI.initSegmentedProgress = function() {
        const segments = document.querySelectorAll('.segmented-progress .segment');

        segments.forEach(function(segment) {
            segment.addEventListener('mouseenter', function(e) {
                const tooltip = document.createElement('div');
                tooltip.className = 'tooltip-popup';
                tooltip.textContent = this.getAttribute('title') || '';
                tooltip.style.left = (e.clientX + 15) + 'px';
                tooltip.style.top = (e.clientY - 40) + 'px';
                document.body.appendChild(tooltip);
                this._tooltip = tooltip;
            });

            segment.addEventListener('mousemove', function(e) {
                if (this._tooltip) {
                    this._tooltip.style.left = (e.clientX + 15) + 'px';
                    this._tooltip.style.top = (e.clientY - 40) + 'px';
                }
            });

            segment.addEventListener('mouseleave', function() {
                if (this._tooltip) {
                    this._tooltip.remove();
                    this._tooltip = null;
                }
            });
        });
    };

    /**
     * Auto-scroll dashboard terminal (Dashboard v2.0)
     */
    FlowbotDCI.initDashboardTerminal = function() {
        const terminalBody = document.querySelector('.terminal-body');
        if (terminalBody) {
            // Scroll to bottom initially
            terminalBody.scrollTop = terminalBody.scrollHeight;

            // Watch for new content
            const observer = new MutationObserver(function() {
                terminalBody.scrollTop = terminalBody.scrollHeight;
            });

            observer.observe(terminalBody, { childList: true, subtree: true });
        }
    };

    /**
     * Initialize progress circle animation (Dashboard v2.0)
     */
    FlowbotDCI.initProgressCircle = function() {
        const circle = document.querySelector('.progress-circle');
        if (!circle) return;

        const progress = parseInt(circle.style.getPropertyValue('--progress')) || 0;
        circle.style.setProperty('--progress', '0');

        setTimeout(function() {
            circle.style.setProperty('--progress', progress);
        }, 100);
    };

    /**
     * Initialize dashboard components (Dashboard v2.0)
     */
    FlowbotDCI.initDashboard = function() {
        this.initTerminalFilters();
        this.initTooltips();
        this.initSegmentedProgress();
        this.initDashboardTerminal();
        this.initProgressCircle();
        console.log('FlowbotDCI Dashboard v2.0 initialized');
    };

    // =========================================
    // DOMAIN TABLE FUNCTIONALITY (domains.php)
    // =========================================

    /**
     * Initialize domain table with sorting and filtering
     */
    FlowbotDCI.initDomainTable = function() {
        const table = document.getElementById('domainTable');
        const searchInput = document.getElementById('domainSearch');

        if (!table) return;

        // Initialize sorting
        const headers = table.querySelectorAll('th.sortable');
        let currentSort = { column: 'total', direction: 'desc' };

        headers.forEach(function(header) {
            header.addEventListener('click', function() {
                const column = this.dataset.sort;
                const direction = (currentSort.column === column && currentSort.direction === 'desc') ? 'asc' : 'desc';

                // Update sort indicators
                headers.forEach(function(h) {
                    h.classList.remove('sort-asc', 'sort-desc');
                });
                this.classList.add('sort-' + direction);

                // Sort table
                FlowbotDCI.sortTable(table, column, direction);
                currentSort = { column: column, direction: direction };
            });
        });

        // Initialize search
        if (searchInput) {
            searchInput.addEventListener('input', FlowbotDCI.debounce(function() {
                FlowbotDCI.filterDomainTable(table, this.value);
            }, 300));
        }

        // Add row click interaction
        const rows = table.querySelectorAll('tbody tr.domain-row');
        rows.forEach(function(row) {
            row.addEventListener('click', function(e) {
                if (e.target.tagName === 'A') return; // Don't interfere with action links
                const domain = this.dataset.domain;
                if (domain) {
                    // Highlight row
                    rows.forEach(function(r) { r.classList.remove('selected'); });
                    this.classList.add('selected');
                }
            });
        });

        console.log('Domain table initialized');
    };

    /**
     * Sort table by column
     */
    FlowbotDCI.sortTable = function(table, column, direction) {
        const tbody = table.querySelector('tbody');
        const rows = Array.from(tbody.querySelectorAll('tr.domain-row'));

        rows.sort(function(a, b) {
            let aVal, bVal;

            if (column === 'domain') {
                aVal = a.dataset.domain || '';
                bVal = b.dataset.domain || '';
                return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
            } else {
                aVal = parseFloat(a.dataset[column]) || 0;
                bVal = parseFloat(b.dataset[column]) || 0;
                return direction === 'asc' ? aVal - bVal : bVal - aVal;
            }
        });

        // Re-append sorted rows
        rows.forEach(function(row) {
            tbody.appendChild(row);
        });
    };

    /**
     * Filter domain table by search query
     */
    FlowbotDCI.filterDomainTable = function(table, query) {
        const rows = table.querySelectorAll('tbody tr.domain-row');
        const lowerQuery = query.toLowerCase().trim();

        rows.forEach(function(row) {
            const domain = (row.dataset.domain || '').toLowerCase();
            if (!lowerQuery || domain.includes(lowerQuery)) {
                row.style.display = '';
                // Highlight matching text
                const domainCell = row.querySelector('.domain-name .domain-text');
                if (domainCell && lowerQuery) {
                    domainCell.innerHTML = FlowbotDCI.highlightText(row.dataset.domain, query);
                } else if (domainCell) {
                    domainCell.textContent = row.dataset.domain;
                }
            } else {
                row.style.display = 'none';
            }
        });

        // Update visible count
        const visibleCount = table.querySelectorAll('tbody tr.domain-row:not([style*="display: none"])').length;
        const countSpan = document.querySelector('.table-count');
        if (countSpan) {
            const totalCount = rows.length;
            countSpan.textContent = lowerQuery ? visibleCount + ' of ' + totalCount + ' domains' : totalCount + ' domains';
        }
    };

    // =========================================
    // LOGS PAGE FUNCTIONALITY (logs.php)
    // =========================================

    /**
     * Initialize logs page with filtering and interactions
     */
    FlowbotDCI.initLogsPage = function() {
        const filterForm = document.getElementById('logsFilterForm');
        const searchInput = document.getElementById('filterSearch');
        const quickFilters = document.querySelectorAll('.quick-filter');
        const table = document.getElementById('logsTable');

        // Auto-submit on select change
        if (filterForm) {
            const selects = filterForm.querySelectorAll('select');
            selects.forEach(function(select) {
                select.addEventListener('change', function() {
                    filterForm.submit();
                });
            });
        }

        // Debounced search
        if (searchInput) {
            let searchTimeout;
            searchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                const input = this;
                searchTimeout = setTimeout(function() {
                    if (input.value.length >= 3 || input.value.length === 0) {
                        filterForm.submit();
                    }
                }, 500);
            });

            // Submit on Enter
            searchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    filterForm.submit();
                }
            });
        }

        // Quick filters highlight
        quickFilters.forEach(function(filter) {
            filter.addEventListener('click', function(e) {
                quickFilters.forEach(function(f) { f.classList.remove('active'); });
                this.classList.add('active');
            });
        });

        // Row click to expand details
        if (table) {
            const rows = table.querySelectorAll('tbody tr.log-row');
            rows.forEach(function(row) {
                row.addEventListener('click', function() {
                    // Toggle expanded state
                    rows.forEach(function(r) { r.classList.remove('expanded'); });
                    this.classList.toggle('expanded');

                    // Show full URL and message in console for debugging
                    const url = this.querySelector('.log-url')?.getAttribute('title');
                    const message = this.querySelector('.log-message')?.getAttribute('title');
                    if (url || message) {
                        console.log('Log Entry:', { url: url, message: message });
                    }
                });
            });
        }

        console.log('Logs page initialized');
    };

    // =========================================
    // EXPORT FUNCTIONALITY
    // =========================================

    /**
     * Export data to CSV
     */
    FlowbotDCI.exportToCSV = function(data, filename) {
        if (!data || !data.length) {
            FlowbotDCI.showAlert('No data to export', 'warning');
            return;
        }

        const headers = Object.keys(data[0]);
        const csvRows = [headers.join(',')];

        data.forEach(function(row) {
            const values = headers.map(function(header) {
                let val = row[header] || '';
                // Escape quotes and wrap in quotes if contains comma
                val = String(val).replace(/"/g, '""');
                if (val.includes(',') || val.includes('"') || val.includes('\n')) {
                    val = '"' + val + '"';
                }
                return val;
            });
            csvRows.push(values.join(','));
        });

        FlowbotDCI.downloadFile(csvRows.join('\n'), filename + '.csv', 'text/csv');
    };

    /**
     * Export data to JSON
     */
    FlowbotDCI.exportToJSON = function(data, filename) {
        if (!data) {
            FlowbotDCI.showAlert('No data to export', 'warning');
            return;
        }

        const jsonStr = JSON.stringify(data, null, 2);
        FlowbotDCI.downloadFile(jsonStr, filename + '.json', 'application/json');
    };

    /**
     * Download file helper
     */
    FlowbotDCI.downloadFile = function(content, filename, mimeType) {
        const blob = new Blob([content], { type: mimeType + ';charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);

        FlowbotDCI.showAlert('Downloaded: ' + filename, 'success');
    };

    // =========================================
    // AUTO-REFRESH FUNCTIONALITY
    // =========================================

    FlowbotDCI.autoRefreshInterval = null;
    FlowbotDCI.autoRefreshEnabled = false;

    /**
     * Start auto-refresh while processing
     */
    FlowbotDCI.startAutoRefresh = function(seconds) {
        seconds = seconds || 5;

        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
        }

        this.autoRefreshEnabled = true;

        this.autoRefreshInterval = setInterval(function() {
            if (!FlowbotDCI.autoRefreshEnabled) return;

            const processId = window.processId;
            if (!processId) return;

            // Fetch progress data
            fetch('?page=api&action=progress&process_id=' + encodeURIComponent(processId))
                .then(function(response) { return response.json(); })
                .then(function(data) {
                    FlowbotDCI.updateDashboardData(data);

                    // Check if processing is complete
                    const remainingLinks = FlowbotDCI.calculateRemainingLinks(data);
                    if (remainingLinks === 0) {
                        FlowbotDCI.stopAutoRefresh();
                        FlowbotDCI.showAlert('Processing complete!', 'success');
                    }
                })
                .catch(function(error) {
                    console.error('Auto-refresh error:', error);
                });
        }, seconds * 1000);

        // Add visual indicator
        const indicator = document.querySelector('.status-indicator');
        if (indicator) {
            indicator.classList.add('refreshing');
        }

        console.log('Auto-refresh started (' + seconds + 's interval)');
    };

    /**
     * Stop auto-refresh
     */
    FlowbotDCI.stopAutoRefresh = function() {
        this.autoRefreshEnabled = false;

        if (this.autoRefreshInterval) {
            clearInterval(this.autoRefreshInterval);
            this.autoRefreshInterval = null;
        }

        // Remove visual indicator
        const indicator = document.querySelector('.status-indicator');
        if (indicator) {
            indicator.classList.remove('refreshing');
        }

        console.log('Auto-refresh stopped');
    };

    /**
     * Calculate remaining links from data
     */
    FlowbotDCI.calculateRemainingLinks = function(data) {
        let remaining = 0;
        const queues = data.phase_queues || {};
        for (var key in queues) {
            if (queues.hasOwnProperty(key)) {
                remaining += (queues[key] || []).length;
            }
        }
        return remaining;
    };

    /**
     * Update dashboard data without full page reload
     */
    FlowbotDCI.updateDashboardData = function(data) {
        // Update progress percentage
        const total = Math.max(data.total_links || 1, 1);
        const processed = (data.processed_links || 0) + (data.ignored_links || 0) + (data.error_links || 0);
        const percent = Math.round((processed / total) * 100 * 10) / 10;

        // Update main progress bar
        const progressFill = document.querySelector('.progress-bar-fill');
        if (progressFill) {
            progressFill.style.width = percent + '%';
        }

        // Update progress text
        const progressText = document.querySelector('.progress-percentage');
        if (progressText) {
            progressText.textContent = percent + '%';
        }

        // Update nav progress mini bar
        const navProgressFill = document.querySelector('.nav-progress-fill');
        if (navProgressFill) {
            navProgressFill.style.width = percent + '%';
        }

        // Update KPI values
        FlowbotDCI.updateKPIValue('.kpi-value.processed', data.processed_links || 0);
        FlowbotDCI.updateKPIValue('.kpi-value.ignored', data.ignored_links || 0);
        FlowbotDCI.updateKPIValue('.kpi-value.errors', data.error_links || 0);

        // Update phase indicator
        const currentPhase = (data.phase_index || 0) + 1;
        const phaseIndicator = document.querySelector('.current-phase-number');
        if (phaseIndicator) {
            phaseIndicator.textContent = currentPhase;
        }

        // Update elapsed time
        if (data.start_time) {
            const elapsed = Math.floor((Date.now() / 1000) - new Date(data.start_time).getTime() / 1000);
            const elapsedEl = document.querySelector('.elapsed-time');
            if (elapsedEl) {
                elapsedEl.textContent = FlowbotDCI.formatTime(elapsed);
            }
        }
    };

    /**
     * Update a KPI value with animation
     */
    FlowbotDCI.updateKPIValue = function(selector, value) {
        const element = document.querySelector(selector);
        if (element) {
            const currentValue = parseInt(element.textContent.replace(/,/g, '')) || 0;
            if (currentValue !== value) {
                FlowbotDCI.animateValue(element, currentValue, value, 300);
            }
        }
    };

    // =========================================
    // UTILITY FUNCTIONS
    // =========================================

    /**
     * Debounce function
     */
    FlowbotDCI.debounce = function(func, wait) {
        let timeout;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                func.apply(context, args);
            }, wait);
        };
    };

    /**
     * Escape HTML special characters to prevent XSS
     * SEC-004: Security fix for XSS vulnerability
     */
    FlowbotDCI.escapeHtml = function(str) {
        if (!str) return '';
        const htmlEntities = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        };
        return String(str).replace(/[&<>"']/g, function(char) {
            return htmlEntities[char];
        });
    };

    /**
     * Highlight text matching query (XSS-safe)
     * SEC-004: Escapes HTML before highlighting to prevent XSS
     */
    FlowbotDCI.highlightText = function(text, query) {
        if (!query || !text) return FlowbotDCI.escapeHtml(text);
        // First escape the text to prevent XSS
        const escapedText = FlowbotDCI.escapeHtml(text);
        // Then highlight matches (query is also escaped for regex safety)
        const escapedQuery = FlowbotDCI.escapeHtml(query);
        const regex = new RegExp('(' + escapedQuery.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
        return escapedText.replace(regex, '<mark>$1</mark>');
    };

    /**
     * Throttle function
     */
    FlowbotDCI.throttle = function(func, limit) {
        let inThrottle;
        return function() {
            const context = this;
            const args = arguments;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(function() {
                    inThrottle = false;
                }, limit);
            }
        };
    };

    /**
     * Check if processing is active (for auto-refresh)
     * PERF-001: Fixed to use window.isComplete flag
     */
    FlowbotDCI.checkProcessingStatus = function() {
        // Check if we're on dashboard page and processing is not complete
        if (typeof window.isComplete !== 'undefined' && window.isComplete === false) {
            // Start auto-refresh if processing is active
            FlowbotDCI.startAutoRefresh(5);
            console.log('Auto-refresh enabled: processing in progress');
        } else if (typeof window.isComplete !== 'undefined' && window.isComplete === true) {
            console.log('Processing complete: auto-refresh disabled');
        }
    };

    // =========================================
    // NAVIGATION FUNCTIONALITY
    // =========================================

    /**
     * Initialize navigation
     */
    FlowbotDCI.initNavigation = function() {
        const navLinks = document.querySelectorAll('.nav-link');

        navLinks.forEach(function(link) {
            link.addEventListener('click', function() {
                // Add loading state
                navLinks.forEach(function(l) { l.classList.remove('active'); });
                this.classList.add('active', 'loading');
            });
        });
    };

    // =========================================
    // INITIALIZATION
    // =========================================

    // Initialize on DOM ready
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            FlowbotDCI.init();
            FlowbotDCI.initDashboard();
            FlowbotDCI.initNavigation();
            FlowbotDCI.checkProcessingStatus();
        });
    } else {
        FlowbotDCI.init();
        FlowbotDCI.initDashboard();
        FlowbotDCI.initNavigation();
        FlowbotDCI.checkProcessingStatus();
    }

})();
