'use strict';

jQuery(document).ready(function ($) {

    const prefix = 'item-';

    const selectors = {
        settings: '#wpie-settings',
        color_picker: '.wpie-color',
        full_editor: '.wpie-fulleditor',
        short_editor: '.wpie-texteditor',
        checkbox: '.wpie-field input[type="checkbox"]',
        item_heading: '.wpie-item .wpie-item_heading',
        image_download: '.wpie-image-download',

        menu_style: '.wpie-menu-style',
        menu_type: '[data-field="menu_type"]',
        items_list: '.wpie-items__list',
        item: '.menu-item',
        item_parent: `[data-field="item-parent"]`,
        item_label: `[data-field="item-label"]`,

        icon_type: `[data-field-box*="icon_type"] select, [data-field-box*="${prefix}icon_type"] select`,
        item_type: `[data-field="${prefix}type"]`,
        action: `[data-field="action"]`,
        icon_animation: `[data-field-box*="icon_animation"] select, [data-field-box*="${prefix}icon_animation"] select`,

        enable_tracking: `[data-field="${prefix}enable_tracking"]`,
        add_item: '.wpie-add-button',
        item_remove: '.wpie-item_heading .wpie_icon-trash',
        item_duplicate: '.wpie-item_heading .wpie_icon-copy',

    };


    function set_up() {

        $(selectors.full_editor).wowFullEditor();
        $(selectors.short_editor).wowTextEditor();

        $(selectors.color_picker).wpColorPicker({
            change: function (event, ui) {
                $(selectors.item).wowpMenuLiveBuilder();
                $(selectors.menu_style).wowpMenuStyleBuilder();
            },
        });

        $('.wp-picker-holder').on('click', function () {
            $(selectors.item).wowpMenuLiveBuilder();
            $(selectors.menu_style).wowpMenuStyleBuilder();
        });

        $(selectors.item).wowpMenuLiveBuilder();
        $(selectors.menu_style).wowpMenuStyleBuilder();

        $('.wpie-icon-box').wowIconPicker();

        $(selectors.items_list).sortable({
            items: '> .wpie-item',
            placeholder: "wpie-item ui-state-highlight",
            // axis: "y",
            cursor: "move",
            handle: '.wpie-item_heading',
            cancel: '.wpie-item_content',
            update: function (event, ui) {
                $(selectors.item).wowpMenuLiveBuilder();
            },

            sort: function (event, ui) {
                if (typeof $(selectors.item).wowpMenuLiveBuilder === "function") {
                    $(selectors.item).wowpMenuLiveBuilder();
                }
            },
            stop: function (event, ui) {

                if (typeof $(selectors.item).wowpMenuLiveBuilder === "function") {
                    $(selectors.item).wowpMenuLiveBuilder();
                }
            }

        });


        $(selectors.color_picker).wpColorPicker();
        $(selectors.image_download).wowImageDownload();
        $(selectors.checkbox).each(set_checkbox);

        $(selectors.icon_type).each(icon_type);
        $(selectors.item_type).each(item_type);
        $(selectors.icon_animation).each(icon_animation);
        $(selectors.action).each(action);
        $(selectors.menu_type).each(menu_type);

        $(selectors.enable_tracking).each(enable_tracking);


    }

    function initialize_events() {
        $(selectors.settings).on('change', selectors.checkbox, set_checkbox);
        $(selectors.settings).on('click', selectors.item_heading, item_toggle);

        $(selectors.settings).on('change', selectors.item_type, item_type);
        $(selectors.settings).on('change', selectors.icon_type, icon_type);
        $(selectors.settings).on('change', selectors.icon_animation, icon_animation);
        $(selectors.settings).on('change', selectors.action, action);
        $(selectors.settings).on('change', selectors.menu_type, menu_type);

        $(selectors.settings).on('change', selectors.enable_tracking, enable_tracking);
        $(selectors.settings).on('click', selectors.add_item, clone_button);
        $(selectors.settings).on('click', selectors.item_remove, item_remove);
        $(selectors.settings).on('click', selectors.item_duplicate, item_duplicate);


        $(selectors.settings).on('change click keyup', selectors.item, function () {
            $(selectors.item).wowpMenuLiveBuilder();
        });

        $(selectors.settings).on('change click keyup', selectors.menu_style, function () {
            $(selectors.menu_style).wowpMenuStyleBuilder();
        });


    }

    //region Main
    function initialize() {
        set_up();
        initialize_events();
    }

    // Set the checkboxes
    function set_checkbox() {
        const next = $(this).next('input[type="hidden"]');
        if ($(this).is(':checked')) {
            next.val('1');
        } else {
            next.val('0');
        }
    }

    function item_toggle() {
        const parent = get_parent_fields($(this), '.wpie-item');
        const val = $(parent).attr('open') ? '0' : '1';
        $(parent).find('.wpie-item__toggle').val(val);
    }

    function get_parent_fields($el, $class = '.wpie-fields') {
        return $el.closest($class);
    }

    function get_field_box($el, $class = '.wpie-field') {
        return $el.closest($class);
    }

    //endregion

    //region Plugin
    function icon_type() {
        const type = $(this).val();
        const box = get_field_box($(this));
        const parent = get_parent_fields($(this));
        const fields = parent.find('[data-field-box]').not(box);
        fields.addClass('is-hidden');

        const fieldMap = {
            icon: ['icon', 'item-icon'],
            image: ['image', 'image_alt', 'item-image', 'item-image_alt'],
            class: ['icon_class', 'item-icon_class'],
            emoji: ['emoji', 'item-emoji'],
        }

        if (fieldMap[type]) {
            const fieldsToShow = fieldMap[type];
            fieldsToShow.forEach(field => {
                parent.find(`[data-field-box|="${field}"]`).removeClass('is-hidden');
            });
        }
    }


    function item_type() {
        const type = $(this).val();
        const parent = get_parent_fields($(this), '.wpie-fieldset');
        const box = get_field_box($(this));
        const fields = parent.find('[data-field-box]').not(box);
        const parentTab = get_parent_fields($(this), '.wpie-tabs-wrapper');

        parentTab.find('.wpie-tab__type-menu').addClass('is-hidden');
        fields.addClass('is-hidden');

        const linkText = parent.find(`[data-field-box="${prefix}link"] .wpie-field__title`);
        linkText.text('Link');

        // Mapping menu types to the respective field boxes.
        const typeFieldMapping = {
            link: [`${prefix}link`, `${prefix}_blank`],
            login: [`${prefix}link`],
            logout: [`${prefix}link`],
            lostpassword: [`${prefix}link`],
            goback: [`${prefix}_blank`],
            google_translate: [`${prefix}translate`, `${prefix}_blank`],
            next_post: [`${prefix}_blank`],
            previous_post: [`${prefix}_blank`],
            share: [`${prefix}share`],
            share_text: [`${prefix}share_text`],
            translate: [`${prefix}translate`],
            bookmark: [`${prefix}mess`],
            copyUrl: [`${prefix}mess`],
            copyText: [`${prefix}mess`],
            smoothscroll: [`${prefix}link`],
            scrollSpy: [`${prefix}link`],
            download: [`${prefix}link`, `${prefix}download`],
            email: [`${prefix}link`],
            telephone: [`${prefix}link`],
            dialog: [`${prefix}text`, `item-text-box`],
            skype_call: [`${prefix}link`],
            skype_chat: [`${prefix}link`],
            whatsapp_call: [`${prefix}link`, `${prefix}_blank`],
            whatsapp_chat: [`${prefix}link`],
            viber_call: [`${prefix}link`],
            viber_chat: [`${prefix}link`],
            telegram_chat: [`${prefix}link`],
            imessage_chat: [`${prefix}link`],
            play: [`${prefix}link`],
            pause: [`${prefix}link`],
            muted: [`${prefix}link`],
            loop: [`${prefix}link`],
            reset: [`${prefix}link`],
            volumeUp: [`${prefix}link`],
            volumeDown: [`${prefix}link`],
            function: [`${prefix}link`],
            event: [`${prefix}link`],

        };

        // Customize the link text for certain types
        const linkTextMapping = {
            login: 'Redirect URL',
            logout: 'Redirect URL',
            lostpassword: 'Redirect URL',
            email: 'Email',
            telephone: 'Phone number',
            whatsapp_call: 'Phone number',
            facetime: 'Phone number',
            viber_call: 'Phone number',
            skype_call: 'Username',
            download: 'File URL',
            smoothscroll: 'Anchor',
            skype_chat: 'Username',
            whatsapp_chat: 'Phone number',
            viber_chat: 'Phone number',
            telegram_chat: 'Username',
            imessage_chat: 'Phone number',
            play: 'Selector',
            pause: 'Selector',
            muted: 'Selector',
            loop: 'Selector',
            reset: 'Selector',
            volumeUp: 'Selector',
            volumeDown: 'Selector',
            function: 'Function Name',
            event: 'Event Name',
        };

        if (typeFieldMapping[type]) {
            const fieldsToShow = typeFieldMapping[type];
            fieldsToShow.forEach(field => {
                parent.find(`[data-field-box|="${field}"]`).removeClass('is-hidden');
            });

            if (linkTextMapping[type]) {
                linkText.text(linkTextMapping[type]);
            }

        }
    }

    // Position
    function icon_animation() {
        const type = $(this).val();
        const parent = get_parent_fields($(this));
        const box = get_field_box($(this));
        const fields = parent.find('[data-field-box]').not(box);
        fields.addClass('is-hidden');

        if (type !== '') {
            fields.removeClass('is-hidden');
        }
    }

    function action() {
        const type = $(this).val();
        const parent = get_parent_fields($(this));
        const box = get_field_box($(this));
        const fields = parent.find('[data-field-box]').not(box);
        fields.addClass('is-hidden');

        if (type === 'scroll_show' || type === 'scroll_hide') {
            parent.find('[data-field-box="scroll"]').removeClass('is-hidden');
        }

        if (type === 'timer_show' || type === 'timer_hide') {
            parent.find('[data-field-box="timer"]').removeClass('is-hidden');
        }
    }

    function menu_type() {
        const type = $(this).val();
        const parent = get_parent_fields($(this));
        const box = get_field_box($(this));
        const fields = parent.find('[data-field-box]').not(box);
        fields.addClass('is-hidden');

        if (type === 'floating') {
            parent.find('[data-field-box="menu_position"]').removeClass('is-hidden');
        }
        if (type === 'dropdown') {
            parent.find('[data-field-box="menu_selector"]').removeClass('is-hidden');
            parent.find('[data-field-box="menu_action"]').removeClass('is-hidden');
        }

        if (type === 'attached') {
            parent.find('[data-field-box="menu_position"]').removeClass('is-hidden');
            parent.find('[data-field-box="menu_selector"]').removeClass('is-hidden');
            parent.find('[data-field-box="menu_out"]').removeClass('is-hidden');
        }
    }

    // Enable Event Tracking
    function enable_tracking() {
        const fieldset = get_parent_fields($(this), '.wpie-fieldset');
        const tracking_field = fieldset.find('.wpie-event-tracking');
        tracking_field.addClass('is-hidden');
        if ($(this).is(':checked')) {
            tracking_field.removeClass('is-hidden');
        }
    }


    function item_remove() {
        const userConfirmed = confirm("Are you sure you want to remove this element?");
        if (userConfirmed) {
            const parent = $(this).closest('.wpie-item');
            $(parent).remove();
            set_up();
        }
    }

    function item_duplicate() {
        const userConfirmed = confirm("Do you want to duplicate this element?");
        if (userConfirmed) {
            const parent = get_parent_fields($(this), '.wpie-items__list');
            const item = $(this).closest('.wpie-item');

            let selectedValues = {};
            item.find('select').each(function () {
                selectedValues[$(this).attr('name')] = $(this).val();
            });

            $(item).attr('open', 'false');
            const clonedItem = item.clone(true, true);
            cleaningItem(clonedItem);

            clonedItem.find('select').each(function () {
                let name = $(this).attr('name');
                if (selectedValues[name]) {
                    $(this).val(selectedValues[name]);
                }
            });

            $(clonedItem).attr('open', '');
            item.after(clonedItem);
            set_up();
        }
    }

    function cleaningItem(item) {

        $(item).find('select').each(function () {
            let selectedValue = $(this).val();
        });

        $(item).find('.wpie-fulleditor').each(function () {
            const field = $(this);
            const id = $(this).attr('id');
            field.removeAttr('style id aria-hidden');
            const parent = $(this).closest('.wpie-field__label');
            const editor = $(parent).find('.wp-editor-wrap');
            if (editor.hasClass('tmce-active')) {
                let content = tinyMCE.get(id)?.getContent();
                field.val(content);
            }
            $(editor).remove();
            $(parent).prepend(field);
        });

        $(item).find('.wpie-color').each(function () {
            const field = $(this);
            field.removeAttr('style');
            const parent = $(this).closest('.wpie-field');
            const picker = $(parent).find('.wp-picker-container');
            $(picker).remove();
            $(parent).append(field);
        });

        $(item).find('.wpie-icon-box').each(function () {
            const field = $(this);
            field.removeAttr('style');
            let $this = $(this);

            // Видаляємо збережені дані плагіна
            $this.removeData('fontIconPicker');

            // Видаляємо додані DOM-елементи (панель вибору)
            $this.siblings('.fip-box').remove();

            // Видаляємо додані класи
            $this.removeClass('fip fip-theme-darkgrey');

            // Відновлюємо оригінальний <select>
            $this.show();

            const parent = $(this).closest('.wpie-field__label');
            const picker = $(parent).find('.icons-selector');
            $(picker).remove();
        });

    }

    // Clone menu item
    function clone_button(e) {
        e.preventDefault();
        const parent = get_parent_fields($(this), '.wpie-items__list');
        const selector = $(parent).find('.wpie-buttons__hr');
        const template = $('#template-button').clone().html();

        $(template).insertBefore($(selector));

        set_up();
    }


    initialize();
});