/**
 * ACF Field Copy/Paste Admin JavaScript
 *
 * Handles copy and paste functionality in the ACF field group editor
 */

(function ($) {
    'use strict';

    /**
     * ACF Copy/Paste Manager
     */
    var ACFCopyPaste = {

        /**
         * Initialize
         */
        init: function () {
            console.log('ACF Copy/Paste: Initializing...');

            // Check if ACF is available
            if (typeof acf === 'undefined') {
                console.warn('ACF Copy/Paste: ACF not loaded yet, waiting...');
                // Try again after a delay
                setTimeout(function () {
                    ACFCopyPaste.init();
                }, 500);
                return;
            }

            console.log('ACF Copy/Paste: ACF detected, adding buttons...');
            this.addFieldActionButtons();
            this.bindEvents();
        },

        /**
         * Add copy/paste buttons to field actions
         */
        addFieldActionButtons: function () {
            var self = this;

            console.log('ACF Copy/Paste: Setting up field action buttons...');

            // Use ACF's field load event
            acf.addAction('append_field', function ($field) {
                console.log('ACF Copy/Paste: append_field hook fired');
                self.addButtonsToField($field);
            });

            // Add to existing fields on page load
            acf.addAction('ready', function () {
                console.log('ACF Copy/Paste: ready hook fired');
                var $fields = $('.acf-field-object');
                console.log('ACF Copy/Paste: Found ' + $fields.length + ' field objects');

                $fields.each(function () {
                    self.addButtonsToField($(this));
                });

                // Add global "Paste Field" button for empty field groups
                self.addGlobalPasteButton();
            });

            // Fallback: manually find and process fields after delay
            setTimeout(function () {
                console.log('ACF Copy/Paste: Fallback - checking for fields manually');
                var $fields = $('.acf-field-object');
                console.log('ACF Copy/Paste: Fallback found ' + $fields.length + ' fields');

                if ($fields.length > 0) {
                    $fields.each(function () {
                        self.addButtonsToField($(this));
                    });
                }

                // Also ensure global paste button exists
                self.addGlobalPasteButton();
            }, 1000);
        },

        /**
         * Add global "Paste Field" button next to "+ Add Field"
         * This allows pasting into empty field groups
         */
        addGlobalPasteButton: function () {
            var self = this;

            // Don't add if already exists
            if ($('.acf-global-paste-btn').length > 0) {
                return;
            }

            // Brand color styling
            var btnStyle = 'margin-left: 8px; background: linear-gradient(135deg, #6167F8 0%, #9966FF 100%) !important; border: none !important; color: white !important;';

            // Method 1: Find "Add Field" button ONLY in the MAIN field group footer
            // NOT inside flexible content layouts
            var $mainFieldList = $('#acf-field-group-fields > .inside > .acf-field-list-wrap > .acf-tfoot');
            var $mainFooterAddBtn = $mainFieldList.find('.add-field');

            if ($mainFooterAddBtn.length && $mainFooterAddBtn.siblings('.acf-global-paste-btn').length === 0) {
                var $globalPasteBtn = $('<a href="#" class="acf-btn acf-global-paste-btn" style="' + btnStyle + '"><i class="acf-icon acf-icon-plus"></i>Paste Field</a>');
                $mainFooterAddBtn.after($globalPasteBtn);
                console.log('ACF Copy/Paste: Global paste button added to MAIN footer');
            }

            // Method 2: Add paste button in the empty state area (when no fields exist)
            var $emptyState = $('#acf-field-group-fields .no-fields-message-inner');
            if ($emptyState.length && $emptyState.find('.acf-empty-paste-btn').length === 0) {
                var $addFirstFieldBtn = $emptyState.find('.add-first-field');
                if ($addFirstFieldBtn.length) {
                    var $emptyPasteBtn = $('<a href="#" class="acf-btn acf-empty-paste-btn" style="' + btnStyle + '"><i class="acf-icon acf-icon-plus"></i>Paste Field</a>');
                    $addFirstFieldBtn.after($emptyPasteBtn);
                    console.log('ACF Copy/Paste: Paste button added to empty state');
                }
            }

            // Method 3: Add context-aware paste buttons inside flexible content layouts
            // These buttons will paste into the layout, not to the outer level
            $('.acf-field-object[data-type="flexible_content"]').each(function () {
                var $flexField = $(this);
                var flexFieldKey = $flexField.data('key');

                // Find all layout footers inside this flexible content
                $flexField.find('.acf-tfoot .add-field').each(function () {
                    var $addBtn = $(this);

                    // Skip if already has paste button
                    if ($addBtn.siblings('.acf-layout-paste-btn').length > 0) {
                        return;
                    }

                    var $layoutPasteBtn = $('<a href="#" class="acf-btn acf-layout-paste-btn" style="' + btnStyle + '" data-flex-parent="' + flexFieldKey + '"><i class="acf-icon acf-icon-plus"></i>Paste Field</a>');
                    $addBtn.after($layoutPasteBtn);
                    console.log('ACF Copy/Paste: Layout paste button added for flex field:', flexFieldKey);
                });
            });
        },

        /**
            /**
     * Add buttons to a specific field
     */
        addButtonsToField: function ($field) {
            // Ensure $field is a jQuery object
            $field = $($field);

            // Find the row-options div (where Edit, Duplicate, Move, Delete are)
            var $rowOptions = $field.find('.row-options');

            console.log('ACF Copy/Paste: Processing field', $field.data('key'));
            console.log('ACF Copy/Paste: Row options found:', $rowOptions.length);

            if ($rowOptions.length === 0) {
                // Skip fields without .row-options (nested fields, etc.)
                return;
            }

            // Check if buttons already exist
            if ($rowOptions.find('.acf-copy-field-btn').length > 0) {
                console.log('ACF Copy/Paste: Buttons already exist, skipping');
                return;
            }

            // Create copy button (styled as a link like Edit, Duplicate, etc.)
            var $copyBtn = $('<a class="copy-field acf-copy-field-btn" title="Copy field" href="#">Copy Field</a>');

            // Create paste button
            var $pasteBtn = $('<a class="paste-field acf-copy-paste-field-btn" title="Paste field below" href="#">Paste Field</a>');

            // Append buttons to row-options
            $rowOptions.append($copyBtn);
            $rowOptions.append($pasteBtn);

            console.log('ACF Copy/Paste: Buttons added successfully to row-options');
        },

        /**
         * Bind event handlers
         */
        bindEvents: function () {
            var self = this;

            // Copy field
            $(document).on('click', '.acf-copy-field-btn', function (e) {
                e.preventDefault();
                e.stopPropagation();

                var $field = $(this).closest('.acf-field-object');
                self.copyField($field);
            });

            // Paste field (after the target field at the same level)
            $(document).on('click', '.acf-copy-paste-field-btn', function (e) {
                e.preventDefault();
                e.stopPropagation();

                var $field = $(this).closest('.acf-field-object');
                self.pasteField($field);
            });

            // Global paste button (header) - paste at top level
            $(document).on('click', '.acf-global-paste-btn', function (e) {
                e.preventDefault();
                e.stopPropagation();
                self.pasteFieldGlobal();
            });

            // Empty state paste button - paste at top level
            $(document).on('click', '.acf-empty-paste-btn', function (e) {
                e.preventDefault();
                e.stopPropagation();
                self.pasteFieldGlobal();
            });

            // Layout paste button - paste INSIDE the flexible content layout
            $(document).on('click', '.acf-layout-paste-btn', function (e) {
                e.preventDefault();
                e.stopPropagation();
                var flexParentKey = $(this).data('flex-parent');
                console.log('Layout paste clicked, flex parent:', flexParentKey);
                self.pasteFieldIntoLayout(flexParentKey);
            });
        },

        /**
         * Copy field to clipboard
         */
        copyField: function ($field) {
            var fieldKey = $field.data('key');

            if (!fieldKey) {
                this.showNotice('error', cscfAcf.strings.copyError);
                return;
            }

            // Get field data via AJAX
            $.ajax({
                url: cscfAcf.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'cscf_acf_get_field',
                    nonce: cscfAcf.nonce,
                    field_key: fieldKey
                },
                success: function (response) {
                    if (response.success && response.data.field) {
                        // Show popup with JSON
                        var jsonString = JSON.stringify(response.data.field, null, 2);
                        ACFFieldJSONPopup.showCopyPopup(jsonString);
                    } else {
                        // Check if this is a pro-required error
                        if (response.data && response.data.requires_pro) {
                            // Show upgrade modal
                            ACFCopyPaste.showUpgradeModal(
                                response.data.field_type,
                                response.data.upgrade_url
                            );
                        } else {
                            // Show regular error notice
                            ACFCopyPaste.showNotice('error', response.data.message || cscfAcf.strings.copyError);
                        }
                    }
                },
                error: function () {
                    ACFCopyPaste.showNotice('error', cscfAcf.strings.copyError);
                }
            });
        },

        /**
         * Paste field from clipboard
         */
        pasteField: function ($field) {
            var self = this;
            var fieldKey = $field.data('key');

            // SMART PARENT DETECTION
            // 1. Check data-parent attribute (ACF sets this for nested fields)
            // 2. Check DOM hierarchy for parent .acf-field-object
            var dataParent = $field.data('parent');
            var parentFieldKey = null;

            // Method 1: data-parent attribute starts with 'field_' means it's inside a parent field
            if (dataParent && typeof dataParent === 'string' && dataParent.indexOf('field_') === 0) {
                parentFieldKey = dataParent;
                console.log('Parent detected from data-parent:', parentFieldKey);
            }

            // Method 2: Check DOM hierarchy - if this field is inside another .acf-field-object
            // This catches cases where data-parent might be a layout key or not set correctly
            if (!parentFieldKey) {
                var $parentFieldObject = $field.parents('.acf-field-object').first();
                if ($parentFieldObject.length) {
                    var parentKey = $parentFieldObject.data('key');
                    if (parentKey && parentKey.indexOf('field_') === 0) {
                        parentFieldKey = parentKey;
                        console.log('Parent detected from DOM hierarchy:', parentFieldKey);
                    }
                }
            }

            // Method 3: Check if inside a flexible content layout
            // Flexible content layouts have a different structure
            var $layoutContainer = $field.closest('.acf-field-setting-fc_layout');
            if ($layoutContainer.length) {
                // We're inside a flexible content layout
                // The parent should be the flexible content field
                var $flexField = $layoutContainer.closest('.acf-field-object[data-type="flexible_content"]');
                if ($flexField.length) {
                    parentFieldKey = $flexField.data('key');
                    console.log('Parent detected from flexible content:', parentFieldKey);
                }
            }

            // Get group key - try multiple methods
            var groupKey = null;

            // Method 1: From hidden input
            groupKey = $('input[name="acf_field_group[key]"]').val();

            // Method 2: Get post ID from URL and convert to group key
            if (!groupKey) {
                var urlParams = new URLSearchParams(window.location.search);
                var postId = urlParams.get('post') || $('input[name="post_ID"]').val();

                if (postId) {
                    // We'll pass the post ID and let PHP convert it to group key
                    groupKey = 'post_' + postId;
                }
            }

            console.log('=== PASTE FIELD DEBUG ===');
            console.log('Target Field Key:', fieldKey);
            console.log('Data Parent:', dataParent);
            console.log('Detected Parent Field Key:', parentFieldKey);
            console.log('Group Key:', groupKey);
            console.log('Will paste as:', parentFieldKey ? 'NESTED (inside ' + parentFieldKey + ')' : 'TOP-LEVEL');
            console.log('=========================');

            if (!groupKey) {
                this.showNotice('error', 'Could not determine field group');
                return;
            }

            // Show popup for JSON input
            ACFFieldJSONPopup.showPastePopup(function (jsonString) {
                // Parse JSON
                var fieldData;
                try {
                    fieldData = JSON.parse(jsonString);
                } catch (e) {
                    self.showNotice('error', 'Invalid JSON format');
                    return;
                }

                // Paste via AJAX
                $.ajax({
                    url: cscfAcf.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'cscf_acf_paste_field',
                        nonce: cscfAcf.nonce,
                        field_data: fieldData,
                        group_key: groupKey,
                        parent_field_key: parentFieldKey,  // NEW: Send parent field key if nested
                        after_field_key: fieldKey
                    },
                    success: function (response) {
                        console.log('Paste Response:', response);

                        if (response.success) {
                            // Check if we should reload (database save)
                            if (response.data.reload) {
                                self.showNotice('success', response.data.message);
                                setTimeout(function () {
                                    location.reload();
                                }, 600);
                                return;
                            }

                            if (response.data.field) {
                                var fieldData = response.data.field;

                                // Duplicate to create field template
                                var acfFieldObj = acf.getField($field);
                                if (acfFieldObj && acfFieldObj.duplicate) {
                                    acfFieldObj.duplicate();

                                    // Update new field with pasted data
                                    setTimeout(function () {
                                        var $new = $field.next('.acf-field-object');
                                        if ($new.length) {
                                            // Update field attributes
                                            $new.attr('data-key', fieldData.key);
                                            $new.attr('data-name', fieldData.name);
                                            $new.attr('data-type', fieldData.type);

                                            // Update field settings
                                            $new.find('.acf-field-setting-label input').val(fieldData.label || '').trigger('blur');
                                            $new.find('.acf-field-setting-name input').val(fieldData.name || '').trigger('blur');
                                            $new.find('.acf-field-setting-key input').val(fieldData.key || '');

                                            // Update field type
                                            if (fieldData.type) {
                                                $new.find('.acf-field-setting-type select').val(fieldData.type).trigger('change');
                                            }

                                            // Update visible label
                                            $new.find('.li-field-label').text(fieldData.label || fieldData.name);

                                            if (acf.unload) acf.unload.on();
                                        }
                                    }, 100);

                                    self.showNotice('success', '✓ Field pasted! Click "Update" to save');
                                }
                            }
                        } else {
                            console.error('Paste error:', response.data);
                            self.showNotice('error', '✕ Error: ' + (response.data.message || cscfAcf.strings.pasteError));
                        }
                    },
                    error: function () {
                        self.showNotice('error', cscfAcf.strings.pasteError);
                    }
                });
            });
        },

        /**
         * Paste field at top level of field group (global paste)
         * Used when pasting into empty field groups or via header button
         */
        pasteFieldGlobal: function () {
            var self = this;

            // Get group key - try multiple methods
            var groupKey = null;

            // Method 1: From hidden input
            groupKey = $('input[name="acf_field_group[key]"]').val();

            // Method 2: Get post ID from URL and convert to group key
            if (!groupKey) {
                var urlParams = new URLSearchParams(window.location.search);
                var postId = urlParams.get('post') || $('input[name="post_ID"]').val();

                if (postId) {
                    groupKey = 'post_' + postId;
                }
            }

            console.log('=== GLOBAL PASTE FIELD ===');
            console.log('Group Key:', groupKey);
            console.log('Will paste at TOP LEVEL of field group');
            console.log('==========================');

            if (!groupKey) {
                this.showNotice('error', 'Could not determine field group');
                return;
            }

            // Show popup for JSON input
            ACFFieldJSONPopup.showPastePopup(function (jsonString) {
                // Parse JSON
                var fieldData;
                try {
                    fieldData = JSON.parse(jsonString);
                } catch (e) {
                    self.showNotice('error', 'Invalid JSON format');
                    return;
                }

                // Paste via AJAX - no parent field key = top level
                $.ajax({
                    url: cscfAcf.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'cscf_acf_paste_field',
                        nonce: cscfAcf.nonce,
                        field_data: fieldData,
                        group_key: groupKey,
                        parent_field_key: ''  // Empty = paste at top level
                    },
                    success: function (response) {
                        console.log('Global Paste Response:', response);

                        if (response.success) {
                            if (response.data.reload) {
                                self.showNotice('success', response.data.message);
                                setTimeout(function () {
                                    location.reload();
                                }, 600);
                                return;
                            }
                            self.showNotice('success', '✓ Field pasted! Click "Update" to save');
                        } else {
                            console.error('Global paste error:', response.data);
                            self.showNotice('error', '✕ Error: ' + (response.data.message || cscfAcf.strings.pasteError));
                        }
                    },
                    error: function () {
                        self.showNotice('error', cscfAcf.strings.pasteError);
                    }
                });
            });
        },

        /**
         * Paste field INTO a flexible content layout (as a sub-field)
         */
        pasteFieldIntoLayout: function (flexParentKey) {
            var self = this;

            // Get group key
            var groupKey = $('input[name="acf_field_group[key]"]').val();
            if (!groupKey) {
                var urlParams = new URLSearchParams(window.location.search);
                var postId = urlParams.get('post') || $('input[name="post_ID"]').val();
                if (postId) {
                    groupKey = 'post_' + postId;
                }
            }

            console.log('=== LAYOUT PASTE FIELD ===');
            console.log('Group Key:', groupKey);
            console.log('Flex Parent Key:', flexParentKey);
            console.log('Will paste INSIDE flexible content layout');
            console.log('==========================');

            if (!groupKey) {
                this.showNotice('error', 'Could not determine field group');
                return;
            }

            if (!flexParentKey) {
                this.showNotice('error', 'Could not determine flexible content parent');
                return;
            }

            // Show popup for JSON input
            ACFFieldJSONPopup.showPastePopup(function (jsonString) {
                var fieldData;
                try {
                    fieldData = JSON.parse(jsonString);
                } catch (e) {
                    self.showNotice('error', 'Invalid JSON format');
                    return;
                }

                // Paste via AJAX with the flex parent key
                $.ajax({
                    url: cscfAcf.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'cscf_acf_paste_field',
                        nonce: cscfAcf.nonce,
                        field_data: fieldData,
                        group_key: groupKey,
                        parent_field_key: flexParentKey  // Paste inside flexible content
                    },
                    success: function (response) {
                        console.log('Layout Paste Response:', response);

                        if (response.success) {
                            if (response.data.reload) {
                                self.showNotice('success', response.data.message + ' (inside layout)');
                                setTimeout(function () {
                                    location.reload();
                                }, 600);
                                return;
                            }
                            self.showNotice('success', '✓ Field pasted inside layout! Click "Update" to save');
                        } else {
                            console.error('Layout paste error:', response.data);
                            self.showNotice('error', '✕ Error: ' + (response.data.message || cscfAcf.strings.pasteError));
                        }
                    },
                    error: function () {
                        self.showNotice('error', cscfAcf.strings.pasteError);
                    }
                });
            });
        },

        /**
         * Copy text to clipboard using Clipboard API
         */
        copyToClipboard: function (text) {
            var self = this;

            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(text).then(function () {
                    self.showNotice('success', cscfAcf.strings.copySuccess);
                }).catch(function () {
                    self.fallbackCopy(text);
                });
            } else {
                this.fallbackCopy(text);
            }
        },

        /**
         * Fallback copy method using textarea
         */
        fallbackCopy: function (text) {
            var $temp = $('<textarea>');
            $('body').append($temp);
            $temp.val(text).select();

            try {
                document.execCommand('copy');
                this.showNotice('success', cscfAcf.strings.copySuccess);
            } catch (err) {
                this.showNotice('error', cscfAcf.strings.copyError);
            }

            $temp.remove();
        },

        /**
         * Read from clipboard using Clipboard API
         */
        readFromClipboard: function (callback) {
            if (navigator.clipboard && navigator.clipboard.readText) {
                navigator.clipboard.readText().then(function (text) {
                    callback(text);
                }).catch(function () {
                    // Fallback: prompt user
                    var text = prompt('Paste field data:');
                    callback(text);
                });
            } else {
                // Fallback: prompt user
                var text = prompt('Paste field data:');
                callback(text);
            }
        },

        /**
         * Show notice message
         */
        showNotice: function (type, message) {
            // Remove any existing notices
            $('.acf-copy-paste-notice').remove();

            var icon = type === 'success' ? '✓' : '✕';
            var bgColor = type === 'success' ? '#46b450' : '#dc3232';

            var $notice = $('<div class="acf-copy-paste-notice"></div>');
            $notice.html('<span class="notice-icon">' + icon + '</span><span class="notice-text">' + message + '</span>');
            $notice.css({
                'position': 'fixed',
                'top': '32px',
                'right': '20px',
                'z-index': '999999',
                'background': bgColor,
                'color': 'white',
                'padding': '15px 20px',
                'border-radius': '4px',
                'box-shadow': '0 3px 10px rgba(0,0,0,0.3)',
                'font-size': '14px',
                'font-weight': '500',
                'display': 'flex',
                'align-items': 'center',
                'gap': '10px',
                'min-width': '300px',
                'opacity': '0',
                'transform': 'translateY(-20px)',
                'transition': 'all 0.3s ease'
            });

            $notice.find('.notice-icon').css({
                'font-size': '20px',
                'font-weight': 'bold'
            });

            // Add to body
            $('body').append($notice);

            // Trigger animation
            setTimeout(function () {
                $notice.css({
                    'opacity': '1',
                    'transform': 'translateY(0)'
                });
            }, 10);

            // Auto-remove after 4 seconds
            setTimeout(function () {
                $notice.css({
                    'opacity': '0',
                    'transform': 'translateY(-20px)'
                });
                setTimeout(function () {
                    $notice.remove();
                }, 300);
            }, 4000);
        },

        /**
         * Show upgrade modal for pro features
         */
        showUpgradeModal: function (fieldType, upgradeUrl) {
            // Remove existing modal if any
            $('.cnc-acf-upgrade-modal-overlay').remove();

            // Get field type label
            var fieldLabels = {
                'select': 'Select',
                'checkbox': 'Checkbox',
                'radio': 'Radio Button',
                'button_group': 'Button Group',
                'true_false': 'True / False',
                'wysiwyg': 'WYSIWYG Editor',
                'repeater': 'Repeater',
                'group': 'Group',
                'flexible_content': 'Flexible Content',
                'relationship': 'Relationship',
                'post_object': 'Post Object',
                'taxonomy': 'Taxonomy'
            };
            var fieldLabel = fieldLabels[fieldType] || fieldType.replace(/_/g, ' ').replace(/\b\w/g, function (l) { return l.toUpperCase(); });

            // Create modal HTML with new two-column layout
            var modalHTML = '<div class="cnc-acf-upgrade-modal-overlay active">' +
                '<div class="cnc-acf-upgrade-modal">' +
                '<div class="cnc-acf-upgrade-modal-header">' +
                '<h2>Upgrade to Pro</h2>' +
                '<button class="cnc-acf-upgrade-modal-close" aria-label="Close">×</button>' +
                '</div>' +
                '<div class="cnc-acf-upgrade-modal-body">' +
                '<div class="cnc-acf-upgrade-modal-icon">🔒</div>' +
                '<div class="cnc-acf-upgrade-modal-content">' +
                '<div class="cnc-acf-upgrade-modal-message">' +
                '<h3>Pro Feature Required</h3>' +
                '<p>The <span class="cnc-acf-upgrade-field-type">' + fieldLabel + '</span> field type is only available in the Pro version.</p>' +
                '</div>' +
                '<div class="cnc-acf-upgrade-features">' +
                '<h4>Pro Version Includes:</h4>' +
                '<ul>' +
                '<li>All Advanced Field Types</li>' +
                '<li>Repeater, Group & Flexible Content</li>' +
                '<li>Gallery, Relationship & Taxonomy Fields</li>' +
                '<li>Priority Support</li>' +
                '<li>Lifetime Updates</li>' +
                '</ul>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="cnc-acf-upgrade-modal-footer">' +
                '<a href="' + upgradeUrl + '" target="_blank" class="cnc-acf-btn cnc-acf-btn-primary">' +
                'Upgrade to Pro →' +
                '</a>' +
                '<button class="cnc-acf-btn cnc-acf-btn-secondary cnc-acf-modal-close-btn">' +
                'Maybe Later' +
                '</button>' +
                '</div>' +
                '</div>' +
                '</div>';


            // Append to body
            $('body').append(modalHTML);

            // Close modal on button click
            $(document).on('click', '.cnc-acf-upgrade-modal-close, .cnc-acf-modal-close-btn', function () {
                $('.cnc-acf-upgrade-modal-overlay').removeClass('active');
                setTimeout(function () {
                    $('.cnc-acf-upgrade-modal-overlay').remove();
                }, 300);
            });

            // Prevent closing when clicking inside modal
            $(document).on('click', '.cnc-acf-upgrade-modal', function (e) {
                e.stopPropagation();
            });
        }
    };

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

})(jQuery);
