/home/coolpkct/www/websites/alylela.com/wp-content/plugins/wp-db-scout/assets/js/wds-clipboard.js
/**
 * WP DB Scout Clipboard JavaScript
 */

(function($) {
    'use strict';

    var WDSClipboard = {
        init: function() {
            this.checkClipboardSupport();
            this.bindEvents();
        },

        checkClipboardSupport: function() {
            // Check if Clipboard API is available
            this.hasClipboardAPI = navigator.clipboard && window.isSecureContext;
            
            // Check if execCommand is available
            this.hasExecCommand = document.queryCommandSupported && document.queryCommandSupported('copy');
            
            if (!this.hasClipboardAPI && !this.hasExecCommand) {
                console.warn('Clipboard operations may not work in this browser');
            }
        },

        bindEvents: function() {
            // Generic copy button handler
            $(document).on('click', '.wds-copy-btn', this.handleCopy.bind(this));
            
            // Copy table data
            $(document).on('click', '.wds-copy-table', this.copyTableData.bind(this));
            
            // Copy search results
            $(document).on('click', '.wds-copy-results', this.copySearchResults.bind(this));
        },

        handleCopy: function(e) {
            e.preventDefault();
            
            var $btn = $(e.currentTarget);
            var targetId = $btn.data('target');
            var $target = $('#' + targetId);
            
            if (!$target.length) {
                this.showError('Target element not found');
                return;
            }
            
            var textToCopy = $target.val() || $target.text();
            
            // Handle password fields
            if ($target.attr('type') === 'password') {
                // Temporarily show password
                $target.attr('type', 'text');
                textToCopy = $target.val();
                
                // Copy and restore
                this.copyToClipboard(textToCopy, $btn);
                
                // Restore password field after a brief delay
                setTimeout(function() {
                    $target.attr('type', 'password');
                }, 100);
            } else {
                this.copyToClipboard(textToCopy, $btn);
            }
        },

        copyToClipboard: function(text, $button) {
            var self = this;
            
            // Try modern Clipboard API first
            if (this.hasClipboardAPI) {
                navigator.clipboard.writeText(text).then(function() {
                    self.showSuccess($button);
                }).catch(function(err) {
                    // Fallback to execCommand
                    self.copyUsingExecCommand(text, $button);
                });
            } else {
                // Use execCommand fallback
                this.copyUsingExecCommand(text, $button);
            }
        },

        copyUsingExecCommand: function(text, $button) {
            // Create temporary textarea
            var $temp = $('<textarea>');
            $temp.css({
                position: 'fixed',
                top: '-9999px',
                left: '-9999px',
                width: '2em',
                height: '2em',
                padding: 0,
                border: 'none',
                outline: 'none',
                boxShadow: 'none',
                background: 'transparent'
            });
            
            $('body').append($temp);
            $temp.val(text).select();
            
            try {
                var successful = document.execCommand('copy');
                if (successful) {
                    this.showSuccess($button);
                } else {
                    this.showError('Copy failed. Please copy manually.');
                }
            } catch (err) {
                this.showError('Copy failed. Please copy manually.');
            }
            
            $temp.remove();
        },

        copyTableData: function(e) {
            e.preventDefault();
            
            var $btn = $(e.currentTarget);
            var $table = $btn.closest('.wds-result-table');
            var tableData = this.extractTableData($table);
            
            this.copyToClipboard(tableData, $btn);
        },

        copySearchResults: function(e) {
            e.preventDefault();
            
            var $btn = $(e.currentTarget);
            var searchTerm = $('.wds-searched-term').text();
            var resultsCount = $('.wds-results-count').text();
            
            var text = 'WP DB Scout Search Results\n';
            text += '==========================\n';
            text += 'Search Term: ' + searchTerm + '\n';
            text += 'Total Results: ' + resultsCount + '\n\n';
            
            // Collect all results
            $('.wds-result-table').each(function() {
                var $table = $(this);
                text += WDSClipboard.extractTableData($table) + '\n\n';
            });
            
            this.copyToClipboard(text, $btn);
        },

        extractTableData: function($table) {
            var tableName = $table.find('.table-name').text();
            var rows = $table.find('.table-rows').text();
            var size = $table.find('.table-size').text();
            var matches = $table.find('.match-count').text();
            
            var text = 'Table: ' + tableName + '\n';
            text += 'Rows: ' + rows + ' | Size: ' + size + ' | Matches: ' + matches + '\n';
            text += '---\n';
            
            // Add match details
            $table.find('.wds-match-item').each(function(index) {
                var $match = $(this);
                var rowId = $match.find('.row-id-value').text();
                
                text += 'Match #' + (index + 1);
                if (rowId) {
                    text += ' (Row ID: ' + rowId + ')';
                }
                text += '\n';
                
                // Get matched columns
                $match.find('.wds-matched-column').each(function() {
                    var colText = $(this).text();
                    text += '  ' + colText + '\n';
                });
            });
            
            return text;
        },

        showSuccess: function($button) {
            // Store original content
            var originalHtml = $button.html();
            var originalClass = $button.attr('class');
            
            // Show success state
            $button.html('<span class="dashicons dashicons-yes"></span> ' + wds_ajax.strings.copied);
            $button.addClass('button-primary wds-copy-success');
            
            // Show notification
            this.showNotification(wds_ajax.strings.copied, 'success');
            
            // Restore original state after 2 seconds
            setTimeout(function() {
                $button.html(originalHtml);
                $button.attr('class', originalClass);
            }, 2000);
        },

        showError: function(message) {
            this.showNotification(message || wds_ajax.strings.copy_failed, 'error');
        },

        showNotification: function(message, type) {
            // Remove existing notifications
            $('.wds-clipboard-notification').remove();
            
            // Create notification element
            var $notification = $('<div class="wds-clipboard-notification">');
            $notification.addClass(type === 'success' ? 'wds-notify-success' : 'wds-notify-error');
            $notification.text(message);
            
            // Style the notification
            $notification.css({
                position: 'fixed',
                top: '50px',
                right: '20px',
                padding: '10px 20px',
                background: type === 'success' ? '#4caf50' : '#f44336',
                color: '#fff',
                borderRadius: '4px',
                boxShadow: '0 2px 5px rgba(0,0,0,0.2)',
                zIndex: 100001,
                fontSize: '14px',
                fontWeight: 'bold',
                opacity: 0,
                transform: 'translateX(100px)'
            });
            
            // Add to body
            $('body').append($notification);
            
            // Animate in
            $notification.animate({
                opacity: 1,
                transform: 'translateX(0)'
            }, 300);
            
            // Auto-remove after 3 seconds
            setTimeout(function() {
                $notification.animate({
                    opacity: 0,
                    transform: 'translateX(100px)'
                }, 300, function() {
                    $(this).remove();
                });
            }, 3000);
        }
    };

    // Initialize when document is ready
    $(document).ready(function() {
        WDSClipboard.init();
    });

    // Export for global use
    window.WDSClipboard = WDSClipboard;

})(jQuery);