(function($) {
    'use strict';

    /**
     * Unified LinkCentral Import Handler
     * Handles all import types (CSV, JSON, ThirstyAffiliates, Pretty Links) with minimal code
     */
    class LinkCentralImport {
        constructor() {
            this.__ = wp.i18n.__;
            this.currentStep = 1;
            this.selectedFile = null;
            this.fileType = null;
            this.csvData = null;
            this.jsonData = null;
            this.importSettings = {};
            this.ajaxAction = linkcentral_import.ajax_action || 'linkcentral_import_csv';
            
            this.init();
        }

        init() {
            this.bindEvents();
        }

        bindEvents() {
            // File imports (CSV/JSON)
            $('#linkcentral-csv-file').on('change', (e) => this.handleFileSelect(e));
            $('#linkcentral-analyze-file').on('click', () => this.analyzeFile());
            $('#linkcentral-select-file').on('click', () => $('#linkcentral-csv-file').click());
            $('#linkcentral-start-import-process').on('click', () => this.startImport('csv'));
            $('#linkcentral-start-json-import').on('click', () => this.startImport('json'));
            
            // Form imports (ThirstyAffiliates)
            $('#linkcentral-import-form').on('submit', (e) => this.handleFormImport(e));
            
            // Navigation
            $('#linkcentral-back-to-upload, #linkcentral-json-back-to-upload').on('click', () => this.goToStep(1));
            
            // Settings
            $('#linkcentral-duplicate-handling, #linkcentral-create-categories, #linkcentral-force-prefix').on('change', () => this.updateImportSettings());
            $(document).on('change', 'input[name="linkcentral-json-import-mode"]', () => this.handleImportModeChange());
        }

        // === FILE HANDLING ===
        handleFileSelect(e) {
            const file = e.target.files[0];
            if (!file) return;

            const fileName = file.name.toLowerCase();
            const isCSV = fileName.endsWith('.csv');
            const isJSON = fileName.endsWith('.json');
            
            if (!isCSV && !isJSON) {
                alert('Please select a CSV or JSON file.');
                return;
            }

            // Show file info
            $('#linkcentral-file-name').text(file.name);
            $('#linkcentral-file-size').text(this.formatFileSize(file.size));
            $('#linkcentral-file-info').show();
            $('#linkcentral-analyze-file').prop('disabled', false);
            
            this.selectedFile = file;
            this.fileType = isCSV ? 'csv' : 'json';
        }

        analyzeFile() {
            if (!this.selectedFile) return;

            $('#linkcentral-analyze-file').prop('disabled', true).text('Analyzing...');

            const reader = new FileReader();
            reader.onload = (e) => {
                try {
                    const content = e.target.result;
                    
                    if (this.fileType === 'json') {
                        this.jsonData = this.parseJSON(content);
                        if (this.jsonData.error) {
                            alert('Error: ' + this.jsonData.error);
                            return;
                        }
                        this.goToStep(2);
                        this.handleImportModeChange();
                    } else {
                        this.csvData = this.parseCSV(content);
                        if (this.csvData.error) {
                            alert('Error: ' + this.csvData.error);
                            return;
                        }
                        if (this.csvData.headers.length !== 9) {
                            alert('CSV must have exactly 9 columns: Title, Slug, Destination URL, Category, Nofollow, Sponsored, Parameter Forwarding, Redirect Type, Note');
                            return;
                        }
                        this.goToStep(2);
                        $('#linkcentral-total-rows').text(this.csvData.total_rows);
                        $('#linkcentral-start-import-process').prop('disabled', false);
                    }
                } catch (error) {
                    alert('Error analyzing file: ' + error.message);
                } finally {
                    $('#linkcentral-analyze-file').prop('disabled', false).text('Continue to Settings');
                }
            };
            
            reader.readAsText(this.selectedFile);
        }

        parseJSON(content) {
            try {
                const data = JSON.parse(content);
                if (data.export_info?.export_type === 'linkcentral_full' && data.links) {
                    return { isLinkCentralExport: true, totalLinks: data.links.length, data: data };
                }
                return { error: 'Not a valid LinkCentral export.' };
            } catch (error) {
                return { error: 'Invalid JSON: ' + error.message };
            }
        }

        parseCSV(content) {
            const lines = content.split('\n').filter(line => line.trim());
            if (lines.length === 0) return { error: 'Empty CSV file.' };

            const delimiter = this.detectDelimiter(lines[0]);
            const headers = this.parseCSVLine(lines[0], delimiter);
            
            return {
                headers: headers,
                total_rows: lines.length - 1,
                delimiter: delimiter
            };
        }

        detectDelimiter(line) {
            const delimiters = [',', ';', '\t', '|'];
            let maxCount = 0, bestDelimiter = ',';
            
            delimiters.forEach(d => {
                const count = (line.match(new RegExp('\\' + d, 'g')) || []).length;
                if (count > maxCount) {
                    maxCount = count;
                    bestDelimiter = d;
                }
            });
            
            return bestDelimiter;
        }

        parseCSVLine(line, delimiter) {
            const result = [];
            let current = '', inQuotes = false;
            
            for (let i = 0; i < line.length; i++) {
                const char = line[i];
                if (char === '"') {
                    inQuotes = !inQuotes;
                } else if (char === delimiter && !inQuotes) {
                    result.push(current.trim());
                    current = '';
                } else {
                    current += char;
                }
            }
            
            result.push(current.trim());
            return result;
        }

        // === IMPORT EXECUTION ===
        startImport(type) {
            this.updateImportSettings();
            this.goToStep(3);
            this.clearMessages();
            this.updateProgress(0);
            this.addMessage('Starting import...', 'info');

            const formData = new FormData();
            
            if (type === 'json') {
                const importMode = $('input[name="linkcentral-json-import-mode"]:checked').val();
                const duplicateAction = importMode === 'restore' ? 'overwrite' : $('#linkcentral-json-duplicate-handling').val();
                
                formData.append('action', 'linkcentral_import_json');
                formData.append('json_file', this.selectedFile);
                formData.append('duplicate_action', duplicateAction);
                formData.append('import_mode', importMode);
            } else {
                formData.append('action', 'linkcentral_import_csv');
                formData.append('csv_file', this.selectedFile);
                formData.append('import_settings', JSON.stringify(this.importSettings));
            }
            
            formData.append('nonce', linkcentral_import.nonce);
            this.sendRequest(formData, true);
        }

        handleFormImport(e) {
            e.preventDefault();
            
            const $form = $('#linkcentral-import-form');
            const $progress = $('#linkcentral-import-progress');
            
            $form.hide();
            $progress.show();
            $('#linkcentral-start-import').prop('disabled', true);
            
            this.clearMessages();
            this.updateProgress(10);
            this.addMessage('Starting import...', 'info');

            // Check for file input
            const fileInput = $form.find('input[type="file"]')[0];
            const formData = new FormData();
            
            formData.append('action', this.ajaxAction);
            formData.append('nonce', $('#linkcentral_import_nonce').val());
            formData.append('duplicate_handling', $('#linkcentral-duplicate-handling').val());

            // Add file if present
            if (fileInput?.files[0]) {
                formData.append(this.ajaxAction.includes('csv') ? 'csv_file' : 'json_file', fileInput.files[0]);
            }

            // Add form fields
            $form.find('input[type="checkbox"]').each(function() {
                const $input = $(this);
                const name = $input.attr('name');
                if (name && name !== 'linkcentral_import_nonce') {
                    formData.append(name, $input.is(':checked') ? 'true' : 'false');
                }
            });

            this.sendRequest(formData, false);
        }

        sendRequest(formData, isFileImport) {
            this.updateProgress(50);
            this.addMessage('Processing data...', 'info');

            $.ajax({
                url: linkcentral_import.ajax_url,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (response) => {
                    this.updateProgress(100);
                    this.addMessage('Import completed! One moment please...', 'success');
                    
                    if (response.success) {
                        this.showResults(response.data, isFileImport);
                        this.handlePostImport(response.data);
                    } else {
                        this.showError(response.data);
                    }
                },
                error: () => {
                    this.showError('Network error occurred.');
                }
            });
        }

        // === UI UPDATES ===
        updateProgress(percentage) {
            $('.linkcentral-progress-fill').css('width', percentage + '%');
            $('#linkcentral-progress-percentage').text(percentage);
        }

        addMessage(message, type = 'info') {
            const $detailedLog = $('#linkcentral-processing-messages');
            const $simpleStatus = $('.linkcentral-progress-status');
            
            if ($detailedLog.length) {
                const $msg = $(`<div class="linkcentral-processing-message linkcentral-message-${type}">${this.escapeHtml(message)}</div>`);
                $detailedLog.append($msg);
                $detailedLog.scrollTop($detailedLog[0].scrollHeight);
            }
            
            if ($simpleStatus.length) {
                $simpleStatus.text(message);
            }
        }

        clearMessages() {
            $('#linkcentral-error-details').hide();
            $('#linkcentral-error-list').empty();
            $('#linkcentral-processing-messages').empty();
        }

        showResults(result, isFileImport) {
            if (isFileImport) {
                this.goToStep(4);
                
                // Update counts
                $('#linkcentral-success-count').text(result.success || 0);
                $('#linkcentral-skipped-count').text(result.skipped || 0);
                $('#linkcentral-error-count').text(result.errors || 0);

                // Add additional info
                const $summary = $('.linkcentral-import-confirmation-summary ul');
                const extras = [];
                
                if (result.analytics_imported > 0) extras.push(`<li>• ${result.analytics_imported} analytics records imported</li>`);
                if (result.keywords_imported > 0) extras.push(`<li>• ${result.keywords_imported} keywords imported</li>`);
                if (result.categories_imported > 0) extras.push(`<li>• ${result.categories_imported} categories imported</li>`);
                if (result.stats_imported > 0) extras.push(`<li>• ${result.stats_imported} click records imported</li>`);
                
                if (extras.length > 0) $summary.append(extras.join(''));
                
                if (result.errors > 0 && result.error_details) {
                    this.showErrorDetails(result.error_details);
                }
            } else {
                // Form import results
                setTimeout(() => {
                    $('#linkcentral-import-progress').hide();
                    
                    let html = '<h4>Import Summary</h4><ul>';
                    html += `<li><strong>Links imported:</strong> ${result.success || 0}</li>`;
                    if (result.skipped > 0) html += `<li><strong>Links skipped:</strong> ${result.skipped}</li>`;
                    if (result.errors > 0) html += `<li><strong>Errors:</strong> ${result.errors}</li>`;
                    if (result.categories_imported > 0) html += `<li><strong>Categories imported:</strong> ${result.categories_imported}</li>`;
                    if (result.stats_imported > 0) html += `<li><strong>Click records imported:</strong> ${result.stats_imported}</li>`;
                    html += '</ul>';
                    
                    $('.linkcentral-import-confirmation-summary').html(html);
                    $('#linkcentral-import-results').show();
                }, 1000);
            }
        }

        showError(message) {
            this.addMessage('Error: ' + message, 'error');
            
            if ($('#linkcentral-import-form').length) {
                // Form import error
                $('#linkcentral-import-progress').hide();
                $('#linkcentral-import-form').show();
                $('#linkcentral-start-import').prop('disabled', false);
            } else {
                // File import error
                this.showResults({ success: 0, skipped: 0, errors: 1, error_details: [{ link: 'Unknown', error: message }] }, true);
            }
        }

        showErrorDetails(errors) {
            const $list = $('#linkcentral-error-list');
            $list.empty();
            
            errors.forEach(error => {
                const html = error.row ? 
                    `<div><strong>Row ${error.row}:</strong> ${this.escapeHtml(error.error)}</div>` :
                    `<div><strong>Link:</strong> ${error.link}<br><strong>Error:</strong> ${error.error}</div>`;
                $list.append(`<div style="margin-bottom: 8px; padding: 5px 0; border-bottom: 1px solid #eee;">${html}</div>`);
            });
            
            $('#linkcentral-error-details').show();
        }

        handlePostImport(result) {
            if (this.ajaxAction === 'linkcentral_import_thirstyaffiliates') {
                $('.linkcentral-import-confirmation-summary').after(`
                    <div class="linkcentral-import-confirmation-success">
                        <h3>✅ Migration Successfully Completed!</h3>
                        <p>ThirstyAffiliates can now be safely disabled.</p>
                        <button type="button" id="linkcentral-disable-ta-plugin" class="button button-primary">
                            Disable ThirstyAffiliates Plugin
                        </button>
                    </div>
                `);

                $('#linkcentral-disable-ta-plugin').on('click', function() {
                    const $btn = $(this);
                    $btn.prop('disabled', true).text('Disabling...');

                    $.post(linkcentral_import.ajax_url, {
                        action: 'linkcentral_disable_thirstyaffiliates',
                        nonce: $('#linkcentral_import_nonce').val()
                    }).done(function(response) {
                        $btn.replaceWith(response.success ?
                            '<span style="color: green;">✅ Plugin disabled</span>' :
                            '<span style="color: red;">❌ ' + response.data + '</span>'
                        );
                    }).fail(function() {
                        $btn.prop('disabled', false).text('Disable Plugin');
                    });
                });
            } else if (this.ajaxAction === 'linkcentral_import_prettylinks') {
                $('.linkcentral-import-confirmation-summary').after(`
                    <div class="linkcentral-import-confirmation-success">
                        <h3>✅ Migration Successfully Completed!</h3>
                        <p>Pretty Links can now be safely disabled.</p>
                        <button type="button" id="linkcentral-disable-pl-plugin" class="button button-primary">
                            Disable Pretty Links Plugin
                        </button>
                    </div>
                `);

                $('#linkcentral-disable-pl-plugin').on('click', function() {
                    const $btn = $(this);
                    $btn.prop('disabled', true).text('Disabling...');

                    $.post(linkcentral_import.ajax_url, {
                        action: 'linkcentral_disable_prettylinks',
                        nonce: $('#linkcentral_import_nonce').val()
                    }).done(function(response) {
                        $btn.replaceWith(response.success ?
                            '<span style="color: green;">✅ Plugin disabled</span>' :
                            '<span style="color: red;">❌ ' + response.data + '</span>'
                        );
                    }).fail(function() {
                        $btn.prop('disabled', false).text('Disable Plugin');
                    });
                });
            }
        }

        // === SETTINGS & NAVIGATION ===
        updateImportSettings() {
            this.importSettings = {
                duplicate_handling: $('#linkcentral-duplicate-handling').val(),
                create_categories: $('#linkcentral-create-categories').is(':checked'),
                force_prefix: $('#linkcentral-force-prefix').is(':checked')
            };
        }

        handleImportModeChange() {
            const mode = $('input[name="linkcentral-json-import-mode"]:checked').val();
            
            if (mode === 'restore') {
                $('#linkcentral-restore-warning-content').show();
                $('#linkcentral-migration-options').hide();
            } else {
                $('#linkcentral-restore-warning-content').hide();
                $('#linkcentral-migration-options').show();
            }
            
            $('#linkcentral-start-json-import').prop('disabled', false);
        }

        goToStep(step) {
            $('.linkcentral-import-step').hide();
            
            if (step === 2 && $('#linkcentral-import-step-settings').length > 0) {
                $('#linkcentral-import-step-settings').show();
            } else {
                const stepIds = ['', 'upload', 'settings', 'processing', 'results'];
                $(`#linkcentral-import-step-${stepIds[step] || 'results'}`).show();
            }
            
            this.currentStep = step;
        }

        // === UTILITIES ===
        formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    }

    // Initialize on document ready
    $(document).ready(() => {
        if (typeof linkcentral_import !== 'undefined') {
            new LinkCentralImport();
        }
    });

})(jQuery);