(function($) {
    'use strict';

    // Determine REST API base URL and nonce with safe fallbacks
    var apiBase = (typeof unlockafeDatabaseList !== 'undefined' && unlockafeDatabaseList.restUrl)
        ? unlockafeDatabaseList.restUrl
        : (typeof wpApiSettings !== 'undefined' && wpApiSettings.root
            ? wpApiSettings.root + 'unlockafe-addons/v1/'
            : '/wp-json/unlockafe-addons/v1/');

    if (apiBase.slice(-1) !== '/') {
        apiBase += '/';
    }

    var apiNonce = (typeof unlockafeDatabaseList !== 'undefined' && unlockafeDatabaseList.nonce)
        ? unlockafeDatabaseList.nonce
        : (typeof wpApiSettings !== 'undefined' && wpApiSettings.nonce ? wpApiSettings.nonce : '');

    /**
     * Initialize Database List Widget
     */
    function initDatabaseList($scope) {
        var $widget = $scope.find('.unlockafe-database-list');
        
        if ($widget.length === 0) {
            return;
        }

        var showTables = $widget.data('show-tables') === 'yes';
        var showFields = $widget.data('show-fields') === 'yes';
        var showApiKeys = $widget.data('show-api-keys') === 'yes';

        // Load database tables
        if (showTables) {
            loadDatabaseTables($widget);
        }

        // Load API keys
        if (showApiKeys) {
            loadApiKeys($widget);
        }

        // Handle table click to show fields
        $widget.on('click', '.db-table-item', function() {
            var tableName = $(this).data('table');
            if (tableName && showFields) {
                loadTableFields($widget, tableName);
            }
        });

        // Handle API key generation
        $widget.on('click', '.generate-api-key-btn', function() {
            generateApiKey($widget);
        });

        // Handle API key deletion
        $widget.on('click', '.delete-api-key-btn', function() {
            var apiKey = $(this).data('api-key') || $(this).attr('data-api-key');
            if (apiKey) {
                deleteApiKey($widget, apiKey);
            }
        });

        // Handle copy API key
        $widget.on('click', '.copy-api-key-btn', function() {
            var $btn = $(this);
            var key = $btn.attr('data-copy') || $btn.data('copy') || '';
            var $status = $btn.siblings('.copy-status');
            if (!key) return;

            function showCopied() {
                if ($status.length) {
                    $status.stop(true, true).show();
                    setTimeout(function(){ $status.fadeOut(200); }, 1200);
                }
            }

            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(key).then(function() {
                    showCopied();
                }).catch(function() {
                    fallbackCopy(key);
                    showCopied();
                });
            } else {
                fallbackCopy(key);
                showCopied();
            }

            function fallbackCopy(text) {
                var textarea = document.createElement('textarea');
                textarea.value = text;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    document.execCommand('copy');
                } catch (err) {
                    console.error('Fallback copy failed:', err);
                }
                document.body.removeChild(textarea);
            }
        });
    }

    /**
     * Load database tables
     */
    function loadDatabaseTables($widget) {
        $.ajax({
            url: apiBase + 'database/list',
            method: 'GET',
            beforeSend: function(xhr) {
                if (apiNonce) {
                    xhr.setRequestHeader('X-WP-Nonce', apiNonce);
                }
            },
            success: function(response) {
                if (response.success && response.tables) {
                    var html = '<ul class="db-tables-ul">';
                    response.tables.forEach(function(table) {
                        html += '<li class="db-table-item" data-table="' + table.name + '">';
                        html += '<strong>' + table.name + '</strong>';
                        html += '<span class="field-count">' + table.columns.length + ' fields</span>';
                        html += '</li>';
                    });
                    html += '</ul>';
                    $widget.find('.db-tables-list').html(html);
                }
            },
            error: function() {
                $widget.find('.db-tables-list').html('<p class="error">Failed to load tables</p>');
            }
        });
    }

    /**
     * Load table fields
     */
    function loadTableFields($widget, tableName) {
        $.ajax({
            url: apiBase + 'database/list',
            method: 'GET',
            beforeSend: function(xhr) {
                if (apiNonce) {
                    xhr.setRequestHeader('X-WP-Nonce', apiNonce);
                }
            },
            success: function(response) {
                if (response.success && response.tables) {
                    var table = response.tables.find(function(t) {
                        return t.name === tableName;
                    });
                    
                    if (table) {
                        var html = '<table class="fields-table"><thead><tr>';
                        html += '<th>Field</th>';
                        html += '<th>Type</th>';
                        html += '<th>Null</th>';
                        html += '<th>Key</th>';
                        html += '</tr></thead><tbody>';
                        
                        table.columns.forEach(function(col) {
                            html += '<tr>';
                            html += '<td><strong>' + col.field + '</strong></td>';
                            html += '<td>' + col.type + '</td>';
                            html += '<td>' + col.null + '</td>';
                            html += '<td>' + (col.key || '-') + '</td>';
                            html += '</tr>';
                        });
                        
                        html += '</tbody></table>';
                        $widget.find('.db-fields-list').html(html);
                    }
                }
            }
        });
    }

    /**
     * Load API keys
     */
    function loadApiKeys($widget) {
        $.ajax({
            url: apiBase + 'database/api-keys',
            method: 'GET',
            beforeSend: function(xhr) {
                if (apiNonce) {
                    xhr.setRequestHeader('X-WP-Nonce', apiNonce);
                }
            },
            success: function(response) {
                if (response.success && response.keys) {
                    if (response.keys.length === 0) {
                        $widget.find('.api-keys-container').html('<p>No API keys found. Generate one using the button above.</p>');
                    } else {
                        var html = '';
                        response.keys.forEach(function(keyData) {
                            var fullKey = keyData.full_key || keyData.masked_key;
                            html += '<div class="api-key-item" data-api-key="' + (keyData.full_key || '') + '">';
                            html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">';
                            html += '<strong>' + (keyData.name || 'Unnamed Key') + '</strong>';
                            html += '<button type="button" class="delete-api-key-btn" data-api-key="' + (keyData.full_key || '') + '" title="Delete">×</button>';
                            html += '</div>';
                            html += '<div class="api-key-value" data-full-key="' + (keyData.full_key || '') + '">' + (keyData.full_key || keyData.masked_key) + '</div>';
                            html += '<div style="margin-top:8px;">';
                            html += '<button type="button" class="copy-api-key-btn" data-copy="' + (keyData.full_key || keyData.masked_key) + '">Copy API Key</button>';
                            html += '<span class="copy-status" style="margin-left:10px;font-size:12px;color:#10b981;display:none;">Copied!</span>';
                            html += '</div>';
                            html += '<p style="margin-top: 8px; font-size: 12px; color: #6b7280;">';
                            html += 'Status: ' + (keyData.active ? 'Active' : 'Inactive');
                            if (keyData.created) {
                                html += ' | Created: ' + keyData.created;
                            }
                            html += '</p>';
                            html += '</div>';
                        });
                        $widget.find('.api-keys-container').html(html);
                    }
                }
            },
            error: function() {
                $widget.find('.api-keys-container').html('<p class="error">Failed to load API keys</p>');
            }
        });
    }

    /**
     * Generate API key
     */
    function generateApiKey($widget) {
        var keyName = prompt('Enter a name for this API key:');
        if (!keyName || keyName.trim() === '') {
            alert('Name is required');
            return;
        }
        
        $.ajax({
            url: apiBase + 'database/generate-key',
            method: 'POST',
            beforeSend: function(xhr) {
                if (apiNonce) {
                    xhr.setRequestHeader('X-WP-Nonce', apiNonce);
                }
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({name: keyName.trim()}),
            success: function(response) {
                if (response.success) {
                    var html = '';
                    html += '<div class="api-key-item" data-api-key="' + response.api_key + '">';
                    html += '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;">';
                    html += '<strong>' + (response.name || 'Unnamed Key') + '</strong>';
                    html += '<button type="button" class="delete-api-key-btn" data-api-key="' + response.api_key + '" title="Delete">×</button>';
                    html += '</div>';
                    html += '<div class="api-key-value" data-full-key="' + response.api_key + '">' + response.api_key + '</div>';
                    html += '<div style="margin-top:8px;">';
                    html += '<button type="button" class="copy-api-key-btn" data-copy="' + response.api_key + '">Copy API Key</button>';
                    html += '<span class="copy-status" style="margin-left:10px;font-size:12px;color:#10b981;display:none;">Copied!</span>';
                    html += '</div>';
                    html += '<p style="margin-top: 8px; font-size: 12px; color: #6b7280;">Copy this key now. It will be shown in the list below.</p>';
                    html += '</div>';
                    
                    $widget.find('.api-keys-container').prepend(html);
                    
                    setTimeout(function(){ loadApiKeys($widget); }, 500);
                }
            },
            error: function() {
                alert('Failed to generate API key');
            }
        });
    }

    /**
     * Delete API key
     */
    function deleteApiKey($widget, apiKey) {
        if (!confirm('Are you sure you want to delete this API key?')) {
            return;
        }
        
        $.ajax({
            url: apiBase + 'database/api-keys/delete',
            method: 'DELETE',
            beforeSend: function(xhr) {
                if (apiNonce) {
                    xhr.setRequestHeader('X-WP-Nonce', apiNonce);
                }
                xhr.setRequestHeader('Content-Type', 'application/json');
            },
            data: JSON.stringify({api_key: apiKey}),
            success: function(response) {
                if (response.success) {
                    $widget.find('.api-key-item[data-api-key="' + apiKey + '"]').fadeOut(300, function() {
                        $(this).remove();
                        if ($widget.find('.api-key-item').length === 0) {
                            loadApiKeys($widget);
                        }
                    });
                }
            },
            error: function() {
                alert('Failed to delete API key');
            }
        });
    }

    /**
     * Copy handlers
     */
    function tryCopyToClipboard(text, $widget) {
        if (!text) return;
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).catch(function() {
                fallbackCopy(text);
            });
        } else {
            fallbackCopy(text);
        }
    }

    function fallbackCopy(text) {
        var $tmp = $('<textarea>').val(text).appendTo('body').select();
        try { document.execCommand('copy'); } catch(e) {}
        $tmp.remove();
    }

    $(document).on('click', '.copy-api-key-btn', function() {
        var $btn = $(this);
        var key = $btn.attr('data-copy') || '';
        var $status = $btn.siblings('.copy-status');
        if (!key) return;
        tryCopyToClipboard(key);
        if ($status.length) {
            $status.stop(true, true).show();
            setTimeout(function(){ $status.fadeOut(200); }, 1200);
        }
    });

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-database-list.default', initDatabaseList);
    });

    // Also initialize on document ready
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-database-list').each(function() {
            var $scope = $(this);
            initDatabaseList($scope);
        });
    });

})(jQuery);
