var ChoiceKeysMobileView = Backbone.View.extend({
    breadcrumb: {},
    chosenKey: {},
    chosenKeyId: '',
    itemsStyleMapping: {},
    itemMapping: {},
    addedKey: {},

    groupNames: [],
    items: [],
    currentGroup: '',
    choiceKeysPages: [],

    events: {
        'keyup #itemSearch': 'searchItemBySearchTerm',
        'click .edit-modal-trigger': 'openEditModal',
        'click .add-new-choice-btn' : 'addNewChoice',
        'click .delete-choice-key' : 'deleteChoiceKey',
        'click #addPageBtn' : 'addPage',
        'click .deletePageBtn' : 'deletePage',
        'keyup #choice-key-edit-modal #itemButtonText' : 'updateChoiceText',
        'change #choice-key-edit-modal .cr' : 'updateChoiceCr',
        'change select[name="pageType"]' : 'updatePageType',
        'change #group-selector' : 'showDiscardChangesModal',
        'click #cancel-discard-changes' : 'onCancelDiscardChanges',
        'click #discard-changes' : 'changeGroup',
        'click .save-keys-button' : 'saveChoiceKeys',
        'click #addChoiceGroupBtn' : 'showChoiceGroupModal',
        'click .add-new-choice-group-button' : 'addChoiceGroup',
        'click #editChoiceGroupBtn' : 'showChoiceGroupEditModal',
        'click .save-choice-group-name-button' : 'editChoiceGroupName',
        'click .expand-collapse' : 'toggleCollapseAll',
        'focus input[name="minRequired"], input[name="maxAllowed"]' : 'selectAllText',

    },

    dataChangedAndNotSaved: false,
    isChoiceGroupsCollapsed: false,

    initialize: async function (options) {
        Number.prototype.toCurrency = function(fractionDigits = 0) {
            return this.valueOf().toLocaleString('en-US',{ maximumFractionDigits: fractionDigits, minimumFractionDigits: fractionDigits });
        };

        this.options = options;
        this.template = _.template(options.template);
        this.breadcrumb = options.breadcrumb;
        this.posKeyFormTemplate = options.posKeyFormTemplate;
        this.model = options.model;
        await this.getChoiceKeys();
        this.changeGroup();

        App.breadCrumbToolTip = "Create, manage, and edit your Choice Group keys"
        App.setBreadcrumbs(this.breadcrumb);
    },

    getCookie: function() {
        var nameEQ = "sessionCookie" + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    },

    
    render: function () {
        var that = this;
        that.$el.html(that.template({
            items: that.currentGroupList,
            groupNames: that.groupNames,
            currentGroup: that.currentGroup,
            choiceKeysPages: that.choiceKeysPages,
            removeTypeFromDescriptionKey: that.removeTypeFromDescriptionKey,
            getPageType: that.getPageType,
        }));
        
        $(document).ready(function () {
            that.initAutoComplete();

            M.Modal.init(document.getElementById('choice-key-edit-modal'), {});
            M.Modal.init(document.getElementById('unsaved-changes-modal'), {});

            
            if (!('ontouchstart' in window || navigator.maxTouchPoints))
                $('.tooltipped').tooltip();
            

           
            $('select').formSelect();
            M.FloatingActionButton.init(document.querySelector('.fixed-action-btn'), {});
        });

        const draggableElements = document.querySelectorAll('.choice-key-card.draggable');

        draggableElements.forEach(element => {
           that.addDragListeners(element);

        });

        this.isChoiceGroupsCollapsed = false;

        return this;
    },

    addDragListeners: function(element) {
        var that = this;
        element.setAttribute('draggable', 'true');
        element.addEventListener('dragstart',  that.handleDragStart);
        element.addEventListener('dragover',   that.handleDragOver);
        element.addEventListener('dragenter',   that.handleDragEnter);
        element.addEventListener('dragleave',  that.handleDragLeave);
        element.addEventListener('dragend',   that.handleDragEnd);
        element.addEventListener('drop',  that.handleDrop);
        
        element.addEventListener('touchstart',  that.handleTouchDragStart);
        element.addEventListener('touchmove',  that.handleTouchDragMove);
        element.addEventListener('touchend',  that.handleTouchDragEnd );
    },
    removeDragListeners: function(element) {
        var that = this;
        element.removeAttribute('draggable');
        element.removeEventListener('dragstart',  that.handleDragStart);
        element.removeEventListener('dragover',   that.handleDragOver);
        element.removeEventListener('dragenter',   that.handleDragEnter);
        element.removeEventListener('dragleave',  that.handleDragLeave);
        element.removeEventListener('dragend',   that.handleDragEnd);
        element.removeEventListener('drop',  that.handleDrop);
    
        element.removeEventListener('touchstart',  that.handleTouchDragStart);
        element.removeEventListener('touchmove',  that.handleTouchDragMove);
        element.removeEventListener('touchend',  that.handleTouchDragEnd );
    },

    
    handleDragEnd: function(e) {
        var that = App.choiceKeysMobileView;
        // that.dragSrcEl.style.opacity = '1';
        const draggableElements = document.querySelectorAll('.draggable');
        draggableElements.forEach(element => {
            element.classList.remove('dragged-over');
        });

        that.currentDraggedClass = '';
    },
    
    handleDragOver: function(e) {
        var that = App.choiceKeysMobileView;
        e.preventDefault();

        return false;
    },
    
    handleDragEnter: function(e) {
        var that = App.choiceKeysMobileView;
        var el = e.target.closest(that.currentDraggedClass + '.draggable');
        if(el && el.dataset.page == that.dragSrcEl.dataset.page)
            el.classList.add('dragged-over');
    },
    
    handleDragLeave: function(e) {
        var that = App.choiceKeysMobileView;
        if (e.currentTarget.contains(e.relatedTarget)) {
            return;
        }
        var el = e.target.closest(that.currentDraggedClass + '.draggable');
        if(el && el.dataset.page == that.dragSrcEl.dataset.page)
            el.classList.remove('dragged-over');
    },

    currentDraggedClass: '',
    dragSrcEl: {},

    handleDragStart: function (e, that) {
        var that = App.choiceKeysMobileView;
        if(e.target.tagName == 'INPUT' ) {
            e.preventDefault();
            return;
        }
        if(that.currentDraggedClass != '') {
             e.stopPropagation();
            return;
        }
        
        var el = e.target;
        if(el.classList.contains('choice-type'))
            that.currentDraggedClass = '.choice-type';
        else if(el.classList.contains('page-type')) {
            that.currentDraggedClass = '.page-type';
            const emptyImage = new Image();
            e.dataTransfer.setDragImage(emptyImage, 0, 0); 
        }
      
        that.dragSrcEl = el;      
    },
      
    handleDrop: function (e, that) {
        var that = App.choiceKeysMobileView;
        e.stopPropagation(); // Stops some browsers from redirecting.

        var el = e.target.closest(that.currentDraggedClass + '.draggable');

        if(el && that.currentDraggedClass == '.page-type' || ( that.currentDraggedClass == '.choice-type' && el.dataset.page == that.dragSrcEl.dataset.page) ) {

            const parent = el.parentElement;
            const siblings = Array.from(parent.children); // Convert HTMLCollection to an array
            const index1 = siblings.indexOf(el); // Index of the first element
            const index2 = siblings.indexOf(that.dragSrcEl); // Index of the second element
            
            that.dragSrcEl.classList.add('fade-in');
            setTimeout(() => {

            if(index1 > index2)
                el.insertAdjacentElement('afterend',that.dragSrcEl);
            else
                el.insertAdjacentElement('beforebegin',that.dragSrcEl);

                setTimeout(() => {
                    that.isChoiceGroupChanged = true;
                    that.dragSrcEl.classList.remove('fade-in');
                    if(that.currentDraggedClass == '.choice-type')
                        that.updateChoiceKeysOrder(that.dragSrcEl)
                }, 100);
            }, 300);
            
        }

        return false;
    },

    draggedItemCopy: null,
    // elementUnderTouch: null,
    currentDropTarget: null,
    draggedItem: null,

    handleTouchDragStart: function(e) {
        var that = App.choiceKeysMobileView;
        if(e.target.tagName == 'INPUT') {
            // e.preventDefault();
            e.stopPropagation();
            return;
        }
        if(that.currentDraggedClass != '')
            return;

        var el = e.target.closest('.draggable');
        if(el.classList.contains('choice-type'))
            that.currentDraggedClass = '.choice-type';
        else if(el.classList.contains('page-type'))
            that.currentDraggedClass = '.page-type';
        
        const touchLocation = e.targetTouches[0];
   
        that.draggedItemCopy = document.createElement('div');
        that.dragSrcEl = e.target.closest(that.currentDraggedClass + '.draggable');
        that.draggedItemCopy.innerHTML = that.dragSrcEl.innerHTML;
        that.draggedItemCopy.classList.add(...that.dragSrcEl.classList);
        that.draggedItemCopy.style.position = 'absolute';
        that.currentDropTarget = that.draggedItemCopy;
        
        const zoom = window.getComputedStyle(that.dragSrcEl)?.getPropertyValue('zoom');
        that.zoomLevel = zoom ? parseFloat(zoom) : 1;
    },

    isDraggedItemInserted: false,

    handleTouchDragMove: function(e) {
        var that = App.choiceKeysMobileView;

        e.preventDefault();
        if(!that.isDraggedItemInserted){
            document.getElementById('grid-stack-container').insertAdjacentElement('beforeend', that.draggedItemCopy);
            that.isDraggedItemInserted = true;
        }
        const touchLocation = e.targetTouches[0];
        const scrollX = window.scrollX || document.documentElement.scrollLeft;
        const scrollY = window.scrollY || document.documentElement.scrollTop;
        
        // Calculate offsets accounting for scroll and zoom
        const offsetX = (touchLocation.clientX + scrollX) / that.zoomLevel;
        const offsetY = (touchLocation.clientY + scrollY) / that.zoomLevel;
        
        // Set position of the dragged item
        that.draggedItemCopy.style.left = `${offsetX }px`;
        that.draggedItemCopy.style.top = `${offsetY }px`;


        const elements = document.elementsFromPoint(touchLocation.clientX, touchLocation.clientY);
        if(elements.length > 1)
            var elementUnderTouch = elements[1].closest(that.currentDraggedClass + '.draggable');
        else
            return;


        if (elementUnderTouch && elementUnderTouch !== that.draggedItemCopy && elementUnderTouch.dataset.page == that.dragSrcEl.dataset.page) {
            if (that.currentDropTarget !== elementUnderTouch) {
                if (that.currentDropTarget) {
                    that.currentDropTarget.classList.remove('dragged-over');
                }
                that.currentDropTarget = elementUnderTouch;
                that.currentDropTarget.classList.add('dragged-over');
            }
        }
    },

    handleTouchDragEnd: function(e) {
        var that = App.choiceKeysMobileView;

        e.stopPropagation();
        that.currentDropTarget.classList.remove('dragged-over');
        
        var dropTarget = document.elementFromPoint(e.changedTouches[0].clientX, e.changedTouches[0].clientY);
        dropTarget = dropTarget.closest(that.currentDraggedClass + '.draggable');
        if (dropTarget && dropTarget.classList.contains('draggable') && dropTarget !== that.dragSrcEl) {
            if( that.currentDraggedClass == '.page-type' || ( that.currentDraggedClass == '.choice-type' && dropTarget.dataset.page == that.dragSrcEl.dataset.page) ) {
                const parent = dropTarget.parentElement;
                const siblings = Array.from(parent.children); // Convert HTMLCollection to an array
                const index1 = siblings.indexOf(dropTarget); // Index of the first element
                const index2 = siblings.indexOf(that.dragSrcEl); // Index of the second element
                    
                that.dragSrcEl.classList.add('fade-in');
                setTimeout(() => {
                    if(index1 > index2)
                        dropTarget.insertAdjacentElement('afterend',that.dragSrcEl);
                    else
                        dropTarget.insertAdjacentElement('beforebegin',that.dragSrcEl);

                    setTimeout(() => {
                        that.isChoiceGroupChanged = true;
                        that.dragSrcEl.classList.remove('fade-in');
                        if(that.currentDraggedClass == '.choice-type')
                            that.updateChoiceKeysOrder(that.dragSrcEl)
                        
                    }, 100);
                }, 300);
            }
        }
        

        if(that.draggedItemCopy)
            that.draggedItemCopy.remove();
        that.isDraggedItemInserted = false;
        that.currentDraggedClass = '';
    },


    getChoiceKeys: async function() {
        var that = this;
        var sessionToken = this.getCookie();
        return $.ajax({
            url: '/data/get-choice-keys',
            data: {
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {

                that.groupNames = [];
                var len = Object.keys(data).length;
                for (var i = 0; i < len; i++) {
                    const newPageArray = [];
                    const pageArray = data[i].pageArray;
                    const len2 = pageArray.length;
                    for (let j = 0; j < len2; j++) {
                        if(pageArray[j] != null)
                            newPageArray.push(pageArray[j]);
                    }

                    data[i].pageArray = newPageArray;
                    that.groupNames.push(data[i].choiceGroup);
                }

                that.items = data;

                that.render();

            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}Occurred a problem while rendering this page{/Literal}' });
                }
            }
        });
    },

    addNewChoice: function(e) {
        var that = this;
        const choiceKeyGroupCardEl =  e.currentTarget.closest('.choice-key-group-card');
        const pageType = choiceKeyGroupCardEl.querySelector('#pageType').value;
        const pageIndex = choiceKeyGroupCardEl.dataset.page;

        this.choiceKeysPages[pageIndex].push({
            itemCode: '',
            cr: true,
            noRepeat: true,
            id: 0,
            text: "{Literal}New Choice Key{/Literal}",
            id2: new Date().getTime()
        })

        this.render();
    },



    initAutoComplete: function () {
        var that = this;
        var elems = document.querySelector('#itemSearch');
        this.itemsAutocomplete = M.Autocomplete.init(elems, {
            minLength: 1,
            lmit: 20,
            sortFunction: function (a, b, inputString) {
                return a.indexOf(inputString) - b.indexOf(inputString);
            },
            onAutocomplete: function (selection) { that.selectItemFromAutocompleteList(selection); }
        });
    },

    searchItemBySearchTerm: function(element) {
        var element = $(element.currentTarget);
        var searchTerm = $(element).val();
        var that = this;
        if (searchTerm.trim().length > 0) {
            if (this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(function() { 
                that.getItemsBySearchTerm(searchTerm); 
            }, 400);
        }
    },

    getItemsBySearchTerm: function(searchTerm) {
        var that = this;
        $.ajax({
            url: '/data/get-items-by-search-term',
            data: {
                searchTerm: searchTerm,
                token: this.getCookie()
            },
            dataType: 'json',
            type: 'POST',
            success: function (data) {
                var results = data.results;
                var items = {};
                for (var i = 0; i < results.length; i++) {
                    items[results[i].itemCode + ' / ' + results[i].itemDescription] = null;
                    that.itemMapping[results[i].itemCode + ' / ' + results[i].itemDescription] = results[i];
                }
                that.itemsAutocomplete.updateData(items);    
                that.itemsAutocomplete.open();
                    
            },
            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                }
            }
        });
    },

    selectItemFromAutocompleteList: function (selection) {
        var that = this;

        Object.size = function(obj) {
            var size = 0, key;
            for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
            }
            return size;
        };
        
        for (var i = 0; i < Object.size(that.itemMapping); i++) {
            if (Object.entries(that.itemMapping)[i][0] == selection) {
                const item = Object.entries(that.itemMapping)[i][1];
                that.updateChoiceItem(item);
            }
        }
    },

    showDiscardChangesModal: function() {
        if(this.isChoiceGroupChanged) {
            var modal = M.Modal.getInstance(document.getElementById('unsaved-changes-modal'));
            modal.open();
        }
        else
            this.changeGroup();
    },

    onCancelDiscardChanges: function() {
        //roll back choice group select to prevues option
        var select = document.getElementById('group-selector');
        select.value = this.choiceGroup;
        M.FormSelect.init(select);
    },

    changeGroup: function () {
        var that = this;
        this.choiceGroup = document.getElementById('group-selector').value;

        const choiceGroupsList = Object.values(that.items);
        const selectedChoiceGroup = choiceGroupsList.filter(i => i.choiceGroup == this.choiceGroup);
        let choiceKeysPages = selectedChoiceGroup[0]?.pageArray;
        // if(choiceKeysPages != undefined && choiceKeysPages[0] == null)
        //     choiceKeysPages = choiceKeysPages.slice(1);
        
        if(choiceKeysPages) {
            choiceKeysPages.forEach( page => {
                let idx = 0;
                page?.sort((a, b) => {
                    if (a.row !== b.row)
                        return a.row - b.row;
                    
                    return a.column - b.column;
                });
                idx = page?.findIndex(choiceKey => (choiceKey.text.startsWith('*') && choiceKey.text.endsWith('*')) || (choiceKey.text.startsWith('#') && choiceKey.text.endsWith('#')));
                if(idx > 0){ // make page title choice first
                    const firstObj = page[0];
                    page[0] = page[idx];
                    page[idx] = firstObj;
                }
            });
            this.choiceKeysPages = choiceKeysPages;
        }
        else if(this.choiceGroup != '') {
            this.choiceKeysPages = [];
            this.choiceKeysPages.push([{
                itemCode: '',
                cr: true,
                noRepeat: true,
                id: 0,
                text: "*{Literal}Description{/Literal}*",
                minRequired: 0,
                maxAllowed: 0,
            }, {
                itemCode: '',
                cr: true,
                noRepeat: true,
                id: 0,
                text: "{Literal}New Choice Key{/Literal}",
                minRequired: 0,
                maxAllowed: 0,
            }
            ]);
        }

        this.isChoiceGroupsCollapsed = false;
        this.isChoiceGroupChanged = false;

        this.render();
    },
    


    saveNewMenuPage: function () {
        var menuPage = this.$el.find('#menuPageName').val();
        that = this;
        var isTaken = false;
        if (menuPage != '' && menuPage != undefined && menuPage != null) {
            for (var i in that.groupNames) {
                if (that.groupNames[i] === menuPage) {
                    isTaken = true;
                    break;
                }
            }

            if (isTaken) {
                M.toast({ html: '{Literal}This Choice Group is already defined{/Literal}' });
            }
            else {
                that.groupNames.push(menuPage);  
                this.render();
            }
        }
        else {
            M.toast({ html: '{Literal}Please enter a valid Choice Group name{/Literal}' });
        }
    },

    openEditNameModal: function () {
        var currentPage = this.$el.find('#group-selector option:selected').text();
        var pageName = document.getElementById('pageName'); 
        pageName.value = currentPage;

        var pageNameModal = this.$el.find('#edit-page-name-modal').modal();
        pageNameModal.modal('open');
    },

    openDeletePageModal: function (e) {
        var deletePageModal = this.$el.find('#delete-page-modal').modal();
        deletePageModal.modal('open');
    },

    addNewPage: function () {
        var newPageModal = this.$el.find('#new-page-form-modal').modal();
        newPageModal.modal('open');
    },



    savePageName: function () {
        var that = this;
        var newPageName = this.$el.find('#pageName').val();
        var currentPage = this.$el.find('#group-selector option:selected').text();
        var sessionToken = this.getCookie();
        
        $.ajax({
            url: '/data/rename-choice-group',
            data: {
                oldChoiceGroup: currentPage,
                newChoiceGroup: (newPageName),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                for (var i = 0; i < that.groupNames.length; i++) {
                    if (that.groupNames[i] == currentPage) {
                        that.groupNames[i] = newPageName;
                    }
                }

                for (var i = 0; i <  Object.keys(that.items).length; i++) {
                    if (that.items[i].choiceGroup == currentPage) {
                        that.items[i].choiceGroup = newPageName;
                    }
                }
                that.render();
                M.toast({ html: '{Literal}Choice Group name changed successfully{/Literal}' });
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem renaming this Choice Group{/Literal}' });
                }
            }
        });
    },

 

    currentEditEl: null,

    openEditModal: function (e) {
        this.currentEditEl = e.currentTarget.closest('.choice-key-card');
        document.querySelector('#choice-key-edit-modal #itemButtonText').value = this.currentEditEl.dataset.text;
        document.querySelector('#choice-key-edit-modal #itemId').value = this.currentEditEl.dataset?.itemid;
        document.querySelector('label[for="itemId"]').classList.add('active');

        document.querySelector('#choice-key-edit-modal #cr').checked = this.currentEditEl.dataset.cr == 'true';
        var modal = M.Modal.getInstance(document.getElementById('choice-key-edit-modal'));
        modal.open();
    },

    updateChoiceText: function() {
        this.currentEditEl.dataset.text = document.querySelector('#choice-key-edit-modal #itemButtonText').value;
        this.currentEditEl.querySelector('.description').innerText = document.querySelector('#choice-key-edit-modal #itemButtonText').value;
        const pageIndex = this.currentEditEl.dataset.page;
        const choiceIndex = this.currentEditEl.dataset.index;
        this.choiceKeysPages[pageIndex][choiceIndex].text = document.querySelector('#choice-key-edit-modal #itemButtonText').value;
        this.isChoiceGroupChanged = true;
    },
    updateChoiceItem: function(item) {
        this.currentEditEl.dataset.itemid = item.itemCode;
        this.currentEditEl.querySelector('.choice-key-price').innerText = item.itemPrice.toCurrency(2);
        this.currentEditEl.querySelector('.choice-key-price').style.display = '';
        const pageIndex = this.currentEditEl.dataset.page;
        const choiceIndex = this.currentEditEl.dataset.index;
        this.choiceKeysPages[pageIndex][choiceIndex].itemCode = item.itemCode;
        document.getElementById('itemId').value = item.itemCode;
        document.getElementById('itemButtonText').value = item.itemDescription;
        this.isChoiceGroupChanged = true;
        document.querySelector('#choice-key-edit-modal #itemButtonText').value = item.itemDescription;
        this.updateChoiceText();
    },
    updateChoiceCr: function() {
        this.currentEditEl.dataset.cr = document.querySelector('#choice-key-edit-modal #cr').checked;
        const pageIndex = this.currentEditEl.dataset.page;
        const choiceIndex = this.currentEditEl.dataset.index;
        this.choiceKeysPages[pageIndex][choiceIndex].cr = this.currentEditEl.dataset.cr;
        this.isChoiceGroupChanged = true;
    },
    updateChoiceNoRepeat: function() {
        this.currentEditEl.dataset.norepeat = document.querySelector('#choice-key-edit-modal #noRepeat').checked;
        const pageIndex = this.currentEditEl.dataset.page;
        const choiceIndex = this.currentEditEl.dataset.index;
        this.choiceKeysPages[pageIndex][choiceIndex].norepeat = this.currentEditEl.dataset.norepeat;
        this.isChoiceGroupChanged = true;
    },
    updatePageType: function(e) {
        const pageIndex = e.target.closest('.choice-key-group-card').dataset.page;
        const pageTypeEl = e.target.closest('select[name="pageType"]');
        const thisPage = this.choiceKeysPages[pageIndex];
        const firstChoiceKey = thisPage[0];
        const pageType = this.getPageType(firstChoiceKey.text);
        const pageTitle = firstChoiceKey.text.replaceAll(pageType,'');
        firstChoiceKey.text = pageTypeEl.value + pageTitle + pageTypeEl.value;
        this.isChoiceGroupChanged = true;
        this.render();            
    },

    getPageType: function(value) {
        var pizzaType = '';
        if(value.startsWith('#3R#') && value.endsWith('#3R#'))
            pizzaType = '#3R#';
        else if(value.startsWith('#3S#') && value.endsWith('#3S#'))
            pizzaType = '#3S#';
        else if(value.startsWith('#') && value.endsWith('#'))
            pizzaType= '#';
        else if(value.startsWith('*') && value.endsWith('*'))
            pizzaType= '*';

        return pizzaType
    },

    removeTypeFromDescriptionKey: function(text) {
        const pageType = App.choiceKeysMobileView.getPageType(text, '');
        if(pageType != '')
            return text.replaceAll(pageType, '');
        else
            return text;
        
    },

    // toggleCollapsible: function (e) {
    //     const currentCollapsible = e.currentTarget.parentElement.querySelector('.choice-keys')
    //     if(currentCollapsible.dataset.hide === 'true') {
    //         currentCollapsible.dataset.hide = false;
    //         e.currentTarget.dataset.collapsed = false;
            
    //         currentCollapsible.parentElement.parentElement.querySelectorAll('.hide-mobile').forEach( el => {
    //             el.style.display = '';
    //         })
    //     }
    //     else {
    //         currentCollapsible.dataset.hide = true;
    //         e.currentTarget.dataset.collapsed = true;

    //         const zoom = window.getComputedStyle(document.querySelector('.choice-key-card'))?.getPropertyValue('zoom');
    //         if(zoom && zoom != '1') { // mobile mode
    //             currentCollapsible.parentElement.querySelectorAll('.hide-mobile').forEach( el => {
    //                 el.style.display = 'none';
    //             })
    //         }
    //     }
    // },

    toggleCollapseAll: function() {
        this.isChoiceGroupsCollapsed = !this.isChoiceGroupsCollapsed;
        document.querySelectorAll('.collapse-page').forEach( (el,index) => {
            el.dataset.collapsed = this.isChoiceGroupsCollapsed;
        });

        document.querySelectorAll('.choice-keys').forEach( (el,index) => {
            el.dataset.hide = this.isChoiceGroupsCollapsed;
        });

        const zoom = window.getComputedStyle(document.querySelector('.choice-key-card'))?.getPropertyValue('zoom');
        if(zoom && zoom != '1') { // mobile mode
            document.querySelectorAll('.hide-mobile').forEach( el => {
                el.style.display = this.isChoiceGroupsCollapsed ? 'none': 'block';
            })
        }

        document.querySelectorAll('.choice-key-group-card').forEach( el => { 
            if(this.isChoiceGroupsCollapsed)
                this.addDragListeners(el, this);
            else
                this.removeDragListeners(el, this);
        });
    },

    deleteChoiceKey: function(e) {
        
        if(this.currentEditEl) {
            this.currentEditEl.remove();
            this.isChoiceGroupChanged = true;
            this.choiceGroup = document.getElementById('group-selector').value;

            const keys = Object.keys(this.items);
            const len = keys.length;
            for (let i = 0; i < len; i++) {
                if(this.items[i].choiceGroup == this.choiceGroup) {
                    var selectedChoiceGroup = this.items[i];
                    break;
                }
            }

            // const selectedChoiceGroup = choiceGroupsList.filter(i => i.choiceGroup == this.choiceGroup)[0];
            const pageIdx = this.currentEditEl.dataset.page;
            const id2 = this.currentEditEl.dataset.id2;
            var choiceIdx;
            if(id2)
                choiceIdx = selectedChoiceGroup.pageArray[pageIdx].findIndex( i => i?.id2 == id2);
            else {
                const id = this.currentEditEl.dataset.id;
                choiceIdx = selectedChoiceGroup.pageArray[pageIdx].findIndex( i => i.id == id);
            }

            if(choiceIdx !== -1) {
                selectedChoiceGroup.pageArray[0].splice(choiceIdx, 1);
                console.log("")
            }
        }
        else {
            M.toast({ html: '{Literal}Something went wrong, could not delete.{/Literal}' });
        }
    },

    deletePage: function(e) {
        const pageEl = e.target.closest('.page-type');
        const pageNumber = pageEl.dataset.page;
        if(pageNumber) {
            pageEl.remove();
            this.isChoiceGroupChanged = true;
        }
        else {
            M.toast({ html: '{Literal}Something went wrong, could not delete.{/Literal}' });
        }
    },

    getValues: function() {
        const pages = [];
        const choiceGroup = document.getElementById('group-selector').value;
        const pageElements = document.querySelectorAll('.choice-key-group-card');
        pageElements.forEach( (pageEl, index) => {
            const pageTitle = pageEl.querySelector('input[name="page-title"]').value;
            const pageType = pageEl.querySelector('select[name="pageType"]').value;
            const minRequired = pageEl.querySelector('input[name="minRequired"]').value;
            const maxAllowed = pageEl.querySelector('input[name="maxAllowed"]').value;

            const choiceKeys = [];
            
            choiceKeys.push({
                id: pageEl.querySelector('input[name="page-title"]').dataset.id,
                group: choiceGroup,
                // page: index + 2,
                text: pageType + pageTitle + pageType,
                itemId: '',
                minRequired: minRequired,
                maxAllowed: maxAllowed,
                cr: false,

            });
            


            const choiceKeyElements = pageEl.querySelectorAll(`.choice-key-card:not(:last-child)`);
            choiceKeyElements.forEach(choiceKeyEl => {
                const id = choiceKeyEl.dataset.id;
                const itemId = choiceKeyEl.dataset.itemid;
                const text = choiceKeyEl.dataset.text;
                const cr = choiceKeyEl.dataset.cr == 'true';

                choiceKeys.push( {
                    id: id,
                    group: choiceGroup,
                    // page: index + 2,
                    text: text,
                    itemId: itemId,
                    minRequired: minRequired,
                    maxAllowed: maxAllowed,
                    cr: cr,
                });
            })

            pages.push(choiceKeys);

        });

        // if(pages.length == 1) {
        //       pages.unshift([ {
        //         id: 0,
        //         group: choiceGroup,
        //         // page: 1,
        //         itemId: '',
        //         text: "{Literal}New Choice Key{/Literal}",
        //         minRequired: 0,
        //         maxAllowed: 0,
        //         cr: false
        //     }
        //     ]);
        // }

        return pages;
    },

   saveChoiceKeys: function() {
        var that = this;
        const pages = this.getValues();
        const choiceGroup = document.getElementById('group-selector').value;
        var sessionToken = this.getCookie();
        
        $.ajax({
            url: '/data/update-choice-keys',
            data: {
                choiceGroup: choiceGroup,
                pages: JSON.stringify(pages),
                token: sessionToken
            },
            dataType: 'json',
            type: 'POST',

            success: function (data) {
                if(data.success) {
                    M.toast({ html: '{Literal}Choice Group name changed successfully{/Literal}' });

                    that.getChoiceKeys().then( () => {
                        that.changeGroup();
                    });
                }
                else
                    M.toast({ html: '{Literal}There was a problem saving this Choice Group{/Literal}' });
            },

            error: function (e) {
                if (e.status == 523) {
                    window.location.href = "#/log-in";
                    location.reload();
                }
                else {
                    M.toast({ html: '{Literal}There was a problem saving this Choice Group{/Literal}' });
                }
            }
        });

   },

    addPage: function () {
        if(this.choiceGroup == '') {
            M.toast({ html: '{Literal}Choice Group not selected{/Literal}' });
            return;
        }

        this.isChoiceGroupChanged = true;
        this.choiceKeysPages.push([{
            itemCode: '',
            cr: true,
            noRepeat: true,
            id: 0,
            text: "*{Literal}Description{/Literal}*",
            minRequired: 0,
            maxAllowed: 0,
            id2: new Date().getTime()
        }, {
            itemCode: '',
            cr: true,
            noRepeat: true,
            id: 0,
            text: "{Literal}New Choice Key{/Literal}",
            minRequired: 0,
            maxAllowed: 0,
            id2: new Date().getTime()
        }
        ]);

        $('.tooltipped').tooltip().remove();
        this.render();
    },

    showChoiceGroupModal: function() {
        var elems = document.getElementById('new-choice-group-form-modal');
        var modal = M.Modal.init(elems, {onOpenEnd: ()=> { document.getElementById('newChoiceGroup').focus()}});
        document.getElementById('newChoiceGroup').value = '';
        modal.open();
    },

    showChoiceGroupEditModal: function() {
        if(this.choiceGroup == '') {
            M.toast({ html: '{Literal}Choice Group not selected{/Literal}' });
            return;
        }
        var elems = document.getElementById('edit-choice-group-name-modal');
        var modal = M.Modal.init(elems, {});
        document.getElementById('choiceGroupEdit').value = document.getElementById('group-selector').value;
        modal.open();
    },

    addChoiceGroup:function() {
        const groupName = document.getElementById('newChoiceGroup').value;
        this.groupNames.push(groupName);
        document.getElementById('group-selector').insertAdjacentHTML('beforeend', `<option value="${groupName}">${groupName}</option>`);
        document.getElementById('group-selector').value = groupName;
        this.changeGroup();
        
    },

    editChoiceGroupName:function() {
        const currentGroupName = document.getElementById('group-selector').value;
        const newGroupName = document.getElementById('choiceGroupEdit').value;
        const index = this.groupNames.indexOf(currentGroupName);
        this.groupNames[index] = newGroupName;

        const selectOptionEl = document.querySelector('#group-selector option[value="'+ currentGroupName +'"');
        selectOptionEl.value = newGroupName;
        selectOptionEl.innerText = newGroupName;
        document.getElementById('group-selector').value = newGroupName;
        this.isChoiceGroupChanged = true;
        
    },

    updateChoiceKeysOrder: function(el) {
        const choiceId = el.dataset.id;
        const pageIndex = el.closest('.choice-key-group-card').dataset.page;
        var that = App.choiceKeysMobileView;
        const choiceKey = that.choiceKeysPages[pageIndex].find( choice => choice.id == choiceId);        
        const childrenArray = Array.from(el.parentElement.children);
        const newChoiceKeyIndex = childrenArray.indexOf(el);
        const oldChoiceKeyIndex = that.choiceKeysPages[pageIndex].indexOf(choiceKey);

        const [item] = that.choiceKeysPages[pageIndex].splice(oldChoiceKeyIndex, 1);
        that.choiceKeysPages[pageIndex].splice(newChoiceKeyIndex + 1, 0, item); // index 0 always page title

    },

    selectAllText: function(el) {
        el.currentTarget.select();
    }
});