/* CodeDE Table Viewer – Admin JS */
/* global cdtvAdmin, jQuery */

(function ($) {
    'use strict';

    var currentStep  = 1;
    var uploadedData = null;
    var isEdit       = $('#cdtv-is-edit').val() === '1';
    var tableId      = $('#cdtv-table-id').val();

    // -----------------------------------------------------------------------
    // Step navigation
    // -----------------------------------------------------------------------
    function goToStep(step) {
        currentStep = step;
        $('.cdtv-wizard-panel').hide();
        $('#cdtv-step-' + step).show();
        $('.cdtv-step').removeClass('active');
        $('.cdtv-step[data-step="' + step + '"]').addClass('active');
    }

    // -----------------------------------------------------------------------
    // On init: edit mode → load existing preview immediately
    // -----------------------------------------------------------------------
    if (isEdit && tableId) {
        loadExistingPreview(tableId);
    }

    function loadExistingPreview(id) {
        $.post(cdtvAdmin.ajaxUrl, {
            action:   'cdtv_get_table_preview',
            nonce:    cdtvAdmin.nonce,
            table_id: id
        }, function (res) {
            if (res.success) {
                // Do NOT set uploadedData here – that would wrongly trigger
                // cdtv_save_table (which needs a fresh upload transient).
                // uploadedData is only set when the user actually uploads a new file.
                buildPreview(res.data);
            } else {
                $('#cdtv-preview-wrap').html('<p style="color:red;">' + escHtml(res.data.message) + '</p>');
            }
        }).fail(function () {
            $('#cdtv-preview-wrap').html('<p style="color:red;">Could not load preview.</p>');
        });
    }

    // -----------------------------------------------------------------------
    // File selection & drag-drop (Step 1 / new table)
    // -----------------------------------------------------------------------
    $('#cdtv-select-file').on('click', function () {
        $('#cdtv-file-input').trigger('click');
    });

    $('#cdtv-file-input').on('change', function () {
        var file = this.files[0];
        if (file) uploadFile(file, 'new');
    });

    var dropZone = document.getElementById('cdtv-drop-zone');
    if (dropZone) {
        dropZone.addEventListener('dragover', function (e) {
            e.preventDefault();
            dropZone.classList.add('drag-over');
        });
        dropZone.addEventListener('dragleave', function () {
            dropZone.classList.remove('drag-over');
        });
        dropZone.addEventListener('drop', function (e) {
            e.preventDefault();
            dropZone.classList.remove('drag-over');
            var file = e.dataTransfer.files[0];
            if (file) uploadFile(file, 'new');
        });
    }

    // -----------------------------------------------------------------------
    // Replace file section (Edit mode)
    // -----------------------------------------------------------------------
    $('#cdtv-toggle-replace').on('click', function () {
        var $area = $('#cdtv-replace-area');
        $area.slideToggle(200);
        $(this).toggleClass('active');
    });

    $('#cdtv-select-file-replace').on('click', function () {
        $('#cdtv-file-input-replace').trigger('click');
    });

    $('#cdtv-file-input-replace').on('change', function () {
        var file = this.files[0];
        if (file) uploadFile(file, 'replace');
    });

    var dropZoneReplace = document.getElementById('cdtv-drop-zone-replace');
    if (dropZoneReplace) {
        dropZoneReplace.addEventListener('dragover', function (e) {
            e.preventDefault();
            dropZoneReplace.classList.add('drag-over');
        });
        dropZoneReplace.addEventListener('dragleave', function () {
            dropZoneReplace.classList.remove('drag-over');
        });
        dropZoneReplace.addEventListener('drop', function (e) {
            e.preventDefault();
            dropZoneReplace.classList.remove('drag-over');
            var file = e.dataTransfer.files[0];
            if (file) uploadFile(file, 'replace');
        });
    }

    // -----------------------------------------------------------------------
    // AJAX: upload file
    // mode: 'new' = step1 flow, 'replace' = edit mode replacement
    // -----------------------------------------------------------------------
    function uploadFile(file, mode) {
        var $progress  = mode === 'replace' ? $('#cdtv-upload-progress-replace') : $('#cdtv-upload-progress');
        var $btn       = mode === 'replace' ? $('#cdtv-select-file-replace')     : $('#cdtv-select-file');
        var hasHeader  = mode === 'replace'
            ? ($('#cdtv-has-header-replace').is(':checked') ? '1' : '0')
            : ($('#cdtv-has-header').is(':checked') ? '1' : '0');

        $progress.show();
        $btn.prop('disabled', true);

        var formData = new FormData();
        formData.append('action',     'cdtv_upload_file');
        formData.append('nonce',      cdtvAdmin.nonce);
        formData.append('file',       file);
        formData.append('has_header', hasHeader);

        $.ajax({
            url:         cdtvAdmin.ajaxUrl,
            type:        'POST',
            data:        formData,
            processData: false,
            contentType: false,
            success: function (res) {
                $progress.hide();
                $btn.prop('disabled', false);
                if (res.success) {
                    uploadedData = res.data;
                    buildPreview(res.data);
                    if (mode === 'new') {
                        goToStep(2);
                    } else {
                        // Hide replace area after successful upload
                        $('#cdtv-replace-area').slideUp(200);
                        $('#cdtv-toggle-replace').removeClass('active');
                    }
                } else {
                    alert(res.data.message || cdtvAdmin.strings.uploadError);
                }
            },
            error: function () {
                $progress.hide();
                $btn.prop('disabled', false);
                alert(cdtvAdmin.strings.uploadError);
            }
        });
    }

    // -----------------------------------------------------------------------
    // Build an inline CSS style string from a style object + alignment
    // -----------------------------------------------------------------------
    function buildCellStyle(style, halign) {
        var parts = [];
        if (halign && halign !== 'general') {
            parts.push('text-align:' + halign);
        }
        if (style) {
            if (style.bg)        parts.push('background-color:' + style.bg);
            if (style.color)     parts.push('color:' + style.color);
            if (style.bold)      parts.push('font-weight:bold');
            if (style.italic)    parts.push('font-style:italic');
            if (style.underline) parts.push('text-decoration:underline');
            if (style.font_name) parts.push('font-family:"' + style.font_name + '",sans-serif');
        }
        return parts.join(';');
    }

    // -----------------------------------------------------------------------
    // Build HTML preview from parsed data (with cell styling)
    // -----------------------------------------------------------------------
    function buildPreview(data) {
        var headerStyles = data.header_styles || [];
        var cellStyles   = data.cell_styles   || {};
        var cellHaligns  = data.cell_haligns  || {};
        var colHaligns   = data.col_haligns   || [];

        var $wrap = $('#cdtv-preview-wrap');

        // In Lite mode: strip all cell formatting – only alignment is kept.
        // This matches exactly what the frontend will render.
        var applyStyles = cdtvAdmin.isLicensed;

        // Show appropriate notice
        $wrap.find('.cdtv-pro-preview-notice, .cdtv-lite-preview-notice').remove();
        if (!applyStyles) {
            $wrap.prepend(
                '<div class="cdtv-lite-preview-notice">' +
                '<span class="cdtv-notice-icon">ℹ️</span> ' +
                '<strong>Lite Preview</strong> – ' +
                'Excel colors &amp; fonts are not displayed in the Lite version. ' +
                '<a href="' + (cdtvAdmin.upgradeUrl || 'admin.php?page=cdtv-upgrade') + '">⭐ Upgrade to Pro</a> ' +
                'to show the full Excel formatting in the frontend.' +
                '</div>'
            );
        }

        var html = '<table class="cdtv-table"><thead><tr>';
        $.each(data.headers, function (i, h) {
            var hs     = applyStyles ? (headerStyles[i] || null) : null;
            var halign = (headerStyles[i] && headerStyles[i].halign) ? headerStyles[i].halign : 'general';
            var st     = buildCellStyle(hs, halign);
            html += '<th' + (st ? ' style="' + st + '"' : '') + '>' + escHtml(h) + '</th>';
        });
        html += '</tr></thead><tbody>';

        $.each(data.preview_rows, function (rowIdx, row) {
            html += '<tr>';
            $.each(row, function (colIdx, cell) {
                var halign = (cellHaligns[rowIdx] && cellHaligns[rowIdx][colIdx])
                    ? cellHaligns[rowIdx][colIdx]
                    : (colHaligns[colIdx] || 'general');
                var cstyle = (applyStyles && cellStyles[rowIdx] && cellStyles[rowIdx][colIdx])
                    ? cellStyles[rowIdx][colIdx] : null;
                var st = buildCellStyle(cstyle, halign);
                html += '<td' + (st ? ' style="' + st + '"' : '') + '>' + escHtml(String(cell)) + '</td>';
            });
            html += '</tr>';
        });

        html += '</tbody></table>';

        var shown = data.preview_rows ? data.preview_rows.length : 0;
        if (data.row_count > shown) {
            html += '<p class="cdtv-preview-note">Showing first ' + shown + ' of ' + data.row_count + ' rows.</p>';
        }
        $('#cdtv-preview-wrap').html(html);

        // Apply current border settings immediately
        applyBorderPreview();
    }

    // -----------------------------------------------------------------------
    // Live border preview
    // -----------------------------------------------------------------------
    function applyBorderPreview() {
        var $table  = $('#cdtv-preview-wrap .cdtv-table');
        if (!$table.length) return;

        var preset = $('#cdtv-border-preset-val').val() || 'none';
        var style  = $('#cdtv-border-style').val()  || 'solid';
        var color  = $('#cdtv-border-color').val()  || '#dddddd';
        var width  = $('#cdtv-border-width').val()  || '1';
        var rule   = width + 'px ' + style + ' ' + color;

        // Reset first
        $table.css({ 'border': '', 'border-collapse': '' });
        $table.find('th, td').css('border', '');

        if (preset === 'outer') {
            $table.css({ 'border': rule, 'border-collapse': 'collapse' });
        } else if (preset === 'all') {
            $table.css({ 'border-collapse': 'collapse', 'border': rule });
            $table.find('th, td').css('border', rule);
        }
    }

    // Re-apply whenever any border control changes
    $(document).on('change input', '#cdtv-border-style, #cdtv-border-color, #cdtv-border-width', function () {
        applyBorderPreview();
    });

    // -----------------------------------------------------------------------
    // Load default CSS template
    // -----------------------------------------------------------------------
    var defaultCssTemplate = [
        '/* ── Header row ── */',
        '.cdtv-table thead th {',
        '    background-color: #2271b1;',
        '    color: #ffffff;',
        '    font-weight: 600;',
        '    text-align: left;',
        '    padding: 10px 14px;',
        '    white-space: nowrap;',
        '}',
        '',
        '/* ── Body cells ── */',
        '.cdtv-table tbody td {',
        '    padding: 9px 14px;',
        '    color: #333333;',
        '    vertical-align: top;',
        '}',
        '',
        '/* ── Alternating row color ── */',
        '.cdtv-table tbody tr:nth-child(even) {',
        '    background-color: #f7f9fc;',
        '}',
        '',
        '/* ── Hover highlight ── */',
        '.cdtv-table tbody tr:hover {',
        '    background-color: #eaf3fb;',
        '}',
        '',
        '/* ── Font size ── */',
        '.cdtv-table {',
        '    font-size: 14px;',
        '}'
    ].join('\n');

    $('#cdtv-load-default-css').on('click', function () {
        var $ta = $('#cdtv-custom-css');
        if ($ta.val().trim() && !window.confirm('Replace existing CSS with the default design template?')) return;
        $ta.val(defaultCssTemplate);
    });

    // -----------------------------------------------------------------------
    // Scroll mode radio buttons – keep hidden field in sync + highlight label
    // -----------------------------------------------------------------------
    $(document).on('change', 'input[name="cdtv_scroll_mode"]', function () {
        var val = $(this).val();
        $('#cdtv-scroll-mode-val').val(val);
        $('.cdtv-scroll-option').removeClass('active');
        $(this).closest('.cdtv-scroll-option').addClass('active');
    });

    function escHtml(str) {
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;');
    }

    // -----------------------------------------------------------------------
    // Border editor
    // -----------------------------------------------------------------------
    $(document).on('click', '.cdtv-border-preset', function () {
        var preset = $(this).data('preset');
        $('.cdtv-border-preset').removeClass('active');
        $(this).addClass('active');
        $('#cdtv-border-preset-val').val(preset);
        if (preset === 'none') {
            $('.cdtv-border-options').slideUp(150);
        } else {
            $('.cdtv-border-options').slideDown(150);
        }
        applyBorderPreview();
    });

    // -----------------------------------------------------------------------
    // Back button (new table flow)
    // -----------------------------------------------------------------------
    $('#cdtv-back-step1').on('click', function () {
        goToStep(1);
    });

    // -----------------------------------------------------------------------
    // AJAX: save table
    // Edit mode without new file → save_table_meta only
    // All other cases → save_table (requires transient from upload)
    // -----------------------------------------------------------------------
    $('#cdtv-save-table').on('click', function () {
        var $btn = $(this);
        $btn.prop('disabled', true).find('.dashicons').hide();
        var origText = $btn.text().trim();
        $btn.text(cdtvAdmin.strings.saving);

        var action = (isEdit && !uploadedData) ? 'cdtv_save_table_meta' : 'cdtv_save_table';

        // For edit + new upload: uploadedData is set, use full save
        // For edit + no upload:  use meta-only save
        // For new table:         use full save

        var hasHeaderVal;
        if (isEdit) {
            hasHeaderVal = uploadedData
                ? ($('#cdtv-has-header-replace').is(':checked') ? '1' : '0')
                : $('#cdtv-has-header-val').val();
        } else {
            hasHeaderVal = $('#cdtv-has-header').is(':checked') ? '1' : '0';
        }

        $.post(cdtvAdmin.ajaxUrl, {
            action:         action,
            nonce:          cdtvAdmin.nonce,
            title:          $('#cdtv-table-title').val(),
            has_header:     hasHeaderVal,
            table_id:       tableId,
            custom_css:     $('#cdtv-custom-css').val(),
            rows_per_page:  parseInt($('#cdtv-rows-per-page').val(), 10) || 0,
            scroll_mode:    $('#cdtv-scroll-mode-val').val() || 'auto',
            enable_search:        $('#cdtv-enable-search').is(':checked')       ? '1' : '0',
            enable_sort:          $('#cdtv-enable-sort').is(':checked')         ? '1' : '0',
            enable_excel_format:  $('#cdtv-enable-excel-format').is(':checked') ? '1' : '0',
            reset_styles:         '0',
            border_preset:        $('#cdtv-border-preset-val').val() || 'none',
            border_style:   $('#cdtv-border-style').val()  || 'solid',
            border_color:   $('#cdtv-border-color').val()  || '#dddddd',
            border_width:   $('#cdtv-border-width').val()  || 1
        }, function (res) {
            $btn.prop('disabled', false).text(origText);
            if (res.success) {
                $('#cdtv-result-shortcode').text(res.data.shortcode);
                goToStep(3);
            } else {
                alert(res.data.message || 'Error saving table.');
            }
        });
    });

    // -----------------------------------------------------------------------
    // Copy shortcode (result step & inline info bar)
    // -----------------------------------------------------------------------
    $('#cdtv-copy-result').on('click', function () {
        copyToClipboard($('#cdtv-result-shortcode').text(), $(this));
    });

    $(document).on('click', '.cdtv-copy-shortcode-inline', function () {
        copyToClipboard($(this).data('code'), $(this));
    });

    $(document).on('click', '.cdtv-copy-shortcode', function () {
        var id = $(this).data('id');
        copyToClipboard('[cdtv id="' + id + '"]', $(this));
    });

    function copyToClipboard(text, $btn) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(text).then(function () {
                var orig = $btn.text();
                $btn.text('Copied!');
                setTimeout(function () { $btn.text(orig); }, 2000);
            });
        }
    }

    // -----------------------------------------------------------------------
    // Delete table
    // -----------------------------------------------------------------------
    $(document).on('click', '.cdtv-delete-table', function () {
        if (!window.confirm(cdtvAdmin.strings.confirmDelete)) return;
        var id  = $(this).data('id');
        var $tr = $(this).closest('tr');

        $.post(cdtvAdmin.ajaxUrl, {
            action:   'cdtv_delete_table',
            nonce:    cdtvAdmin.nonce,
            table_id: id
        }, function (res) {
            if (res.success) {
                $tr.fadeOut(300, function () { $(this).remove(); });
            } else {
                alert(res.data.message || 'Error deleting table.');
            }
        });
    });

    // -----------------------------------------------------------------------
    // Export table as CSV
    // -----------------------------------------------------------------------
    $(document).on('click', '.cdtv-export-table', function () {
        var id   = $(this).data('id');
        var form = $('<form>', { method: 'POST', action: cdtvAdmin.ajaxUrl });
        form.append($('<input>').attr({ type: 'hidden', name: 'action',   value: 'cdtv_export_table' }));
        form.append($('<input>').attr({ type: 'hidden', name: 'nonce',    value: cdtvAdmin.nonce }));
        form.append($('<input>').attr({ type: 'hidden', name: 'table_id', value: id }));
        $('body').append(form);
        form.submit();
        form.remove();
    });

    // -----------------------------------------------------------------------
    // Export table as XLSX (Pro)
    // -----------------------------------------------------------------------
    $(document).on('click', '.cdtv-export-xlsx', function () {
        var id   = $(this).data('id');
        var form = $('<form>', { method: 'POST', action: cdtvAdmin.ajaxUrl });
        form.append($('<input>').attr({ type: 'hidden', name: 'action',   value: 'cdtv_export_xlsx' }));
        form.append($('<input>').attr({ type: 'hidden', name: 'nonce',    value: cdtvAdmin.nonce }));
        form.append($('<input>').attr({ type: 'hidden', name: 'table_id', value: id }));
        $('body').append(form);
        form.submit();
        form.remove();
    });

}(jQuery));
