/**
 * PC Form Builder Admin Scripts
 *
 * JavaScript functionality for the form builder admin interface.
 *
 * @package PCFormBuilder
 */

(function($) {
    'use strict';

    var PCFB_Admin = {
        fieldIndex: 0,
        deletedFields: [],

        init: function() {
            this.initFieldTypeButtons();
            this.initFieldToggle();
            this.initFieldDelete();
            this.initDeleteModal();
            this.initFormBuilder();
        },

        initFieldTypeButtons: function() {
            var self = this;

            $('.pcfb-add-field-btn').on('click', function(e) {
                e.preventDefault();
                var fieldType = $(this).data('field-type');
                self.addField(fieldType);
            });
        },

        addField: function(fieldType) {
            var self = this;
            var container = $('#pcfb-fields-container');

            if (container.find('.pcfb-empty-fields').length > 0) {
                container.find('.pcfb-empty-fields').remove();
            }

            var fieldIndex = this.getNextFieldIndex();
            var nonce = pcfbAdminVars.nonce;

            $.ajax({
                url: pcfbAdminVars.ajaxurl,
                type: 'POST',
                data: {
                    action: 'pcfb_add_field',
                    field_type: fieldType,
                    field_index: fieldIndex,
                    nonce: nonce
                },
                success: function(response) {
                    if (response.success) {
                        container.append(response.data.html);
                        self.reindexFields();
                        self.initFieldToggle();
                        self.initFieldDelete();
                        self.updateLabelOnChange();
                    }
                },
                error: function() {
                    alert(pcfbAdminVars.i18n.confirmDeleteField);
                }
            });
        },

        getNextFieldIndex: function() {
            var maxIndex = 0;
            $('#pcfb-fields-container [name^="fields["]').each(function() {
                var match = $(this).attr('name').match(/fields\[(\d+)\]/);
                if (match && parseInt(match[1]) > maxIndex) {
                    maxIndex = parseInt(match[1]);
                }
            });
            return maxIndex + 1;
        },

        reindexFields: function() {
            var fields = $('#pcfb-fields-container .pcfb-field-item');
            fields.each(function(index) {
                var field = $(this);
                field.find('[name^="fields["]').each(function() {
                    var name = $(this).attr('name');
                    var newName = name.replace(/fields\[\d+\]/, 'fields[' + index + ']');
                    $(this).attr('name', newName);
                });
            });
        },

        initFieldToggle: function() {
            $('.pcfb-toggle-field').off('click').on('click', function(e) {
                e.preventDefault();
                $(this).closest('.pcfb-field-item').toggleClass('collapsed');
            });
        },

        initFieldDelete: function() {
            var self = this;

            $('.pcfb-delete-field').off('click').on('click', function(e) {
                e.preventDefault();
                var fieldItem = $(this).closest('.pcfb-field-item');
                var fieldId = fieldItem.data('field-id');

                if (confirm(pcfbAdminVars.i18n.confirmDeleteField)) {
                    if (fieldId && fieldId !== 'new') {
                        self.deletedFields.push(fieldId);
                        $('<input type="hidden" name="deleted_fields[]" value="' + fieldId + '">').appendTo('#pcfb-form-builder');
                    }
                    fieldItem.fadeOut(300, function() {
                        $(this).remove();
                        self.reindexFields();
                        self.checkEmptyFields();
                    });
                }
            });
        },

        checkEmptyFields: function() {
            var container = $('#pcfb-fields-container');
            if (container.find('.pcfb-field-item').length === 0) {
                container.html('<div class="pcfb-empty-fields"><p>' + pcfbAdminVars.i18n.fieldLabel + '</p></div>');
            }
        },

        updateLabelOnChange: function() {
            $('.pcfb-field-label-input').off('input').on('input', function() {
                var label = $(this).val();
                var fieldItem = $(this).closest('.pcfb-field-item');
                var fieldName = fieldItem.find('.pcfb-field-name-display');
                var baseName = this.getAttribute('name').match(/fields\[(\d+)\]\[field_label\]/);
                if (baseName) {
                    var slug = label.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '');
                    if (slug === '') {
                        slug = 'field_' + baseName[1];
                    }
                    fieldName.text(slug);
                    var hiddenName = fieldItem.find('input[name^="fields["][name$="[field_name]"]');
                    hiddenName.val(slug);
                }
            });
        },

        initDeleteModal: function() {
            var self = this;

            $(document).on('click', '.pcfb-delete-form, .pcfb-delete-form-btn, .pcfb-delete-form-link', function(e) {
                if (e.target.tagName === 'BUTTON' || $(this).hasClass('pcfb-delete-form') || $(this).hasClass('pcfb-delete-form-btn') || $(this).hasClass('pcfb-delete-form-link')) {
                    e.preventDefault();
                    var formId = $(this).data('form-id');
                    var formName = $(this).data('form-name');

                    $('#pcfb-delete-form-id').val(formId);
                    $('#pcfb-delete-form-name').text(formName);
                    $('#pcfb-delete-modal').addClass('active').show();
                }
            });

            $('.pcfb-modal-close, .pcfb-modal-cancel').on('click', function(e) {
                e.preventDefault();
                $('#pcfb-delete-modal').removeClass('active').hide();
            });

            $('#pcfb-delete-modal').on('click', function(e) {
                if ($(e.target).is('#pcfb-delete-modal')) {
                    $(this).removeClass('active').hide();
                }
            });
        },

        initFormBuilder: function() {
            var self = this;

            if ($('#pcfb-fields-container').length > 0) {
                $('#pcfb-fields-container').sortable({
                    handle: '.pcfb-field-header',
                    placeholder: 'pcfb-field-placeholder',
                    tolerance: 'pointer',
                    update: function() {
                        self.reindexFields();
                    }
                });
            }

            if ($('#pcfb-sections-container').length > 0) {
                $('#pcfb-sections-container').sortable({
                    handle: '.pcfb-section-header',
                    placeholder: 'pcfb-section-placeholder',
                    tolerance: 'pointer'
                });
            }

            $('#pcfb-add-section').on('click', function(e) {
                e.preventDefault();
                self.addSection();
            });

            $('#pcfb-form-builder').on('submit', function(e) {
                var formName = $('#form-name').val().trim();
                if (!formName) {
                    e.preventDefault();
                    alert(pcfbAdminVars.i18n.fieldLabel);
                    $('#form-name').focus();
                    return false;
                }

                var hasRequiredFields = false;
                $('.pcfb-field-item').each(function() {
                    if ($(this).find('[name*="[validation_rules][required]"]').is(':checked')) {
                        hasRequiredFields = true;
                    }
                });
            });
        },

        addSection: function() {
            var container = $('#pcfb-sections-container');
            var sectionCount = container.find('.pcfb-section-box').length;
            var sectionHtml = '<div class="pcfb-section-box" data-section-id="new-' + sectionCount + '">' +
                '<div class="pcfb-section-header">' +
                '<span class="dashicons dashicons-menu"></span>' +
                '<span class="pcfb-section-title">Section ' + (sectionCount + 1) + '</span>' +
                '</div>' +
                '<div class="pcfb-section-content">' +
                '<input type="hidden" name="sections[' + sectionCount + '][id]" value="">' +
                '<input type="hidden" name="sections[' + sectionCount + '][title]" value="Section ' + (sectionCount + 1) + '">' +
                '<p class="description">Drag fields into this section or click to configure.</p>' +
                '</div>' +
                '</div>';
            container.append(sectionHtml);
        }
    };

    $(document).ready(function() {
        PCFB_Admin.init();
    });

})(jQuery);
