//quill.js custom wysiwyg inits

$(function () { // start of document ready:

    if($('#text2-editor').length != 0){

        const Link = Quill.import('formats/link');
        Link.sanitize = function(url) {
            // Always trust the custom protocol "intent
            return url;
        };
        Quill.register(Link, true);

        const quill = new Quill('#text2-editor', {
            theme: 'snow',
            formats: ['bold', 'underline', 'link', 'color'],
            modules: {
                toolbar: {
                    container: "#text2-toolbar",
                    handlers: {
                        link: function(value) {

                            // Open your custom dialog instead of Quill default
                            selectIntentDialog().then(result => {
                                if (result) {
                                    console.log('Link to set:', result);
                                    const range = quill.getSelection();
                                    if (range) {
                                        quill.format('link', result);
                                    }
                                }
                            });
                        }
                    }
                }
            }
        });

        // Custom tooltip HTML        
        $customTooltip = $('#custom-link-tooltip');

        // Tooltip state
        let currentLinkElement = null;
        let currentLinkIndex = null;
        let currentLinkLength = null;
        let weAreMiddleOfEditingQuillLinks = false;

        // Show custom tooltip
        function showCustomTooltip(linkElement, linkValue, bounds) {

            currentLinkElement = linkElement;
            currentLinkIndex = quill.getIndex(linkElement);
            currentLinkLength = linkElement.length();

            //console.log("tooptip opened: Link at index: " + currentLinkIndex + " with length: " + currentLinkLength );
            
            // Update preview
            let parsed = JSON.parse(base64Decode(linkValue));
            $('#clt-intent-type').val(parsed.intent_type);
            $('#clt-intent-data').val(parsed.intent_data);
            intentNamesPrinter($('#clt-intent-type'));

            const linkText = linkElement.domNode.innerText || linkElement.domNode.textContent; // visible text
            $('.clt-hyper-text-preview').text(linkText);

            //$('#tooltip-link-preview').attr('href', linkValue).text(linkValue);
            
            const editorBounds = quill.container.getBoundingClientRect();
            $customTooltip.css('display', 'block');
    
            // Get tooltip width for centering
            const tooltipWidth = $customTooltip.outerWidth();
            const tooltipParentWidth = $customTooltip.parent().width();
            let centerLeft = editorBounds.left + bounds.left + (bounds.width / 2) - (tooltipWidth / 2);
            
            if(centerLeft < 20){
                centerLeft = 20;
                $('.custom-tooltip-arrow').css('left', '25%');
            }else if((centerLeft + (tooltipWidth)) > tooltipParentWidth){
                centerLeft = (tooltipParentWidth - tooltipWidth) - 20;
                $('.custom-tooltip-arrow').css('left', '75%');
            }else{
                $('.custom-tooltip-arrow').css('left', '50%');
            }
            
            $customTooltip.css({
                left: centerLeft + 'px',
                top: (editorBounds.top + bounds.bottom + 5) + 'px'
            });

        }

        // Hide custom tooltip
        function hideCustomTooltip(from) {
            //console.log("Hiding custom tooltip and clearing current link vars from: " + from);
            $customTooltip.hide();
            currentLinkElement = null;
            currentLinkIndex = null;
            currentLinkLength = null;
        }

        // Edit button handler
        $('#tooltip-edit-btn').on('click', function() {

            weAreMiddleOfEditingQuillLinks = true;
            //console.log("Editing link, weAreMiddleOfEditingQuillLinks set to true");

            //const currentLink = $('#tooltip-link-preview').attr('href');
            selectIntentDialog().then(result => {
                //console.log("Result from intent dialog wia custom tooltip: " + result);
                //console.log("Editing link at index: " + currentLinkIndex + " with length: " + currentLinkLength );
                if (result && currentLinkIndex !== null) {
                    quill.formatText(currentLinkIndex, currentLinkLength, 'link', result, 'user');
                    quill.setSelection(currentLinkIndex + currentLinkLength);
                    hideCustomTooltip("final_result_section");
                    weAreMiddleOfEditingQuillLinks = false;
                    //console.log("Editing link, weAreMiddleOfEditingQuillLinks set to false");
                }
            });
        });

        // Remove link button handler
        $('#tooltip-remove-btn').on('click', function() {
            if (currentLinkIndex !== null) {
                quill.formatText(currentLinkIndex, currentLinkLength, 'link', false, 'user');
                quill.setSelection(currentLinkIndex + currentLinkLength);
            }
            hideCustomTooltip("remove_link_btn_section");
        });

        // Detect clicks on links
        quill.on('selection-change', function(range, oldRange, source) {
            if (!range) {
                hideCustomTooltip("deselection_section");
                return;
            }
            
            // Check if cursor is on a link
            const [link, offset] = quill.scroll.descendant(
                Quill.import('formats/link'),
                range.index
            );
            
            if (link) {
                const linkValue = link.domNode.getAttribute('href');
                const linkBounds = quill.getBounds(range.index);
                showCustomTooltip(link, linkValue, linkBounds);
            }else{
                if(!weAreMiddleOfEditingQuillLinks){
                    hideCustomTooltip("outside_click_section");
                }else{
                    //console.log("Not hiding tooltip because we are in the middle of editing links");
                }
            }

        });

        // Hide tooltip when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('#custom-link-tooltip').length && 
                !$(e.target).closest(quill.container).length) {
                if(!weAreMiddleOfEditingQuillLinks){
                    hideCustomTooltip("outside_click_section");
                }else{
                    //console.log("Not hiding tooltip because we are in the middle of editing links");
                }
            }
        });

        $('.clt-close').on('click', function() {
            hideCustomTooltip("close_btn_click_section");
        });

        // Prevent tooltip from closing when clicking inside
        $('#custom-link-tooltip').on('mousedown', function (e) {
            e.stopPropagation();
            e.preventDefault(); // optional: prevents focus change
        });

        // Hide default Quill tooltip
        const defaultTooltip = quill.theme.tooltip;
        if (defaultTooltip && defaultTooltip.root) {
            $(defaultTooltip.root).hide();
        }






        //other tested Quill inits:

        //load the current quill data (styled text or normal paraghraph) if exists
        let encoded = $('#text2-editor').data('current-quill-data');
        if (encoded) {
            try {
                let jsonString = base64Decode(encoded);
                //console.log("prevoius quill: " + jsonString);
                let delta = JSON.parse(jsonString);
                quill.setContents(delta);
                // Move cursor to end (after Quill finishes rendering)
                setTimeout(function () {
                    const length = quill.getLength();
                    quill.setSelection(length, 0);
                }, 100);
            } catch(e) {
                console.error("Failed to decode Quill delta", e);
            }
        }else{
            //console.log("no prevoius quill data found");
        }

        //save the quill object to the dom and get it in post_json_editor to save the data on save btn in editor page
        $('#text2-editor').data('quill', quill);

        const quill_pickr = Pickr.create({
            el: '#quill-color-picker',
            theme: 'nano',
            swatches: [
                '#F44336',
                '#F9C70E',
                '#2AB3D1',
                '#0C32F5',
                '#D11AFF',
                '#1FD4C3',
                '#15C083'
            ],
            components: {
                preview: true,
                opacity: true,
                hue: true,
                interaction: {
                    hex: true,
                    rgba: false,
                    hsla: false,
                    hsva: false,
                    cmyk: false,
                    input: true,
                    clear: false,
                    save: true
                }
            },
            i18n: {
                'btn:save': 'Save',
                'btn:cancel': 'Cancel',
                'btn:clear': 'Clear',
            }
        });

        quill_pickr.on('change', (color, instance) => {
            const hexColor = color.toHEXA().toString();
            quill.format('color', hexColor);
        });

        quill_pickr.on('save', (color, instance) => {
            const hexColor = color.toHEXA().toString();
            quill.format('color', hexColor);
            quill_pickr.hide();
        });


        quill.format('align', 'right');

        $("#align").on("change", function () {
            const val = $(this).val();
            const $editor = $("#text2-editor .ql-editor");

            // Remove old direction classes
            $editor.removeClass("quill-align-left quill-align-right quill-align-center quill-align-justify");

            // Apply new direction/alignment class
            if (val === "right") {
                $editor.addClass("quill-align-right");
                quill.format('align', 'right');
            } else if (val === "left") {
                $editor.addClass("quill-align-left");
                quill.format('align', 'left');
            } else if (val === "center") {
                $editor.addClass("quill-align-center");
                quill.format('align', 'center');
            } else if (val === "justify") {
                $editor.addClass("quill-align-justify");
                quill.format('align', 'justify');
            }
        });

        $("#text_direction").on("change", function () {
            const val = $(this).val();
            const $editor = $("#text2-editor .ql-editor");
            $editor.removeClass("quill-dir-rtl quill-dir-ltr");
            if (val === "ltr") {
                $editor.addClass("quill-dir-ltr");
            }else if (val === "rtl") {
                $editor.addClass("quill-dir-rtl");
            }
        });

        $("#color").on("change", function () {
            const val = $(this).val();
            const $editor = $("#text2-editor .ql-editor");
            $editor.css("color", val);
        });

        $("#background_color").on("change", function () {
            const val = $(this).val();
            const $editor = $("#text2-editor .ql-editor");
            const savedActiveBox = $("#box_active").val();
            if (savedActiveBox === "1") {
                $editor.css("background-color", val);
            }else{
                $editor.css("background-color", "#fff");
            }
        });

        $("#box_active").on("change", function () {
            const val = $(this).val();
            const $editor = $("#text2-editor .ql-editor");
            const savedBackgroundColor = $("#background_color").val();
            if (val === "1") {
                $editor.css("background-color", savedBackgroundColor);
            }else{
                $editor.css("background-color", "#fff");
            }
        });

        // set defalut values when first init page
        setTimeout(() => {
            const savedAlign = $("#align").val();
            const savedDirection = $("#text_direction").val();
            const savedColor = $("#color").val();
            const savedBackgroundColor = $("#background_color").val();
            const savedActiveBox = $("#box_active").val();
            $("#align").val(savedAlign).trigger("change");
            $("#text_direction").val(savedDirection).trigger("change");
            $("#color").val(savedColor).trigger("change");
            if(savedActiveBox === "1"){
                $("#background_color").val(savedBackgroundColor).trigger("change");
            }
        }, 200);
        

    }

}); //end of jqury doc ready
