/**
 * CSV Import/Export Module
 * Handles: CSV export, import, preview
 */
(function($) {
    'use strict';

    window.SchemafyCsvExport = {
        /**
         * Export schemas to CSV
         */
        exportSchemasCSV: function() {
            if (!window.SchemafyBulk || !window.SchemafyBulk.allBulkSchemas || window.SchemafyBulk.allBulkSchemas.length === 0) {
                window.SchemafyUtilities.showNotification('No schemas to export', 'warning');
                return;
            }

            const schemas = window.SchemafyBulk.allBulkSchemas;

            const exportData = schemas.map(schema => ({
                url: schema.url,
                schema_name: schema.schema_name,
                schema_type: schema.schema_type,
                schema_data: schema.schema_data,
                is_active: schema.is_active ? 'Active' : 'Inactive',
                created_at: schema.created_at
            }));

            const csv = this.convertToCSV(exportData);
            this.downloadCSV(csv, `schemafy-schemas-export-${Date.now()}.csv`);

            window.SchemafyUtilities.showNotification(`Exported ${schemas.length} schema(s) successfully`, 'success');
        },

        /**
         * Export selected schemas only
         */
        bulkExportSchemas: function(ids) {
            if (!window.SchemafyBulk || !window.SchemafyBulk.allBulkSchemas) {
                window.SchemafyUtilities.showNotification('No schemas available', 'warning');
                return;
            }

            const selectedSchemas = window.SchemafyBulk.allBulkSchemas.filter(schema => ids.includes(parseInt(schema.id)));

            if (selectedSchemas.length === 0) {
                window.SchemafyUtilities.showNotification('No schemas to export', 'warning');
                return;
            }

            const exportData = selectedSchemas.map(schema => ({
                url: schema.url,
                schema_name: schema.schema_name,
                schema_type: schema.schema_type,
                schema_data: schema.schema_data,
                is_active: schema.is_active ? 'Active' : 'Inactive',
                created_at: schema.created_at
            }));

            const csv = this.convertToCSV(exportData);
            this.downloadCSV(csv, `schemafy-schemas-export-${Date.now()}.csv`);

            window.SchemafyUtilities.showNotification(`Exported ${selectedSchemas.length} schema(s) successfully`, 'success');
        },

        /**
         * Collapse a JSON-LD string to a single minified line.
         * Pretty-printed JSON carries newlines which, even when quoted, render
         * as multiple visual lines in Excel. Minifying keeps one row = one schema.
         */
        minifyJsonField: function(value) {
            if (typeof value !== 'string' || value === '') return value;
            try {
                return JSON.stringify(JSON.parse(value));
            } catch (e) {
                // Not valid JSON (or already broken) — at least strip line breaks
                return value.replace(/\r?\n/g, ' ').replace(/\s{2,}/g, ' ').trim();
            }
        },

        /**
         * Convert array to CSV string (RFC 4180 quoting).
         */
        convertToCSV: function(objArray) {
            const self = this;
            const array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray;
            let str = '';

            const headers = Object.keys(array[0]);
            str += headers.join(',') + '\r\n';

            for (let i = 0; i < array.length; i++) {
                let line = '';
                for (let j = 0; j < headers.length; j++) {
                    if (line !== '') line += ',';

                    const header = headers[j];
                    let value = array[i][header];

                    // Keep each schema on a single CSV line
                    if (header === 'schema_data') {
                        value = self.minifyJsonField(value);
                    }

                    if (value === null || value === undefined) {
                        value = '';
                    }

                    if (typeof value === 'string') {
                        // Quote when the value contains a delimiter, quote or any
                        // line break (covers \r, \n and the \r\n pair).
                        if (/[",\r\n]/.test(value)) {
                            value = '"' + value.replace(/"/g, '""') + '"';
                        }
                    }
                    line += value;
                }
                str += line + '\r\n';
            }
            return str;
        },

        /**
         * Download CSV file
         */
        downloadCSV: function(csv, filename) {
            // Prepend a UTF-8 BOM so Excel reads accented characters correctly
            // (without it "Organización" opens as "OrganizaciÃ³n").
            const blob = new Blob(['﻿' + csv], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);

            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },

        /**
         * Show import modal
         */
        showImportModal: function() {
            const modalHtml = `
                <div class="schemafy-modal-overlay" id="schemafy-import-modal">
                    <div class="schemafy-modal-v2" style="max-width: 760px;">
                        <div class="schemafy-modal-header-v2">
                            <h3><span class="dashicons dashicons-upload"></span> Import Schemas from CSV</h3>
                            <button class="schemafy-modal-close-v2">&times;</button>
                        </div>
                        <div class="schemafy-modal-body-v2">

                            <!-- STEP 1 -->
                            <div style="display: flex; gap: 12px; align-items: flex-start; margin-bottom: 24px;">
                                <div style="min-width: 28px; height: 28px; border-radius: 50%; background: var(--schemafy-primary); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px;">1</div>
                                <div>
                                    <p style="margin: 0 0 6px; font-weight: 600;">Prepare your CSV file</p>
                                    <p style="margin: 0; color: var(--schemafy-gray-600); font-size: 13px;">
                                        Your file must be a <strong>.csv</strong> file with the correct columns. Not sure how?
                                        <a href="#" id="schemafy-open-help-from-import" style="text-decoration: underline;">See the required format and an example &rarr;</a>
                                    </p>
                                </div>
                            </div>

                            <!-- STEP 2 -->
                            <div style="display: flex; gap: 12px; align-items: flex-start; margin-bottom: 24px;">
                                <div style="min-width: 28px; height: 28px; border-radius: 50%; background: var(--schemafy-primary); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px;">2</div>
                                <div style="width: 100%;">
                                    <p style="margin: 0 0 8px; font-weight: 600;">Upload your CSV file</p>
                                    <input type="file" id="schemafy-import-file" accept=".csv" class="schemafy-file-input">
                                    <p style="margin: 6px 0 0; color: var(--schemafy-gray-500); font-size: 12px;">Only <strong>.csv</strong> files are accepted. Max recommended size: 5 MB.</p>
                                </div>
                            </div>

                            <!-- STEP 3 — Preview (hidden until file selected) -->
                            <div id="schemafy-import-preview" style="display: none;">
                                <div style="display: flex; gap: 12px; align-items: flex-start; margin-bottom: 12px;">
                                    <div style="min-width: 28px; height: 28px; border-radius: 50%; background: var(--schemafy-primary); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px;">3</div>
                                    <div>
                                        <p style="margin: 0 0 4px; font-weight: 600;">Review your data before importing</p>
                                        <p style="margin: 0; color: var(--schemafy-gray-600); font-size: 13px;">
                                            The table below shows a preview of the first 5 rows. Make sure the columns and values look correct before clicking <strong>Import</strong>.
                                        </p>
                                    </div>
                                </div>
                                <div id="schemafy-import-preview-content" style="max-height: 300px; overflow-y: auto; border: 1px solid var(--schemafy-gray-300); border-radius: 8px; margin-left: 40px;"></div>
                            </div>

                            <!-- Required columns quick reference -->
                            <div class="schemafy-info-box-v2" style="margin-top: 24px;">
                                <span class="dashicons dashicons-info" style="margin-top: 2px;"></span>
                                <div style="font-size: 13px; line-height: 1.7;">
                                    <strong>Required columns — your file must include all of these:</strong>
                                    <table style="margin-top: 8px; border-collapse: collapse; width: 100%;">
                                        <thead>
                                            <tr style="background: var(--schemafy-gray-100);">
                                                <th style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); text-align: left;">Column name</th>
                                                <th style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); text-align: left;">What to put here</th>
                                                <th style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); text-align: left;">Example</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <tr>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);"><code>url</code></td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);">The full URL of the page where this schema will appear</td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">https://mysite.com/about</td>
                                            </tr>
                                            <tr style="background: var(--schemafy-gray-50);">
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);"><code>schema_name</code></td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);">A short label to identify this schema in the list</td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">About Page Schema</td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);"><code>schema_type</code></td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);">The schema.org type that describes your content</td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">Article, Product, WebPage…</td>
                                            </tr>
                                            <tr style="background: var(--schemafy-gray-50);">
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);"><code>schema_data</code></td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);">The full JSON-LD code (wrap in double quotes inside the CSV)</td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">{"@context":"https://schema.org",…}</td>
                                            </tr>
                                            <tr>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);"><code>is_active</code> <em style="color:var(--schemafy-gray-500)">(optional)</em></td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300);">Whether the schema should be enabled immediately</td>
                                                <td style="padding: 6px 10px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">Active or Inactive (default: Active)</td>
                                            </tr>
                                        </tbody>
                                    </table>
                                    <p style="margin: 10px 0 0; color: var(--schemafy-gray-500);">
                                        💡 <strong>Tip:</strong> Export your existing schemas first — the downloaded file is already in the correct format and can be used as a template.
                                    </p>
                                </div>
                            </div>

                        </div>
                        <div class="schemafy-modal-footer-v2">
                            <button class="schemafy-btn-secondary" id="schemafy-import-cancel">Cancel</button>
                            <button class="schemafy-btn-primary" id="schemafy-import-start" disabled>
                                <span class="dashicons dashicons-upload"></span> Import
                            </button>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(modalHtml);

            // File selection handler
            $('#schemafy-import-file').on('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    this.previewCSVFile(file);
                }
            });

            // Open help modal from import modal link
            $('#schemafy-import-modal').on('click', '#schemafy-open-help-from-import', (e) => {
                e.preventDefault();
                this.showCSVHelpModal();
            });

            // Close modal
            $('#schemafy-import-modal .schemafy-modal-close-v2, #schemafy-import-cancel').on('click', () => {
                $('#schemafy-import-modal').remove();
            });

            // Start import
            $('#schemafy-import-start').on('click', () => {
                const file = $('#schemafy-import-file')[0].files[0];
                if (file) {
                    this.importCSVFile(file);
                }
            });
        },

        /**
         * Preview CSV file content
         */
        previewCSVFile: function(file) {
            const reader = new FileReader();

            reader.onload = (e) => {
                const rows = this.parseCSV(e.target.result);

                if (rows.length < 2) {
                    window.SchemafyUtilities.showNotification('The CSV file is empty or has no data rows. Add at least one row below the header and try again.', 'error');
                    return;
                }

                const headers = rows[0];
                const requiredHeaders = ['url', 'schema_name', 'schema_type', 'schema_data'];
                const missingHeaders = requiredHeaders.filter(h => !headers.includes(h));

                if (missingHeaders.length > 0) {
                    window.SchemafyUtilities.showNotification(
                        'Your file is missing required column(s): ' + missingHeaders.join(', ') + '. Please check the format guide and update your file.',
                        'error'
                    );
                    return;
                }

                // Build preview table
                let previewHtml = '<table style="width: 100%; font-size: 12px; border-collapse: collapse;">';
                previewHtml += '<thead><tr>';
                headers.forEach(h => {
                    previewHtml += `<th style="padding: 8px; border: 1px solid var(--schemafy-gray-300); background: var(--schemafy-gray-100); text-align: left;">${h}</th>`;
                });
                previewHtml += '</tr></thead><tbody>';

                const previewRows = rows.slice(1, 6);
                previewRows.forEach(values => {
                    previewHtml += '<tr>';
                    values.forEach(v => {
                        const truncated = v.length > 50 ? v.substring(0, 50) + '…' : v;
                        previewHtml += `<td style="padding: 8px; border: 1px solid var(--schemafy-gray-300);">${window.SchemafyUtilities.escapeHtml(truncated)}</td>`;
                    });
                    previewHtml += '</tr>';
                });

                previewHtml += '</tbody></table>';
                previewHtml += `<p style="margin: 10px 10px 6px; color: var(--schemafy-gray-500); font-size: 12px;">Showing ${previewRows.length} of ${rows.length - 1} data row(s). If the data looks wrong, close this window, fix your file, and upload it again.</p>`;

                $('#schemafy-import-preview-content').html(previewHtml);
                $('#schemafy-import-preview').show();
                $('#schemafy-import-start').prop('disabled', false);
            };

            reader.readAsText(file);
        },

        /**
         * Parse a whole CSV document into rows of fields.
         *
         * Handles:
         *  - quoted fields containing commas AND line breaks (multi-line cells)
         *  - escaped quotes ("")
         *  - LENIENT inner quotes: a lone " inside a quoted field that is NOT
         *    followed by a delimiter/newline is treated as a literal character,
         *    so user files like  "Servicio "de" Grúas"  no longer break import
         *    (reported bug: bulk fails when values contain double quotes).
         *  - a leading UTF-8 BOM.
         *
         * @param {string} content Raw file text.
         * @return {Array<Array<string>>} Rows of trimmed field values.
         */
        parseCSV: function(content) {
            if (content.charCodeAt(0) === 0xFEFF) {
                content = content.slice(1); // strip BOM
            }

            const rows = [];
            let row = [];
            let field = '';
            let inQuotes = false;
            const n = content.length;

            for (let i = 0; i < n; i++) {
                const char = content[i];

                if (inQuotes) {
                    if (char === '"') {
                        const next = content[i + 1];
                        if (next === '"') { field += '"'; i++; continue; }        // escaped ""
                        if (next === undefined || next === ',' || next === '\n' || next === '\r') {
                            inQuotes = false; continue;                            // real closing quote
                        }
                        field += '"'; continue;                                    // lenient: literal quote
                    }
                    field += char;
                    continue;
                }

                if (char === '"' && field === '') { inQuotes = true; continue; }    // open quote at field start
                if (char === ',') { row.push(field.trim()); field = ''; continue; }
                if (char === '\r') { continue; }
                if (char === '\n') { row.push(field.trim()); rows.push(row); row = []; field = ''; continue; }
                field += char;
            }

            // flush trailing field/row
            row.push(field.trim());
            if (row.length > 1 || row[0] !== '') {
                rows.push(row);
            }
            return rows;
        },

        /**
         * Import CSV file
         */
        importCSVFile: function(file) {
            const reader = new FileReader();

            reader.onload = (e) => {
                const rows = this.parseCSV(e.target.result);

                if (rows.length < 2) {
                    window.SchemafyUtilities.showNotification('No data to import', 'error');
                    return;
                }

                const headers = rows[0];
                const schemas = [];

                for (let i = 1; i < rows.length; i++) {
                    const values = rows[i];
                    const schema = {};

                    headers.forEach((header, index) => {
                        schema[header] = values[index] || '';
                    });

                    if (schema.url && schema.schema_name && schema.schema_data) {
                        schemas.push(schema);
                    }
                }

                if (schemas.length === 0) {
                    window.SchemafyUtilities.showNotification(
                        'No valid schemas were found in your file. Make sure each row has a url, schema_name, and schema_data value.',
                        'error'
                    );
                    return;
                }

                window.SchemafyUtilities.showNotification(`Importing ${schemas.length} schema(s)… Please wait.`, 'info');

                $.ajax({
                    url: schemafy_ajax.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'schemafy_import_schemas_csv',
                        nonce: schemafy_ajax.nonce,
                        schemas: JSON.stringify(schemas)
                    },
                    success: (response) => {
                        if (response.success) {
                            $('#schemafy-import-modal').remove();
                            window.SchemafyUtilities.showNotification(`Successfully imported ${response.data.imported} schema(s)`, 'success');

                            if (window.SchemafyBulk) {
                                window.SchemafyBulk.loadBulkSchemas();
                            }
                        } else {
                            window.SchemafyUtilities.showNotification(response.data || 'Import failed', 'error');
                        }
                    },
                    error: () => {
                        window.SchemafyUtilities.showNotification('A network error occurred. Check your connection and try again.', 'error');
                    }
                });
            };

            reader.readAsText(file);
        },

        /**
         * Show CSV help modal
         */
        showCSVHelpModal: function() {
            const modalHtml = `
                <div class="schemafy-modal-overlay" id="schemafy-csv-help-modal">
                    <div class="schemafy-modal-v2" style="max-width: 760px;">
                        <div class="schemafy-modal-header-v2">
                            <h3><span class="dashicons dashicons-editor-help"></span> CSV Format Guide — How to Prepare Your File</h3>
                            <button class="schemafy-modal-close-v2">&times;</button>
                        </div>
                        <div class="schemafy-modal-body-v2">

                            <!-- What is a CSV -->
                            <div class="schemafy-info-box-v2" style="margin-bottom: 24px;">
                                <span class="dashicons dashicons-lightbulb" style="margin-top: 2px;"></span>
                                <div style="font-size: 13px; line-height: 1.7;">
                                    <strong>What is a CSV file?</strong><br>
                                    A CSV (Comma-Separated Values) file is a simple spreadsheet you can create in Excel, Google Sheets, or any text editor.
                                    Each row is one schema and each column is a field. The first row must contain the column headers exactly as shown below.
                                </div>
                            </div>

                            <!-- Required columns -->
                            <h4 style="margin-bottom: 8px;">📋 Required columns</h4>
                            <p style="color: var(--schemafy-gray-600); font-size: 13px; margin-bottom: 12px;">Every row in your file must have a value for each of these columns. Rows missing any of them will be skipped on import.</p>
                            <table style="width: 100%; border-collapse: collapse; font-size: 13px; margin-bottom: 24px;">
                                <thead>
                                    <tr style="background: var(--schemafy-gray-100);">
                                        <th style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); text-align: left;">Column</th>
                                        <th style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); text-align: left;">What to fill in</th>
                                        <th style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); text-align: left;">Example value</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);"><code>url</code></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);">The full URL of the page where this schema should appear. Must start with <em>https://</em></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">https://mysite.com/blog/post-1</td>
                                    </tr>
                                    <tr style="background: var(--schemafy-gray-50);">
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);"><code>schema_name</code></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);">A short internal name so you can find this schema in the list later</td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">Blog Post Schema</td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);"><code>schema_type</code></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);">The schema.org type that best describes your content</td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">Article &nbsp;|&nbsp; Product &nbsp;|&nbsp; WebPage &nbsp;|&nbsp; FAQPage</td>
                                    </tr>
                                    <tr style="background: var(--schemafy-gray-50);">
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);"><code>schema_data</code></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);">The complete JSON-LD code. In the CSV cell, wrap the entire value in double quotes and replace any internal <code>"</code> with <code>""</code></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">"{""@context"":""https://schema.org"",…}"</td>
                                    </tr>
                                </tbody>
                            </table>

                            <!-- Optional columns -->
                            <h4 style="margin-bottom: 8px;">⚙️ Optional columns</h4>
                            <table style="width: 100%; border-collapse: collapse; font-size: 13px; margin-bottom: 24px;">
                                <thead>
                                    <tr style="background: var(--schemafy-gray-100);">
                                        <th style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); text-align: left;">Column</th>
                                        <th style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); text-align: left;">What to fill in</th>
                                        <th style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); text-align: left;">Accepted values</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);"><code>is_active</code></td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300);">Whether the schema should be live immediately after import. If left blank, it defaults to <strong>Active</strong>.</td>
                                        <td style="padding: 8px 12px; border: 1px solid var(--schemafy-gray-300); color: var(--schemafy-gray-500);">Active &nbsp;|&nbsp; Inactive</td>
                                    </tr>
                                </tbody>
                            </table>

                            <!-- Example -->
                            <h4 style="margin-bottom: 8px;">📄 Example CSV</h4>
                            <p style="color: var(--schemafy-gray-600); font-size: 13px; margin-bottom: 8px;">Copy this into a <code>.csv</code> file or open it in Excel/Google Sheets as a starting point:</p>
                            <pre style="background: var(--schemafy-gray-100); padding: 14px 16px; border-radius: 8px; overflow-x: auto; font-size: 12px; line-height: 1.6; border: 1px solid var(--schemafy-gray-300);">url,schema_name,schema_type,schema_data,is_active
https://example.com/page1,Homepage Schema,WebPage,"{""@context"":""https://schema.org"",""@type"":""WebPage"",""name"":""Homepage""}",Active
https://example.com/about,About Schema,AboutPage,"{""@context"":""https://schema.org"",""@type"":""AboutPage"",""name"":""About Us""}",Active</pre>

                            <!-- Common mistakes -->
                            <h4 style="margin-top: 24px; margin-bottom: 8px;">⚠️ Common mistakes to avoid</h4>
                            <ul style="font-size: 13px; color: var(--schemafy-gray-700); line-height: 1.9; padding-left: 20px; margin: 0 0 24px;">
                                <li>Missing a required column header — the names must match exactly (lowercase, no spaces).</li>
                                <li>Forgetting to wrap <code>schema_data</code> in double quotes inside the CSV cell.</li>
                                <li>Using single quotes instead of double quotes inside JSON.</li>
                                <li>Leaving a row without a <code>url</code>, <code>schema_name</code>, or <code>schema_data</code> — those rows will be skipped silently.</li>
                                <li>Saving the file as <code>.xlsx</code> instead of <code>.csv</code> — always export/save as CSV from Excel or Google Sheets.</li>
                            </ul>

                            <div class="schemafy-info-box-v2">
                                <span class="dashicons dashicons-info" style="margin-top: 2px;"></span>
                                <div style="font-size: 13px;">
                                    <strong>Easiest way to get started:</strong> Go back and click <strong>Export All</strong> first. The downloaded file is already in the correct format — open it in Excel or Google Sheets, add or edit rows, save as CSV, and import it here.
                                </div>
                            </div>

                        </div>
                        <div class="schemafy-modal-footer-v2">
                            <button class="schemafy-btn-primary" id="schemafy-csv-help-close">Got it, close</button>
                        </div>
                    </div>
                </div>
            `;

            $('body').append(modalHtml);

            $('#schemafy-csv-help-modal .schemafy-modal-close-v2, #schemafy-csv-help-close').on('click', () => {
                $('#schemafy-csv-help-modal').remove();
            });
        }
    };

})(jQuery);