jQuery(document).ready(function ($) {
    // Initialize jQuery first to make sure no conflicts
    jQuery.noConflict();
    console.log("Checking jQuery version: ", jQuery.fn.jquery);

    // Add these lines near the top of your script, just after jQuery is loaded
    console.log('jQuery version:', $.fn.jquery);
    console.log('DataTables version:', $.fn.dataTable.version);
    console.log('DataTables Editor available:', !!DataTable.Editor);
    console.log('Bootstrap modal available:', typeof $.fn.modal);
        
    // Check if Bootstrap JS is loaded correctly
    if (typeof $.fn.modal === 'undefined') {
        console.error('Bootstrap modal function not found, loading it dynamically');
        // Dynamically load Bootstrap JS if not present
        var script = document.createElement('script');
        script.src = 'https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js';
        script.onload = function() {
            console.log('Bootstrap loaded dynamically');
            // Reinitialize DataTable.use bootstrap
            DataTable.use('bootstrap');
        };
        document.head.appendChild(script);
    }    
    
    // Create global Tabular3 namespace
    window.Tabular3 = window.Tabular3 || {};

    // Initialize inputFormatMapping as an extensible object
    window.Tabular3.inputFormatMapping = {
        text: { type: 'text' },
        number: { type: 'text', attr: { type: 'number' } },
        date: { type: 'datetime' },
        select: { type: 'select' },
        textarea: { type: 'textarea' },
        wysiwyg: { type: 'textarea' }, 
        featured_image: { type: 'text' }, // Default to text type
        media_upload: { type: 'text' }, // Default to text type
        media_list: { type: 'textarea' },        
        taxonomy_autocomplete: { type: 'autocomplete', opts: { multiple: true } },
        relationship: { type: 'autocomplete' },
        readonly: { type: 'readonly' },
        hidden: { type: 'hidden' },
        currency: { type: 'text', attr: { type: 'number', step: '0.01' } },
    };

    // Method to extend input format mapping
    window.Tabular3.extendInputFormatMapping = function(newMappings) {
        // Merge new mappings into the existing mapping
        Object.assign(this.inputFormatMapping, newMappings);
    };

    // Check if configuration is available
    if (typeof window.tabular3_config === 'undefined') {
        console.error('Tabular3 configuration is missing.');
        return;
    }

    const config = window.tabular3_config;
    
    // ✅ Ensure Bootstrap is explicitly used in DataTables
    DataTable.use('bootstrap');

    // Dynamically Generate Fields for Editor
    const editorFields = config.editorFields.map(field => {
        // Special handling for WYSIWYG fields
        
        console.log('We think that we have ' + field.inputFormat + ' for ' + field.name);        
        
        if (field.inputFormat === 'wysiwyg') {
            return {
                label: field.label,
                name: field.name,
                type: 'textarea',
                attr: {
                    'data-editor-type': 'wysiwyg'
                }
            };
        }

        if (field.inputFormat === 'media_list') {
            return {
                label: field.label,
                name: field.name,
                type: 'textarea',
            };
        }        
        
        // Use the global inputFormatMapping
        const inputFormatMapping = window.Tabular3.inputFormatMapping;

        // Base field configuration
        const fieldConfig = {
            label: field.label,
            name: field.name,
            ...(inputFormatMapping[field.inputFormat] || { type: 'text' })
        };
        
        // Handle select options
        if (field.inputFormat === 'select' && field.selectOptions) {
            fieldConfig.options = field.selectOptions.split('\n').map(opt => ({
                label: opt.trim(),
                value: opt.trim()
            }));
        }
        
        // Handle taxonomy autocomplete
        if (field.inputFormat === 'taxonomy_autocomplete' && field.taxonomy) {
            // search: params.term,

            fieldConfig.type = 'autocomplete';
            fieldConfig.ajax = tabular3.ajax_url + '?action=tabular3_get_taxonomy_terms';            
            fieldConfig.ajaxData = {
                action: 'tabular3_get_taxonomy_terms',
                taxonomy: field.taxonomy,
                nonce: tabular3.nonce
            };
            fieldConfig.action = 'tabular3_get_taxonomy_terms';            
        }

        
        // Handle relationship fields
        if (field.inputFormat === 'relationship' && field.relationshipType) {
            // search: params.term,
            
            fieldConfig.type = 'autocomplete';
            fieldConfig.ajax = tabular3.ajax_url + '?action=tabular3_get_relationship_items';
            fieldConfig.ajaxData = {
                action: 'tabular3_get_relationship_items',
                relationship_type: field.relationshipType,
                nonce: tabular3.nonce
            };
            fieldConfig.action = 'tabular3_get_relationship_items';
        }

        return fieldConfig;
    });

    
    const editor = new DataTable.Editor({
        ajax: {
            url: tabular3.ajax_url,
            type: 'POST',
            data: d => {
                d.action = 'tabular3_update_posts';
                d.nonce = tabular3.nonce;
                d.post_type = config.postType;
            }
        },
        fields: editorFields,
        idSrc: 'ID',
        table: '#tabular3-table',
        display: 'bootstrap',
        formOptions: {
            main: {
                submitOnReturn: false,
                buttons: true,
                submit:        'all',
                title:         true,
                drawType:      false

            }
        }
        
    });
    
    /*
    {
    focus:         0,
    message:       true,
    onBackground:  'blur',
    onBlur:        'close',
    onComplete:    'close',
    onEsc:         'close',
    onFieldError:  'focus',
    onReturn:      'submit',
    scope:         'row'
    }
    */
    
        
    editor.on('open', function () {
        config.dtColumns.forEach(function(column) {
            if (column.editorClass) {
                // editor.field() returns the Editor field object for the given data property
                $(editor.field(column.data).node()).addClass(column.editorClass);
                
                // add the new elements
                if (column.editorClass == 'media_upload') {
                    var $fieldNode = $(editor.field(column.data).node());
                    // Only append if it hasn't already been added
                    if ($fieldNode.find('.media_uploader').length === 0) {
                        var currentValue = editor.field(column.data).val();
                        $fieldNode.append(
                            '<div class="media_preview">' +
                                '<img src="' + currentValue + '" alt="Image" style="max-width:160px; height:auto;" />' +
                            '</div>' + 
                            '<div class="media_uploader">' +
                                '<button type="button" data-field="' + column.data + '">Media Upload</button>' +
                            '</div>'
                        );
                    }
                }
                if (column.editorClass == 'featured_image') {
                    var $fieldNode = $(editor.field(column.data).node());
                    // Only append if it hasn't already been added
                    if ($fieldNode.find('.media_uploader').length === 0) {
                        var currentValue = editor.field(column.data).val();                        
                        $fieldNode.append(
                            '<div class="media_preview">' +
                                '<img src="' + currentValue + '" alt="Image" style="max-width:160px; height:auto;" />' +
                            '</div>' +                             
                            '<div class="media_uploader">' +
                                '<button type="button" data-field="' + column.data + '">Media Upload</button>' +
                            '</div>'
                        );
                    }
                }
            }
        });
    });    
    
    /*
    editor.on('open', function (e, action) {
        // Find the modal container. The exact selector may vary depending on your Editor version/configuration.
        // In many cases, the Editor form container uses the class "DTE_Form"
        $('.DTE_Form').append('<div class="my-extra-content">Your additional HTML and functionality here</div>');
    });
    */
    
    // Add this event handler to reload the table after edits
    editor.on('postEdit', function() {
        $('#tabular3-table').DataTable().ajax.reload(null, false);
    });
    
    // Also add similar handlers for other operations if needed
    editor.on('postCreate', function() {
        $('#tabular3-table').DataTable().ajax.reload(null, false);
    });
    
    editor.on('postRemove', function() {
        $('#tabular3-table').DataTable().ajax.reload(null, false);
    });
    
    editor.on('onInitCreate onInitEdit', function() {
        var form = this;
        var footer = $(form.dom.footer);
        
        /*
        // Remove existing buttons
        footer.empty();
        
        // Add custom Update button
        $('<button class="btn btn-primary">Update</button>')
            .appendTo(footer)
            .on('click', function(e) {
                e.preventDefault();
                form.submit();
            });
        */
    });
    
    // Initialize DataTable
    $('#tabular3-table').DataTable({
        dom: 'Bfrtip',
        ajax: {
            url: tabular3.ajax_url,
            type: 'POST',
            data: {
                action: 'tabular3_get_posts',
                nonce: tabular3.nonce,
                post_type: config.postType
            }
        },
        columns: config.dtColumns.map(column => ({
            data: column.data,
            title: column.title,
            className: column.className
        })),
        buttons: [
            { extend: 'create', editor, className: 'btn btn-primary' },
            { extend: 'edit', editor, className: 'btn btn-info' },
            { extend: 'remove', editor, className: 'btn btn-danger' },
            {
                extend: 'collection',
                text: 'Export',
                className: 'btn btn-secondary',
                buttons: [
                    'copy',
                    'excel',
                    'csv',
                    'pdf',
                    'print'
                ]
            }
        ],
        select: {
            style: 'os',
            selector: 'td:first-child'
        },
        responsive: true,
        autoWidth: false,
        processing: true,
        paging: true,
        pageLength: 25,
        language: {
            processing: '<div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div>'
        },
        columnDefs: [{
                targets: config.dtColumns.findIndex(col => col.className && col.className.includes('media_upload')),
                render: function(data, type, row) {
                    // When displaying the cell, wrap the image URL in an <img> tag.
                    if (type === 'display' && data) {
                        return '<img src="' + data + '" alt="Image" style="max-width:160px; height:auto;" />';
                    }
                    return data;
                }
            },
            {
                targets: config.dtColumns.findIndex(col => col.className && col.className.includes('featured_image')),
                render: function(data, type, row) {
                    // When displaying the cell, wrap the image URL in an <img> tag.
                    if (type === 'display' && data) {
                        return '<img src="' + data + '" alt="Image" style="max-width:160px; height:auto;" />';
                    }
                    return data;
                }            
        }]       
    });
    
    // add on functionality
    // Use event delegation to bind the click event to the media upload button
    $(document).on('click', '.media_uploader button', function(e) {
        e.preventDefault();
        
        // Get the field name associated with this button
        var fieldName = $(this).data('field');
        
        // Create a new media frame
        var mediaUploader = wp.media({
            title: 'Select or Upload Media',
            button: { text: 'Use this Media' },
            multiple: false  // Change to true if you want multiple selections
        });
        
        // When an image is selected, update the Editor field value
        mediaUploader.on('select', function() {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            // Set the value (typically the URL) to the Editor field
            editor.field(fieldName).val(attachment.url);
            
            var $fieldNode = $(editor.field(fieldName).node());
            $fieldNode.find('.media_preview img').attr('src', attachment.url);
        
            // Optionally, update the UI (e.g., display a preview) here if desired.
        });
        
        // Open the media uploader
        mediaUploader.open();
    });
    
});
