(function($){
    $.pixeColorDisplayText = true;

    $.pixePluginOption = {
        'layout': {
            'page-margin': {
                'title': 'Page Margin',
                'type': 'margin',
                'enable-sync': false,
                'description-top': 'Outer spacing around the page content. Link to edit all sides together.'
            },
            'page-type': {
                'title': 'Page Type',
                'type': 'combobox',
                'options': {
                    '': 'Full Width',
                    'boxed': 'Boxed Width'
                },
                'with-default': false,
                'width': '1-1',
                'description-top': 'Choose how content is constrained within the viewport.'
            },
            'boxed-width': {
                'title': 'Box Width',
                'type': 'range-input',
                'range': 'box-width',
                'width': '1-1',
                'description-top': 'Maximum width of the box frame area.',
                'condition': { 'page-type': 'boxed' }
            },
            'content-width': {
                'title': 'Content Width',
                'type': 'range-input',
                'range': 'content-width',
                'width': '1-1',
                'variable-type': 'none',
                'description-top': 'Maximum width of the inner content column.'
            },
            'bg-section-open': {
                'title': 'Background',
                'type': 'div-open',
                'description-top': 'Body and content background colors. Leave empty to inherit from the theme.'
            },
            'body-background': {
                'title': 'Body BG Color',
                'type': 'colordisplay',
                'width': '1-2'
            },
            'boxed-background': {
                'title': 'Boxed BG Color',
                'type': 'colordisplay',
                'width': '1-2',
                'condition': { 'page-type': 'boxed' }
            },
            'content-background': {
                'title': 'Content BG Color',
                'type': 'colordisplay',
                'width': '1-2',
                'condition': { 'page-type': '' }
            },
            'bg-section-close': {
                'type': 'div-close'
            },
            'overflow': {
                'title': 'Overflow',
                'type': 'combobox',
                'options': 'overflow',
                'width': '1-1',
                'description-top': 'How content that exceeds the page bounds is handled.'
            },
            'responsive-section-open': {
                'title': 'Responsive Breakouts',
                'type': 'div-open',
                'description-top': 'Viewport widths at which the tablet and mobile layouts kick in.'
            },
            'tablet-breakout': {
                'title': 'Tablet Breakout',
                'type': 'range-input',
                'suffix-text': 'px',
                'min': '600',
                'max': '1200',
                'width': '1-2',
                'variable-type': 'none',
            },
            'mobile-breakout': {
                'title': 'Mobile Breakout',
                'type': 'range-input',
                'suffix-text': 'px',
                'min': '300',
                'max': '900',
                'width': '1-2',
                'variable-type': 'none',
            },
            'responsive-section-close': {
                'type': 'div-close'
            },
        },
        'general': {
            'builder-post-types': {
                'title': 'Post Types',
                'type': 'checkbox-multiple-raw',
                'options': pixeData.postTypes,
                'width': '1-1',
                'extra-class': 'pixe-style-block pixe-custom-checkbox',
                'description-top': 'Content types that get the “Edit with PixeBuilder” button.'
            },
            'builder-user-role': {
                'title': 'Access by User Role',
                'type': 'checkbox-multiple-raw',
                'callback': 'user-role',
                'width': '1-1',
                'extra-class': 'pixe-style-block pixe-custom-checkbox',
                'condition': { 'callback': 'pixe-callback' },
                'description-top': 'Roles allowed to open and edit pages in PixeBuilder.'
            },
            'upload-file-type': {
                'title': 'Upload Permissions',
                'type': 'checkbox-multiple-raw',
                'options': {
                    'svg': '<span class="pixe-title" >Enable SVG Uploads</span>' + 
                           '<span class="pixe-caption" >Allows uploading SVG files. Required for SVG icons and graphics.</span>',
                    'json': '<span class="pixe-title" >Enable JSON uploads</span>' + 
                            '<span class="pixe-caption" >Allows uploading JSON files. Required for importing custom blocks and pages.</span>',
                    'fonts': '<span class="pixe-title" >Enable font uploads</span>' + 
                            '<span class="pixe-caption" >Allows uploading custom fonts. Supports WOFF and WOFF2 formats.</span>',
                    
                },
                'width': '1-1',
                'extra-class': 'pixe-custom-checkbox',
                'description-top': 'These file types carry security risks — enable only for trusted roles.'
            },
            'context-menu': {
                'title': 'Context Menu',
                'type': 'checkbox',
                'default': 'yes',
                'width': '1-1',
                'description-top': 'Show a right-click context menu when editing elements in the builder.'
            },
            'smooth-anchor-scroll': {
                'title': 'Smooth Scroll to Anchor',
                'type': 'checkbox',
                'default': 'yes',
                'width': '1-1',
                'description-top': 'Animate page scrolling when navigating to anchor links.'
            },
        },
        'page-transition': {
            'enable-preloader': {
                'title': 'Enable Preloader',
                'type': 'checkbox',
                'width': '1-1',
                'description-top': 'Display an animated loading screen before each page is revealed.'
            },
            'type': {
                'title': 'Preloader Type',
                'type': 'combobox',
                'options': {
                    'none': 'None',
                    'css': 'Css Animation',
                    'image': 'Image',
                    'icon': 'Icon'
                },
                'width': '1-1',
                'with-default': false,
                'class': 'pixe-type-bottom pixe-0h-description',
                'description-top': 'The animation shown while the next page loads in the background.'
            },
            'style': {
                'title': '&nbsp;',
                'type': 'combobox',
                'class': 'pixe-preload-icon-combobox',
                'popup-class': 'pixe-preload-icon-popup',
                'options': 'preloadIcon',
                'width': '1-1',
                'hide-reset': true,
                'class': 'pixe-type-connect pixe-type-bottom',
                'condition': {'type': 'css'}
            },
            'image': {
                'title': '&nbsp;',
                'type': 'upload',
                'width': '1-1',
                'class': 'pixe-type-connect pixe-type-bottom',
                'condition': {'type': 'image'}
            },
            'icon': {
                'title': '&nbsp;',
                'type': 'upload',
                'convert-svg': true,
                'width': '1-1',
                'class': 'pixe-type-connect pixe-type-bottom',
                'condition': {'type': 'icon'}
            },
            'button': {
                'title': '&nbsp;',
                'type': 'button',
                'icon': 'play',
                'button-text': pixei18n.button.preview,
                'button-class': 'pixe-type-white',
                'button-callback': 'preview-preload',
                'class': 'pixe-type-connect',
                'width': '1-1'
            },
            'style-open': {
                'title': 'Preloader Style',
                'type': 'div-open',
                'condition': {'type': ['css', 'image', 'icon']}
            },
            'size': {
                'title': 'Size',
                'width': '1-2',
                'type': 'range-input',
                'range': 'font-size',
                'condition': {'type': 'css'}
            },
            'speed': {
                'title': 'Speed (ms)',
                'type': 'range-input',
                'min': 100,
                'max': 1000, 
                'width': '1-2',
                'condition': {'type': 'css'}
            },
            'color': {
                'title': 'Color',
                'type': 'colordisplay',
                'color-type': 'plain-color',
                'width': '1-2',
                'condition': {'type': 'css'}
            },
            'icon-width': {
                'title': 'Width',
                'type': 'range-input',
                'range': 'font-size',
                'width': '1-2',
                'condition': {'type': ['image', 'icon']}
            },
            'icon-color': {
                'title': 'Icon & Svg Color',
                'type': 'colordisplay',
                'color-type': 'plain-color',
                'width': '1-2',
                'condition': {'type': 'icon'}
            },
            'icon-opacity': {
                'title': 'Fade Opacity',
                'type': 'range-input',
                'min': 0,
                'max': 100,
                'default': 100,
                'suffix-text': '%',
                'width': '1-2',
                'condition': {'type': ['image']}
            },
            'style-close': {
                'type': 'div-close',
            },
            'icon-effect': {
                'title': 'Icon Animation Effect',
                'type': 'combobox',
                'width': '1-1',
                'options': 'animationEffects',
                'condition': {'type': ['image', 'icon']}
            },
            'icon-timing-open': {
                'title': 'Icon Animation Timing',
                'type': 'div-open',
                'condition': {'type': ['image', 'icon']}
            },
            'icon-duration': {
                'title': 'Duration (ms)',
                'type': 'range-input',
                'min': 0,
                'max': 10000,
                'width': '1-2'
            },
            'icon-delay': {
                'title': 'Delay (ms)',
                'type': 'range-input',
                'min': 0,
                'max': 10000,
                'width': '1-2'
            },
            'icon-timing-close': {
                'type': 'div-close',
                'condition': {'type': ['image', 'icon']}
            },
            'overlay-color': {
                'title': 'Overlay Color',
                'type': 'colordisplay',
                'width': '1-1',
                'description-top': 'Background color of the transition overlay that covers the screen.'
            },
            'overlay-image': {
                'title': 'Overlay Image',
                'type': 'upload',
                'width': '1-1',
                'description-top': 'Choose how content is constrained within the viewport.'
            },
            'effect-div-open': {
                'title': 'Animation Effect',
                'type': 'div-open',
                'description-top': 'The entrance and exit animations applied during page transitions.'
            },
            'in-effect': {
                'title': 'Entrance Effect',
                'type': 'combobox',
                'options': 'transEffectsOut',
                'width': '1-2'
            },
            'out-effect': {
                'title': 'Exit Effect',
                'type': 'combobox',
                'options': 'transEffectsIn',
                'width': '1-2'
            },
            'effect-div-close': {
                'type': 'div-close'
            },
            'timing-div-open': {
                'title': 'Animation Timing',
                'type': 'div-open',
                'description-top': 'Control the speed and delay of the page transition animation.'
            },
            'duration': {
                'title': 'Speed (ms)',
                'type': 'range-input',
                'min': 100,
                'max': 1000, 
                'width': '1-2'
            },
            'delay': {
                'title': 'Delay (ms)',
                'type': 'range-input',
                'min': 100,
                'max': 1000, 
                'width': '1-2'
            },
            'timing-div-close': {
                'type': 'div-close'
            },
        }
    };

    $.pixePluginSettings = {

        init: function(container){
            var t = this;
            var type = container.attr('data-type');
            var values = container.data('value');
            if( typeof(values) != 'object' || Array.isArray(values) ) values = {};

            var tabHead = container.prev('.pixe-plugin-settings-tab-head');
            var options = $.pixePluginOption[type];
            var groupContainer;
            for( var slug in options ){
                var option = options[slug];

                // style selector
                if( option.type == 'ssoption' ){
                    var ss = new $.pixeStyleSelector({
                        obj: {'': values},
                        slug: '',
                        type: option.options,
                        display: 'html'
                    });
                    ss.getContent(container, option.options);
                }else if( option.type == 'div-open' ){
                    groupContainer = $('<div class="pixe-plugin-settings-input-group" ></div>');

                    var input = $.pixeInputWrap({
                        title: option.title,
                        class: 'pixe-plugin-settings-input',
                        descriptionTop: option['description-top'],
                        content: groupContainer,
                        width: '1-1'
                    });
                    container.append(input);
                    
                    if( option.condition ){
                        input.attr('data-condition', '');
                        input.data('condition', option.condition);
                        input.pixeInputCondition(values);
                    }

                }else if( option.type == 'div-close' ){
                    groupContainer = undefined;
                }else{
                    var input;
                    if( groupContainer ){
                        input = $.pixeGetInput(slug, values[slug], option, groupContainer);
                    }else{
                        option.class  = option.class? option.class + ' ': '';
                        option.class += 'pixe-plugin-settings-input';
                        input = $.pixeGetInput(slug, values[slug], option, container);
                    }

                    if( option.condition ){
                        input.pixeInputCondition(values);
                    }
                }
            }

            var submitWrap = $('<div class="pixe-input-wrap pixe-input-submit-wrap" data-width="1-1" ></div>');
            submitWrap.insertAfter(container.parent('.pixe-plugin-settings-tab-inner, .pixe-plugin-settings-content-inner'));

            var submitStatus = $('<div class="pixe-plugin-settings-status" ><span></span>All changes saved</div>');
            submitWrap.append(submitStatus);
            var submitStatuses = submitStatus;
            
            // duplicate status to tab head
            if( tabHead.length ){
                submitStatuses = submitStatuses.add(submitStatus.clone().appendTo(tabHead));
            }

            // set status
            var setSubmitStatus = function(text, isOnProgress){
                submitStatuses.toggleClass('pixe-on-progress', !!isOnProgress);
                submitStatuses.html('<span></span>' + text);
            };
            
            var submitText = container.attr('data-submit-text') || 'Save Options';
            var submit = $('<div class="pixe-update-plugin-settings" >' + $.pixeGetAdminIcon('check') + submitText + '</div>');
            submit.appendTo(submitWrap);

            // top note
            if( $.pixePluginOption[type + '-note'] ){
                submitWrap.prepend('<div class="pixe-note">' + $.pixePluginOption[type + '-note'] + '</div>');
            } 

            // on input changes
            container.on('input change pickerchange', '[data-slug]', function(e){
                if( $(this).closest('.pixe-sselector-options').length ) return;
                
                var slug = $(this).attr('data-slug');
                var value = $.pixeGetInputVal($(this));
                $.pixeSetData(values, slug, value);
                setSubmitStatus('Unsaved changes', true);

                // conditional
                container.find('[data-condition]').each(function(){
                    $(this).pixeInputCondition(values);
                });

                // data callback
                if( type == 'page-transition' ){
                    $.pixeCallback['transition-data'](values);
                }
            });

            // button callback
            container.on('click', '.pixe-button-callback', function(){
                var button = $(this);
                var callback = button.attr('data-button-callback');
                if( callback && $.pixeCallback[callback] ){
                    $.pixeCallback[callback](button, values);
                }
            });

            // on submit
            submit.on('click', function(){
                if( $(this).hasClass('pixe-loading') ) return;

                var button = $(this);
                button.addClass('pixe-loading');

                t.onUpdateFilter(type, values);

                // update ajax data
                var ajaxData = $.pixeGetAjaxData({
                    action: 'pixe_save_plugin_settings',
                    type: type,
                    value: values
                });

                $.pixeAjax({ 
                    ajaxData: ajaxData,
                    onSuccess: function(){
                        button.removeClass('pixe-loading');
                        setSubmitStatus('All changes saved', false);
                        $.pixeConfirmationBox({
                            extraClass: 'pixe-style-2',
                            title: 'Settings Saved',
                            message: 'Options successfully saved!',
                            confirmText: '',
                            cancelText: ''
                        });
                    }
                });
            });

        },

        onUpdateFilter: function(type, values){
            if( !values ) return;
            var t = this;

            if( type == 'layout' ){
                var style = $.pixeGetLayoutCss(values);
                $.pixeSetData(values, 'style', style);
            }
        },

    }

    $(document).ready(function(){
        $('#pixe-plugin-settings-area').each(function(){
            $.pixePluginSettings.init($(this));
        });
    });

})(jQuery);
