<?php
/**
 * Settings > Import Data Tab
 *
 * @package Freelance_Studio
 * @since 8.3.0
 */

if (!defined('ABSPATH')) {
    exit;
}
?>

<div class="fs-settings-section">
    <h2><?php esc_html_e('Import Data', 'freelance-studio'); ?></h2>
    <p class="description"><?php esc_html_e('Import data from CSV files exported from Wave, FreshBooks, QuickBooks, or other tools. Select the type of data you are importing, then upload your CSV file.', 'freelance-studio'); ?></p>
</div>

<!-- Import Type Selector -->
<div class="fs-settings-section" id="fs-import-type-section">
    <h3><?php esc_html_e('What are you importing?', 'freelance-studio'); ?></h3>
    <div class="fs-import-type-cards">
        <button type="button" class="fs-import-type-card active" data-type="invoices">
            <span class="dashicons dashicons-media-spreadsheet"></span>
            <strong><?php esc_html_e('Invoices', 'freelance-studio'); ?></strong>
            <span><?php esc_html_e('Clients, projects & invoices', 'freelance-studio'); ?></span>
        </button>
        <button type="button" class="fs-import-type-card" data-type="expenses">
            <span class="dashicons dashicons-money-alt"></span>
            <strong><?php esc_html_e('Expenses', 'freelance-studio'); ?></strong>
            <span><?php esc_html_e('Business expenses & receipts', 'freelance-studio'); ?></span>
        </button>
    </div>
</div>

<!-- Step 1: Upload -->
<div class="fs-settings-section" id="fs-import-step-upload">
    <h3><?php esc_html_e('Step 1: Upload CSV File', 'freelance-studio'); ?></h3>
    <p class="description" id="fs-import-upload-desc"><?php esc_html_e('Upload a CSV file containing invoice data. The file should include columns for client name, project name, invoice number, dates, and amounts.', 'freelance-studio'); ?></p>
    
    <div class="fs-import-dropzone" id="fs-import-dropzone">
        <div class="fs-import-dropzone-content">
            <span class="dashicons dashicons-upload"></span>
            <p><?php esc_html_e('Drag & drop your CSV file here', 'freelance-studio'); ?></p>
            <p class="fs-import-dropzone-or"><?php esc_html_e('or', 'freelance-studio'); ?></p>
            <label class="fs-btn fs-btn-secondary">
                <?php esc_html_e('Browse Files', 'freelance-studio'); ?>
                <input type="file" accept=".csv" id="fs-import-file" style="display: none;">
            </label>
        </div>
        <div class="fs-import-dropzone-selected" style="display: none;">
            <span class="dashicons dashicons-media-spreadsheet"></span>
            <span class="fs-import-filename"></span>
            <button type="button" class="fs-btn-link fs-import-remove-file"><?php esc_html_e('Remove', 'freelance-studio'); ?></button>
        </div>
    </div>

    <div class="fs-import-supported-columns" style="margin-top: 16px;">
        <p class="description"><strong><?php esc_html_e('Supported CSV columns:', 'freelance-studio'); ?></strong></p>
        <p class="description" id="fs-import-columns-help"><?php esc_html_e('Client Name, Project Name, Number (invoice #), Created Date, Due Date, Issued Date, Sent Date, Paid Date, Total, Tax Total, Discount Total, Payment Total, Notes, Currency', 'freelance-studio'); ?></p>
    </div>
</div>

<!-- Step 2: Column Mapping (shown after upload) -->
<div class="fs-settings-section" id="fs-import-step-mapping" style="display: none;">
    <h3><?php esc_html_e('Step 2: Column Mapping', 'freelance-studio'); ?></h3>
    <p class="description"><?php esc_html_e('We detected the following columns in your CSV. Verify the mappings are correct.', 'freelance-studio'); ?></p>
    
    <table class="widefat fs-import-mapping-table" id="fs-import-mapping-table">
        <thead>
            <tr>
                <th><?php esc_html_e('CSV Column', 'freelance-studio'); ?></th>
                <th><?php esc_html_e('Maps To', 'freelance-studio'); ?></th>
                <th><?php esc_html_e('Sample Data', 'freelance-studio'); ?></th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    
    <div style="margin-top: 16px;">
        <label style="display: flex; align-items: center; gap: 8px;">
            <input type="checkbox" id="fs-import-skip-existing" checked>
            <?php esc_html_e('Skip invoices with duplicate invoice numbers', 'freelance-studio'); ?>
        </label>
    </div>
    <div style="margin-top: 8px;">
        <label style="display: flex; align-items: center; gap: 8px;">
            <input type="checkbox" id="fs-import-projects-completed" checked>
            <?php esc_html_e('Mark all imported projects as "Completed"', 'freelance-studio'); ?>
        </label>
    </div>
    
    <div style="margin-top: 20px; display: flex; gap: 10px;">
        <button type="button" class="fs-btn fs-btn-secondary" id="fs-import-back-to-upload"><?php esc_html_e('Back', 'freelance-studio'); ?></button>
        <button type="button" class="fs-btn fs-btn-primary" id="fs-import-preview-btn"><?php esc_html_e('Preview Import', 'freelance-studio'); ?></button>
    </div>
</div>

<!-- Step 3: Preview (shown after mapping) -->
<div class="fs-settings-section" id="fs-import-step-preview" style="display: none;">
    <h3><?php esc_html_e('Step 3: Preview', 'freelance-studio'); ?></h3>
    <p class="description"><?php esc_html_e('Review what will be imported before committing.', 'freelance-studio'); ?></p>
    
    <div class="fs-import-preview-stats">
        <div class="fs-import-stat-card">
            <span class="fs-import-stat-number" id="fs-import-stat-clients">0</span>
            <span class="fs-import-stat-label"><?php esc_html_e('New Clients', 'freelance-studio'); ?></span>
        </div>
        <div class="fs-import-stat-card">
            <span class="fs-import-stat-number" id="fs-import-stat-existing-clients">0</span>
            <span class="fs-import-stat-label"><?php esc_html_e('Existing Clients', 'freelance-studio'); ?></span>
        </div>
        <div class="fs-import-stat-card">
            <span class="fs-import-stat-number" id="fs-import-stat-projects">0</span>
            <span class="fs-import-stat-label"><?php esc_html_e('New Projects', 'freelance-studio'); ?></span>
        </div>
        <div class="fs-import-stat-card">
            <span class="fs-import-stat-number" id="fs-import-stat-invoices">0</span>
            <span class="fs-import-stat-label"><?php esc_html_e('Invoices', 'freelance-studio'); ?></span>
        </div>
        <div class="fs-import-stat-card">
            <span class="fs-import-stat-number" id="fs-import-stat-skipped">0</span>
            <span class="fs-import-stat-label"><?php esc_html_e('Skipped (Duplicate)', 'freelance-studio'); ?></span>
        </div>
        <div class="fs-import-stat-card fs-import-stat-total">
            <span class="fs-import-stat-number" id="fs-import-stat-total">$0</span>
            <span class="fs-import-stat-label"><?php esc_html_e('Total Revenue', 'freelance-studio'); ?></span>
        </div>
    </div>
    
    <!-- Preview table -->
    <div class="fs-import-preview-table-wrap" style="margin-top: 20px; max-height: 400px; overflow-y: auto;">
        <table class="widefat" id="fs-import-preview-table">
            <thead>
                <tr>
                    <th><?php esc_html_e('#', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Client', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Project', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Invoice #', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Total', 'freelance-studio'); ?></th>
                    <th><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    
    <div style="margin-top: 20px; display: flex; gap: 10px;">
        <button type="button" class="fs-btn fs-btn-secondary" id="fs-import-back-to-mapping"><?php esc_html_e('Back', 'freelance-studio'); ?></button>
        <button type="button" class="fs-btn fs-btn-primary" id="fs-import-run-btn"><?php esc_html_e('Run Import', 'freelance-studio'); ?></button>
    </div>
</div>

<!-- Step 4: Progress (shown during import) -->
<div class="fs-settings-section" id="fs-import-step-progress" style="display: none;">
    <h3><?php esc_html_e('Importing...', 'freelance-studio'); ?></h3>
    
    <div class="fs-import-progress-wrap">
        <div class="fs-import-progress-bar">
            <div class="fs-import-progress-fill" id="fs-import-progress-fill" style="width: 0%"></div>
        </div>
        <p class="fs-import-progress-text" id="fs-import-progress-text"><?php esc_html_e('Starting import...', 'freelance-studio'); ?></p>
    </div>
</div>

<!-- Step 5: Results (shown after import) -->
<div class="fs-settings-section" id="fs-import-step-results" style="display: none;">
    <h3><?php esc_html_e('Import Complete', 'freelance-studio'); ?></h3>
    
    <div class="fs-import-results-summary" id="fs-import-results-summary"></div>
    
    <div style="margin-top: 20px; display: flex; gap: 10px;" id="fs-import-result-links">
        <a href="<?php echo esc_url(admin_url('admin.php?page=fs-clients')); ?>" class="fs-btn fs-btn-secondary fs-import-result-invoices-link"><?php esc_html_e('View Clients', 'freelance-studio'); ?></a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=fs-finances&tab=invoices')); ?>" class="fs-btn fs-btn-primary fs-import-result-invoices-link"><?php esc_html_e('View Invoices', 'freelance-studio'); ?></a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=fs-finances&tab=expenses')); ?>" class="fs-btn fs-btn-primary fs-import-result-expenses-link" style="display:none;"><?php esc_html_e('View Expenses', 'freelance-studio'); ?></a>
        <button type="button" class="fs-btn fs-btn-secondary" id="fs-import-another"><?php esc_html_e('Import Another File', 'freelance-studio'); ?></button>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    var importData = {
        rows: [],
        headers: [],
        mapping: {},
        file: null,
        importType: 'invoices'
    };

    // ---- Import Type Selector ----
    $('.fs-import-type-card').on('click', function() {
        $('.fs-import-type-card').removeClass('active');
        $(this).addClass('active');
        importData.importType = $(this).data('type');
        updateImportTypeUI();
        // If a file is already loaded, re-run auto-mapping with new type
        if (importData.headers.length > 0) {
            var autoMap = getAutoMap();
            importData.mapping = {};
            importData.headers.forEach(function(h, i) {
                importData.mapping[i] = autoMap[h.toLowerCase().trim()] || 'skip';
            });
            // If mapping step is visible, refresh it
            if ($('#fs-import-step-mapping').is(':visible')) {
                showMappingStep();
            }
        }
    });

    function updateImportTypeUI() {
        if (importData.importType === 'expenses') {
            $('#fs-import-upload-desc').text('<?php esc_html_e('Upload a CSV file containing expense data. The file should include columns for date, amount, merchant/vendor, and category.', 'freelance-studio'); ?>');
            $('#fs-import-columns-help').text('<?php esc_html_e('Date, Total/Amount, Merchant, Category, Purpose/Description, Notes, Sales Tax, Currency', 'freelance-studio'); ?>');
            $('#fs-import-skip-existing').closest('div').hide();
            $('#fs-import-projects-completed').closest('div').hide();
        } else {
            $('#fs-import-upload-desc').text('<?php esc_html_e('Upload a CSV file containing invoice data. The file should include columns for client name, project name, invoice number, dates, and amounts.', 'freelance-studio'); ?>');
            $('#fs-import-columns-help').text('<?php esc_html_e('Client Name, Project Name, Number (invoice #), Created Date, Due Date, Issued Date, Sent Date, Paid Date, Total, Tax Total, Discount Total, Payment Total, Notes, Currency', 'freelance-studio'); ?>');
            $('#fs-import-skip-existing').closest('div').show();
            $('#fs-import-projects-completed').closest('div').show();
        }
    }

    // Field definitions per import type
    var invoiceFields = {
        'client_name': '<?php esc_html_e('Client Name', 'freelance-studio'); ?>',
        'project_name': '<?php esc_html_e('Project Name', 'freelance-studio'); ?>',
        'invoice_number': '<?php esc_html_e('Invoice Number', 'freelance-studio'); ?>',
        'issue_date': '<?php esc_html_e('Issue Date', 'freelance-studio'); ?>',
        'due_date': '<?php esc_html_e('Due Date', 'freelance-studio'); ?>',
        'paid_date': '<?php esc_html_e('Paid Date', 'freelance-studio'); ?>',
        'sent_date': '<?php esc_html_e('Sent Date', 'freelance-studio'); ?>',
        'total': '<?php esc_html_e('Total', 'freelance-studio'); ?>',
        'payment_total': '<?php esc_html_e('Payment Total', 'freelance-studio'); ?>',
        'tax_total': '<?php esc_html_e('Tax Total', 'freelance-studio'); ?>',
        'discount_total': '<?php esc_html_e('Discount Total', 'freelance-studio'); ?>',
        'notes': '<?php esc_html_e('Notes', 'freelance-studio'); ?>',
        'currency': '<?php esc_html_e('Currency', 'freelance-studio'); ?>',
        'skip': '<?php esc_html_e('— Skip this column —', 'freelance-studio'); ?>'
    };

    var expenseFields = {
        'expense_date': '<?php esc_html_e('Date', 'freelance-studio'); ?>',
        'amount': '<?php esc_html_e('Amount', 'freelance-studio'); ?>',
        'merchant': '<?php esc_html_e('Merchant / Vendor', 'freelance-studio'); ?>',
        'category': '<?php esc_html_e('Category', 'freelance-studio'); ?>',
        'description': '<?php esc_html_e('Description / Purpose', 'freelance-studio'); ?>',
        'notes': '<?php esc_html_e('Notes', 'freelance-studio'); ?>',
        'sales_tax': '<?php esc_html_e('Sales Tax', 'freelance-studio'); ?>',
        'currency': '<?php esc_html_e('Currency', 'freelance-studio'); ?>',
        'skip': '<?php esc_html_e('— Skip this column —', 'freelance-studio'); ?>'
    };

    // Auto-detect mapping
    var invoiceAutoMap = {
        'client name': 'client_name', 'client': 'client_name',
        'project name': 'project_name', 'project': 'project_name',
        'number': 'invoice_number', 'invoice number': 'invoice_number', 'invoice #': 'invoice_number',
        'issued date': 'issue_date', 'issue date': 'issue_date', 'invoice date': 'issue_date',
        'created date': 'issue_date', 'date': 'issue_date',
        'due date': 'due_date', 'due': 'due_date',
        'paid date': 'paid_date', 'paid': 'paid_date',
        'sent date': 'sent_date',
        'total': 'total', 'amount': 'total',
        'payment total': 'payment_total',
        'tax total': 'tax_total', 'tax': 'tax_total',
        'discount total': 'discount_total', 'discount': 'discount_total',
        'notes': 'notes', 'currency': 'currency'
    };

    var expenseAutoMap = {
        'date': 'expense_date', 'expense date': 'expense_date', 'created date': 'expense_date',
        'issued date': 'expense_date',
        'total': 'amount', 'amount': 'amount',
        'merchant': 'merchant', 'vendor': 'merchant',
        'category': 'category',
        'purpose': 'description', 'description': 'description',
        'notes': 'notes',
        'sales tax': 'sales_tax', 'tax': 'sales_tax',
        'currency': 'currency'
    };

    function getFields() { return importData.importType === 'expenses' ? expenseFields : invoiceFields; }
    function getAutoMap() { return importData.importType === 'expenses' ? expenseAutoMap : invoiceAutoMap; }

    // ---- CSV Parser ----
    function parseCSV(text) {
        var lines = [], currentLine = [], currentField = '', inQuotes = false;
        for (var i = 0; i < text.length; i++) {
            var c = text[i], next = text[i + 1];
            if (inQuotes) {
                if (c === '"' && next === '"') { currentField += '"'; i++; }
                else if (c === '"') { inQuotes = false; }
                else { currentField += c; }
            } else {
                if (c === '"') { inQuotes = true; }
                else if (c === ',') { currentLine.push(currentField.trim()); currentField = ''; }
                else if (c === '\n' || (c === '\r' && next === '\n')) {
                    currentLine.push(currentField.trim()); currentField = '';
                    if (currentLine.length > 1 || currentLine[0] !== '') lines.push(currentLine);
                    currentLine = []; if (c === '\r') i++;
                } else { currentField += c; }
            }
        }
        currentLine.push(currentField.trim());
        if (currentLine.length > 1 || currentLine[0] !== '') lines.push(currentLine);
        return lines;
    }

    // ---- File handling ----
    function handleFile(file) {
        if (!file || !file.name.toLowerCase().endsWith('.csv')) {
            alert('<?php esc_html_e('Please select a CSV file.', 'freelance-studio'); ?>');
            return;
        }
        importData.file = file;
        $('.fs-import-dropzone-content').hide();
        $('.fs-import-dropzone-selected').show();
        $('.fs-import-filename').text(file.name);

        var reader = new FileReader();
        reader.onload = function(e) {
            var parsed = parseCSV(e.target.result);
            if (parsed.length < 2) { alert('<?php esc_html_e('CSV file appears empty or has no data rows.', 'freelance-studio'); ?>'); return; }
            importData.headers = parsed[0];
            importData.rows = parsed.slice(1);
            var autoMap = getAutoMap();
            importData.mapping = {};
            importData.headers.forEach(function(h, i) {
                importData.mapping[i] = autoMap[h.toLowerCase().trim()] || 'skip';
            });
            showMappingStep();
        };
        reader.readAsText(file);
    }

    $('#fs-import-file').on('change', function() { if (this.files.length) handleFile(this.files[0]); });
    var $dropzone = $('#fs-import-dropzone');
    $dropzone.on('dragover dragenter', function(e) { e.preventDefault(); $(this).addClass('fs-import-dropzone-active'); })
        .on('dragleave drop', function(e) { e.preventDefault(); $(this).removeClass('fs-import-dropzone-active'); })
        .on('drop', function(e) { var files = e.originalEvent.dataTransfer.files; if (files.length) handleFile(files[0]); });

    $('.fs-import-remove-file').on('click', function() {
        importData.file = null; importData.rows = []; importData.headers = [];
        $('#fs-import-file').val('');
        $('.fs-import-dropzone-content').show(); $('.fs-import-dropzone-selected').hide();
        $('#fs-import-step-mapping').hide(); $('#fs-import-step-upload').show();
    });

    // ---- Mapping Step ----
    function showMappingStep() {
        $('#fs-import-step-upload').hide();
        $('#fs-import-step-mapping').show();
        updateImportTypeUI();
        var fields = getFields();
        var $tbody = $('#fs-import-mapping-table tbody').empty();
        importData.headers.forEach(function(header, i) {
            var $select = $('<select class="fs-import-map-select" data-col="' + i + '">');
            Object.keys(fields).forEach(function(key) {
                var $opt = $('<option>').val(key).text(fields[key]);
                if (importData.mapping[i] === key) $opt.prop('selected', true);
                $select.append($opt);
            });
            var sample = importData.rows.length > 0 ? (importData.rows[0][i] || '') : '';
            if (sample.length > 60) sample = sample.substring(0, 60) + '...';
            $tbody.append($('<tr>').append($('<td>').text(header), $('<td>').append($select), $('<td>').html('<code>' + $('<span>').text(sample).html() + '</code>')));
        });
    }

    $(document).on('change', '.fs-import-map-select', function() { importData.mapping[$(this).data('col')] = $(this).val(); });
    $('#fs-import-back-to-upload').on('click', function() { $('#fs-import-step-mapping').hide(); $('#fs-import-step-upload').show(); });

    // ---- Preview Step ----
    $('#fs-import-preview-btn').on('click', function() {
        if (importData.importType === 'expenses') {
            previewExpenses();
        } else {
            previewInvoices();
        }
    });

    function previewExpenses() {
        var mapped = Object.values(importData.mapping);
        if (mapped.indexOf('amount') === -1) {
            alert('<?php esc_html_e('Amount column is required. Please map it before continuing.', 'freelance-studio'); ?>');
            return;
        }

        var expenses = [];
        var totalAmount = 0;
        var categories = {};

        importData.rows.forEach(function(row) {
            var exp = {};
            Object.keys(importData.mapping).forEach(function(colIdx) {
                var field = importData.mapping[colIdx];
                if (field !== 'skip') exp[field] = row[colIdx] || '';
            });
            if (exp.amount) {
                expenses.push(exp);
                totalAmount += parseFloat(exp.amount) || 0;
                var cat = exp.category || '<?php esc_html_e('Uncategorized', 'freelance-studio'); ?>';
                categories[cat] = (categories[cat] || 0) + 1;
            }
        });

        // Update stats
        $('#fs-import-stat-clients').closest('.fs-import-stat-card').hide();
        $('#fs-import-stat-existing-clients').closest('.fs-import-stat-card').hide();
        $('#fs-import-stat-projects').closest('.fs-import-stat-card').hide();
        $('#fs-import-stat-skipped').closest('.fs-import-stat-card').hide();
        $('#fs-import-stat-invoices').text(expenses.length);
        $('#fs-import-stat-invoices').next('.fs-import-stat-label').text('<?php esc_html_e('Expenses', 'freelance-studio'); ?>');
        $('#fs-import-stat-total').text('$' + totalAmount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
        $('#fs-import-stat-total').next('.fs-import-stat-label').text('<?php esc_html_e('Total Expenses', 'freelance-studio'); ?>');

        // Preview table
        var $thead = $('#fs-import-preview-table thead tr').html(
            '<th>#</th><th><?php esc_html_e('Date', 'freelance-studio'); ?></th><th><?php esc_html_e('Merchant', 'freelance-studio'); ?></th><th><?php esc_html_e('Category', 'freelance-studio'); ?></th><th><?php esc_html_e('Description', 'freelance-studio'); ?></th><th><?php esc_html_e('Amount', 'freelance-studio'); ?></th>'
        );
        var $tbody = $('#fs-import-preview-table tbody').empty();
        expenses.slice(0, 100).forEach(function(exp, i) {
            $tbody.append(
                '<tr><td>' + (i + 1) + '</td>' +
                '<td>' + $('<span>').text(exp.expense_date || '—').html() + '</td>' +
                '<td>' + $('<span>').text(exp.merchant || '—').html() + '</td>' +
                '<td>' + $('<span>').text(exp.category || '—').html() + '</td>' +
                '<td>' + $('<span>').text(exp.description || '—').html() + '</td>' +
                '<td>$' + (parseFloat(exp.amount) || 0).toLocaleString(undefined, {minimumFractionDigits: 2}) + '</td></tr>'
            );
        });
        if (expenses.length > 100) {
            $tbody.append('<tr><td colspan="6" style="text-align:center; color: var(--fs-gray-500);"><?php esc_html_e('...and', 'freelance-studio'); ?> ' + (expenses.length - 100) + ' <?php esc_html_e('more', 'freelance-studio'); ?></td></tr>');
        }

        importData.importItems = expenses;
        $('#fs-import-step-mapping').hide();
        $('#fs-import-step-preview').show();
    }

    function previewInvoices() {
        var mapped = Object.values(importData.mapping);
        if (mapped.indexOf('client_name') === -1) {
            alert('<?php esc_html_e('Client Name column is required.', 'freelance-studio'); ?>');
            return;
        }

        var $btn = $('#fs-import-preview-btn');
        $btn.prop('disabled', true).text('<?php esc_html_e('Analyzing...', 'freelance-studio'); ?>');

        var invoices = [], clientSet = {}, projectSet = {};
        importData.rows.forEach(function(row) {
            var inv = {};
            Object.keys(importData.mapping).forEach(function(colIdx) {
                var field = importData.mapping[colIdx];
                if (field !== 'skip') inv[field] = row[colIdx] || '';
            });
            if (inv.client_name) {
                invoices.push(inv);
                clientSet[inv.client_name] = true;
                if (inv.project_name) projectSet[inv.client_name + '||' + inv.project_name] = true;
            }
        });

        $.post(ajaxurl, {
            action: 'fs_import_preview',
            nonce: '<?php echo esc_js(wp_create_nonce('fs_import_nonce')); ?>',
            clients: JSON.stringify(Object.keys(clientSet)),
            invoice_numbers: JSON.stringify(invoices.map(function(inv) { return inv.invoice_number || ''; })),
            projects: JSON.stringify(Object.keys(projectSet))
        }, function(response) {
            $btn.prop('disabled', false).text('<?php esc_html_e('Preview Import', 'freelance-studio'); ?>');
            if (!response.success) { alert(response.data || '<?php esc_html_e('Preview failed.', 'freelance-studio'); ?>'); return; }

            var existing = response.data;
            var skipDupes = $('#fs-import-skip-existing').is(':checked');
            var newClients = 0, existingClients = 0, newProjects = 0;
            var importInvoices = [], skippedCount = 0, totalRevenue = 0;

            Object.keys(clientSet).forEach(function(name) {
                if (existing.clients.indexOf(name.toLowerCase()) > -1) existingClients++; else newClients++;
            });
            Object.keys(projectSet).forEach(function(key) {
                if (existing.projects.indexOf(key.toLowerCase()) === -1) newProjects++;
            });
            invoices.forEach(function(inv) {
                var isDupe = inv.invoice_number && existing.invoice_numbers.indexOf(inv.invoice_number) > -1;
                if (isDupe && skipDupes) { skippedCount++; return; }
                totalRevenue += parseFloat(inv.total) || 0;
                importInvoices.push(inv);
            });

            // Show all stat cards and reset labels
            $('.fs-import-stat-card').show();
            $('#fs-import-stat-invoices').next('.fs-import-stat-label').text('<?php esc_html_e('Invoices', 'freelance-studio'); ?>');
            $('#fs-import-stat-total').next('.fs-import-stat-label').text('<?php esc_html_e('Total Revenue', 'freelance-studio'); ?>');

            $('#fs-import-stat-clients').text(newClients);
            $('#fs-import-stat-existing-clients').text(existingClients);
            $('#fs-import-stat-projects').text(newProjects);
            $('#fs-import-stat-invoices').text(importInvoices.length);
            $('#fs-import-stat-skipped').text(skippedCount);
            $('#fs-import-stat-total').text('$' + totalRevenue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));

            // Reset preview table headers
            $('#fs-import-preview-table thead tr').html(
                '<th><?php esc_html_e('#', 'freelance-studio'); ?></th><th><?php esc_html_e('Client', 'freelance-studio'); ?></th><th><?php esc_html_e('Project', 'freelance-studio'); ?></th><th><?php esc_html_e('Invoice #', 'freelance-studio'); ?></th><th><?php esc_html_e('Date', 'freelance-studio'); ?></th><th><?php esc_html_e('Total', 'freelance-studio'); ?></th><th><?php esc_html_e('Status', 'freelance-studio'); ?></th>'
            );
            var $tbody = $('#fs-import-preview-table tbody').empty();
            importInvoices.slice(0, 100).forEach(function(inv, i) {
                var status = inv.paid_date ? 'paid' : (inv.sent_date ? 'sent' : 'draft');
                $tbody.append('<tr><td>' + (i + 1) + '</td><td>' + $('<span>').text(inv.client_name).html() + '</td><td>' + $('<span>').text(inv.project_name || '—').html() + '</td><td>' + $('<span>').text(inv.invoice_number || '—').html() + '</td><td>' + $('<span>').text(inv.issue_date || inv.due_date || '—').html() + '</td><td>$' + (parseFloat(inv.total) || 0).toLocaleString(undefined, {minimumFractionDigits: 2}) + '</td><td><span class="fs-status-badge status-' + status + '">' + status.toUpperCase() + '</span></td></tr>');
            });
            if (importInvoices.length > 100) {
                $tbody.append('<tr><td colspan="7" style="text-align:center; color: var(--fs-gray-500);"><?php esc_html_e('...and', 'freelance-studio'); ?> ' + (importInvoices.length - 100) + ' <?php esc_html_e('more', 'freelance-studio'); ?></td></tr>');
            }
            importData.importItems = importInvoices;
            $('#fs-import-step-mapping').hide();
            $('#fs-import-step-preview').show();
        });
    }

    $('#fs-import-back-to-mapping').on('click', function() { $('#fs-import-step-preview').hide(); $('#fs-import-step-mapping').show(); });

    // ---- Run Import ----
    $('#fs-import-run-btn').on('click', function() {
        var $btn = $(this);
        var typeLabel = importData.importType === 'expenses' ? '<?php esc_html_e('expenses', 'freelance-studio'); ?>' : '<?php esc_html_e('clients, projects, and invoices', 'freelance-studio'); ?>';
        if (!confirm('<?php esc_html_e('This will create', 'freelance-studio'); ?> ' + typeLabel + ' <?php esc_html_e('in your database. Continue?', 'freelance-studio'); ?>')) return;

        $btn.prop('disabled', true);
        $('#fs-import-step-preview').hide();
        $('#fs-import-step-progress').show();

        var batchSize = 25;
        var batches = [];
        for (var i = 0; i < importData.importItems.length; i += batchSize) {
            batches.push(importData.importItems.slice(i, i + batchSize));
        }

        var totalBatches = batches.length;
        var results = { clients_created: 0, projects_created: 0, invoices_created: 0, expenses_created: 0, errors: [] };

        function processBatch(batchIndex) {
            if (batchIndex >= totalBatches) { showResults(results); return; }
            var pct = Math.round((batchIndex / totalBatches) * 100);
            $('#fs-import-progress-fill').css('width', pct + '%');
            $('#fs-import-progress-text').text('<?php esc_html_e('Processing batch', 'freelance-studio'); ?> ' + (batchIndex + 1) + ' <?php esc_html_e('of', 'freelance-studio'); ?> ' + totalBatches + '...');

            var action = importData.importType === 'expenses' ? 'fs_import_expenses_batch' : 'fs_import_batch';
            var postData = {
                action: action,
                nonce: '<?php echo esc_js(wp_create_nonce('fs_import_nonce')); ?>',
                batch: JSON.stringify(batches[batchIndex])
            };
            if (importData.importType === 'invoices') {
                postData.projects_completed = $('#fs-import-projects-completed').is(':checked') ? 1 : 0;
            }

            $.post(ajaxurl, postData, function(response) {
                if (response.success) {
                    results.clients_created += response.data.clients_created || 0;
                    results.projects_created += response.data.projects_created || 0;
                    results.invoices_created += response.data.invoices_created || 0;
                    results.expenses_created += response.data.expenses_created || 0;
                    if (response.data.errors) results.errors = results.errors.concat(response.data.errors);
                } else {
                    results.errors.push('<?php esc_html_e('Batch', 'freelance-studio'); ?> ' + (batchIndex + 1) + ' <?php esc_html_e('failed:', 'freelance-studio'); ?> ' + (response.data || ''));
                }
                processBatch(batchIndex + 1);
            }).fail(function() {
                results.errors.push('<?php esc_html_e('Batch', 'freelance-studio'); ?> ' + (batchIndex + 1) + ' <?php esc_html_e('failed: Network error', 'freelance-studio'); ?>');
                processBatch(batchIndex + 1);
            });
        }
        processBatch(0);
    });

    // ---- Show Results ----
    function showResults(results) {
        $('#fs-import-progress-fill').css('width', '100%');
        setTimeout(function() {
            $('#fs-import-step-progress').hide();
            $('#fs-import-step-results').show();

            var html = '<div class="fs-import-results-cards"><div class="fs-import-result-card fs-import-result-success"><span class="dashicons dashicons-yes-alt"></span><div>';
            if (importData.importType === 'expenses') {
                html += '<strong>' + results.expenses_created + '</strong> <?php esc_html_e('expenses imported', 'freelance-studio'); ?>';
                $('.fs-import-result-invoices-link').hide();
                $('.fs-import-result-expenses-link').show();
            } else {
                html += '<strong>' + results.clients_created + '</strong> <?php esc_html_e('clients created', 'freelance-studio'); ?><br>';
                html += '<strong>' + results.projects_created + '</strong> <?php esc_html_e('projects created', 'freelance-studio'); ?><br>';
                html += '<strong>' + results.invoices_created + '</strong> <?php esc_html_e('invoices imported', 'freelance-studio'); ?>';
                $('.fs-import-result-invoices-link').show();
                $('.fs-import-result-expenses-link').hide();
            }
            html += '</div></div>';

            if (results.errors.length > 0) {
                html += '<div class="fs-import-result-card fs-import-result-errors"><span class="dashicons dashicons-warning"></span><div><strong>' + results.errors.length + ' <?php esc_html_e('errors occurred:', 'freelance-studio'); ?></strong><ul>';
                results.errors.slice(0, 10).forEach(function(err) { html += '<li>' + $('<span>').text(err).html() + '</li>'; });
                if (results.errors.length > 10) html += '<li>...<?php esc_html_e('and', 'freelance-studio'); ?> ' + (results.errors.length - 10) + ' <?php esc_html_e('more', 'freelance-studio'); ?></li>';
                html += '</ul></div></div>';
            }
            html += '</div>';
            $('#fs-import-results-summary').html(html);
        }, 500);
    }

    // Import another
    $('#fs-import-another').on('click', function() {
        importData = { rows: [], headers: [], mapping: {}, file: null, importType: importData.importType };
        $('#fs-import-file').val('');
        $('.fs-import-dropzone-content').show(); $('.fs-import-dropzone-selected').hide();
        $('.fs-import-stat-card').show();
        $('#fs-import-step-results').hide(); $('#fs-import-step-upload').show();
    });
});
</script>
