(function ($) {
    "use strict";

    $(document).on('change', '#chatLogSearchBYDatePickr', function () {
        chatlogSearch($(this).val(), 'date');
    })

    $(document).on('input', '#chatLogSearch', function () {
        chatlogSearch($(this).val(), 'prompt');
    })

    function chatlogSearch(search_content, type) {
        commonAjaxHelper('GET', $("#chatLogSearchRoute").val(), {
            search_content: search_content,
            type: type,
            chatbotId: $("#chatbotId").val()
        }, chatLogSearchResponse, chatLogSearchResponse);
    }

    function chatLogSearchResponse(response) {
        if (response.status === 'success') {
            $("#logList").html(response.data);
        }
    }

    $(document).on("keyup","#search", function () {
        var value = $(this).val().toLowerCase();
        $("#leadDataTable tbody tr").filter(function () {
            $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
        });
    });

    // lead data fetch
    $("#leadDataTable").DataTable({
        ordering: true,
        serverSide: true,
        processing: true,
        searching: false,
        responsive: true,
        paging: true,
        ajax: {
            url: $("#leadsListRoute").val(),
            data: {
                'chatbot_id': $("#chatbotId").val()
            }
        },
        columns: [
            {"data": "name", "name": "name"},
            {"data": "email", "name": "email"},
            {"data": "phone", "name": "phone"},
            {"data": "created_at", "name": "created_at"},
        ],
    });



    $(document).on('change', '#dateSearch', function () {

        var dateRange = $(this).val();
        let currentDate = new Date();
        let dates = dateRange.split(' to ');
        let startDate = dates[1] ? dates[0] : currentDate;
        let endDate = dates[1] ? dates[1] : dates[0];

        var fromDate = new Date(startDate);
        var toDate = new Date(endDate);
        $("#leadDataTable tbody tr").filter(function () {
            var dateText = $(this).find("td:nth-child(4)").text();
            var date = new Date(dateText);
            if (!isNaN(fromDate) && !isNaN(toDate)) {
                $(this).toggle(date >= fromDate && date <= toDate);
            } else if (!isNaN(fromDate)) {
                $(this).toggle(date >= fromDate);
            } else if (!isNaN(toDate)) {
                $(this).toggle(date <= toDate);
            } else {
                $(this).show();
            }
        });
    });


    $(document).on('click', '#webUrlAddButton', function () {

        $("#webUrlAddButton").attr("disabled", "true");
        $("#webUrlAddButton").prepend('<i class="fa fa-spinner fa-spin"></i> ');

        var url = $("#webUrlInputField").val().trim();
        var urlList = $('#urlList');
        var urlPattern = /^(https?:\/\/[^\s$.?#].[^\s]*)$/i;


        if (!urlPattern.test(url)) {
            toastr.error("Please enter a valid URL")
            $("#webUrlAddButton .fa-spin").remove();
            $("#webUrlAddButton").removeAttr("disabled");
            return;
        }

        var existingUrls = urlList.find('li span').map(function () {
            $("#webUrlAddButton .fa-spin").remove();
            $("#webUrlAddButton").removeAttr("disabled");
            return $(this).text();
        }).get();

        if ($.inArray(url, existingUrls) !== -1) {
            toastr.error("This URL has already been added.")
            $("#webUrlAddButton .fa-spin").remove();
            $("#webUrlAddButton").removeAttr("disabled");
            return;
        }

        url = url.replace(/^https?:\/\//, '');

        commonAjaxHelper('GET', $("#sourceCountRoute").val(), {
            source: url,
            type: 'url'
        }, sourceCountResponse, sourceCountResponse);
    });

    function sourceCountResponse(response) {
        if (response.status === 'success' && response.data.textCount != 0) {
            var totalSourceCount = parseInt($("#totalSourceCount").text());
            var webUrlCountShow = parseInt($("#webUrlCountShow").text());
            var webUrlSourceCountShow = parseInt($("#webUrlSourceCountShow").text());
            $("#totalSourceCount").text(totalSourceCount + response.data.textCount);
            $("#webUrlCountShow").text(webUrlCountShow + 1);
            $("#webUrlSourceCountShow").text(webUrlSourceCountShow + response.data.textCount);
            $('#urlList').append(response.data.item);
            $('#webUrlInputField').val('');
            if ($('#urlListSection').hasClass('d-none')) {
                $('#urlListSection').removeClass('d-none');
            }
        }else {
            toastr.error(response.responseJSON.message);
        }
        $("#webUrlAddButton .fa-spin").remove();
        $("#webUrlAddButton").removeAttr("disabled");
        updateUrlBoxIndices();
    }

    $(document).on('click', '.url-delete', function () {
        var totalSourceCount = parseInt($("#totalSourceCount").text());
        var webUrlCountShow = parseInt($("#webUrlCountShow").text());
        var webUrlSourceCountShow = parseInt($("#webUrlSourceCountShow").text());

        var hasCount = parseInt($(this).siblings('.count-text').val());

        $("#totalSourceCount").text(totalSourceCount - hasCount);
        $("#webUrlCountShow").text(webUrlCountShow - 1);
        $("#webUrlSourceCountShow").text(webUrlSourceCountShow - hasCount);

        $(this).closest('.url-delete-section').remove();

        if (parseInt($("#totalSourceCount").text()) == 0) {
            $('#urlListSection').addClass('d-none');
        }
    });


    $(document).on('change', '#file-input-2', function () {

        $(".source-pdf-icon i").removeClass('d-none');
        $(".source-pdf-icon img").addClass('d-none');
        $(".source-pdf-icon input").removeAttr('id');

        const selectedFiles = $(this)[0]?.files;
        const pdfFile = selectedFiles[0];


        if (selectedFiles.length == 0) {
            toastr.error("Select at least one file.");
            $(".source-pdf-icon i").addClass('d-none');
            $(".source-pdf-icon img").removeClass('d-none');
            $(".source-pdf-icon input").attr('id', 'file-input-2');
            return;
        }

        if (pdfFile.type !== 'application/pdf') {
            toastr.error('Invalid file type. Please upload a valid PDF.');
            $(".source-pdf-icon i").addClass('d-none');
            $(".source-pdf-icon img").removeClass('d-none');
            $(".source-pdf-icon input").attr('id', 'file-input-2');
            return;
        }


        const formData = new FormData();
        const csrfToken = $('meta[name="csrf-token"]').attr('content');
        formData.append('source_pdf', pdfFile);
        $.ajax({
            url: $("#pdfSourceCountRoute").val(),
            type: 'POST',
            headers: {
                'X-CSRF-TOKEN': csrfToken
            },
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                var totalSourceCount = parseInt($("#totalSourceCount").text());
                var pdfUrlCountShow = parseInt($("#pdfUrlCountShow").text());
                var pdfFileSourceCountShow = parseInt($("#pdfFileSourceCountShow").text());
                $("#totalSourceCount").text(totalSourceCount+response.data.textCount);
                $("#pdfUrlCountShow").text(1);
                $("#pdfFileSourceCountShow").text(pdfFileSourceCountShow+response.data.textCount);
            },
            error: function (xhr, status, error) {
                toastr.error(xhr.responseJSON.message);
            }
        })
        $(".source-pdf-icon i").addClass('d-none');
        $(".source-pdf-icon img").removeClass('d-none');
        $(".source-pdf-icon input").attr('id', 'file-input-2');

    });

    function sourceCountPdfResponse(response) {
        if (response.status === 'success' && response.data.textCount != 0) {
            var totalSourceCount = parseInt($("#totalSourceCount").text());
            var webUrlCountShow = parseInt($("#webUrlCountShow").text());
            var webUrlSourceCountShow = parseInt($("#webUrlSourceCountShow").text());
            $("#totalSourceCount").text(totalSourceCount + response.data.textCount);
            $("#webUrlCountShow").text(webUrlCountShow + 1);
            $("#webUrlSourceCountShow").text(webUrlSourceCountShow + response.data.textCount);
            $('#urlList').append(response.data.item);
            $('#webUrlInputField').val('');
            if ($('#urlListSection').hasClass('d-none')) {
                $('#urlListSection').removeClass('d-none');
            }
        }
        $("#webUrlAddButton .fa-spin").remove();
        $("#webUrlAddButton").removeAttr("disabled");
    }


    const initialText = $("#sourceContent").text();
    let totalC = initialText.length;
    let previousLength = initialText.length;
    let charHiden = 0;

    $(document).on('input', '#sourceContent', function () {

        var totalSourceCount = parseInt($("#totalSourceCount").text());
        if (totalSourceCount.length != 0) {
            charHiden = totalSourceCount - totalC;
        }
        let currentLength = $(this).val().length;
        if (currentLength > previousLength) {
            totalC += currentLength - previousLength;
        } else if (currentLength < previousLength) {
            totalC -= previousLength - currentLength;
        }
        previousLength = currentLength;

        charHiden = charHiden + totalC;

        $("#totalSourceCount").text(charHiden);
        $("#contentCountShow").text(1);
        $("#contentSourceCountShow").text(totalC);
    });

    $(document).ready(function () {
        // Bubble
        $(document).on('input', '#bubbleBackground', function () {
            $('#bubbleBackgroundColor').css('background-color', $(this).val());
        });
        $(document).on('change', '#bubblePosition', function (){
            let selectedPosition = $(this).val();
            if (selectedPosition === $('#bubblePositionLeft').val()) {
                $('#bubblePreview').removeClass('bot-position-fixed-right').addClass('bot-position-fixed-left');
            } else if (selectedPosition === $('#bubblePositionRight').val()) {
                $('#bubblePreview').removeClass('bot-position-fixed-left').addClass('bot-position-fixed-right');
            }
        })

        $(document).on('input','#previewBubbleIconColor', function () {
            let bubbleIconColor = $(this).val();
            $('#bubbleBackgroundColor svg').find('*').attr('fill', bubbleIconColor);
        });

        $(document).on('change','#bubbleIcon', function (e) {
            let file = e.target.files[0];
            if (file.type === 'image/svg+xml') {
                let reader = new FileReader();
                reader.onload = function (event) {
                    let svgContent = event.target.result;
                    $('#bubbleBackgroundColor').html(svgContent);
                    let bubbleIconColor = $('#previewBubbleIconColor').val();
                    $('#bubbleBackgroundColor svg').find('*').attr('fill', bubbleIconColor);
                };
                reader.readAsText(file);
            } else {
                toastr.error('Please upload an SVG file.');
                $('#bubbleBackgroundColor').html('');
                $('#bubbleIcon').val('');
            }
        });

        // Header
        $(document).on('input', '#headerTitle, #headerTitleColor', function () {
            $('#chatbotTitle').text($('#headerTitle').val()).css('color', $('#headerTitleColor').val());
        });

        $(document).on('input','#headerSubtitle, #headerSubtitleColor', function () {
            $('#chatbotSubtitle').text($('#headerSubtitle').val()).css('color', $('#headerSubtitleColor').val());
        });
        $(document).on('input','#previewHeaderBackgroundColor', function () {
            $('#chatbotHeader').css('background-color', $(this).val());
        });

        $(document).on('change','#headerLogo', function (e) {
            let file = e.target.files[0];
            let imageUrl = URL.createObjectURL(file)
            $('#previewHeaderLogo img').attr('src', imageUrl)

        });

        // Body
        $(document).on('input','#ChatbotMessageColor', function () {
            $('#ChatbotMessageText').css('color', $(this).val())
        });
        $(document).on('input','#previewBodyChatbotMessageBackground', function () {
            $('#ChatbotMessageText').css('background-color', $(this).val())
        });
        $(document).on('input','#previewBodyUserMessageColor', function () {
            $('#bodyUserMessageText').css('color', $(this).val())
        });
        $(document).on('input','#previewBodyUserMessageBackground', function () {
            $('#bodyUserMessageText').css('background-color', $(this).val())
        });
        $(document).on('input','#previewBodyBackground', function () {
            $('#bdaConvectionBotBody').css('background-color', $(this).val())
        });

        // Footer

        $(document).on('input','#previewFooterMessageColor', function () {
            $('#footerMessageText').css('color', $(this).val())
        });
        $(document).on('input','#footerBackground', function () {
            $('#chatBgChatColorFooter').css('background-color', $(this).val())
        });
        $(document).on('input','#footerMessagePlaceholderColor', function () {
            let placeholderColor = $('#footerMessagePlaceholderColor').val();
            let styleElement = document.createElement('style');
            styleElement.innerHTML = `#footerMessageText::placeholder { color: ${placeholderColor}; }`;
            document.head.appendChild(styleElement);
        });
        $(document).on('input','#footerMessagePlaceholder', function () {
            let placeholderText = $('#footerMessagePlaceholder').val();
            let placeholderColor = $('#footerMessagePlaceholderColor').val();
            $('#footerMessageText').attr('placeholder', placeholderText);
            let styleElement = document.createElement('style');
            styleElement.innerHTML = `#footerMessageText::placeholder { color: ${placeholderColor}; }`;
            document.head.appendChild(styleElement);
        });

        // style
        $('#bubbleBackgroundColor').css('background-color', $('#showBubbleBackgroundColor').val())

        $('#chatbotTitle').css('color', $('#titleColor').val());
        $('#chatbotSubtitle').css('color', $('#subtitleColor').val());
        $('#chatbotHeader').css('background-color', $('#headerBackgroundColor').val());
        $('#ChatbotMessageText').css('color', $('#bodyChatbotMessageColor').val()).css('background-color', $('#bodyChatbotMessageBackground').val());
        $('#bodyUserMessageText').css('color', $('#bodyUserMessageColor').val()).css('background-color', $('#bodyUserMessageBackground').val());
        $('#bdaConvectionBotBody').css('background-color',$('#bodyBackground').val());

        let initialColor = $('#footerMessagePlaceholderColor').val();
        let styleTag = $('<style>').html(`#footerMessageText::placeholder { color: ${initialColor}; }`);
        $('head').append(styleTag);
        $('#footerMessageText').css('color', $('#footerMessageColor').val());
        $('#chatBgChatColorFooter').css('background-color', $('#footerBackgroundColor').val())
    });


    let qaInitialText = 0;
    $('.qa-text-count').each(function (index) {
        qaInitialText = qaInitialText + parseInt($(this).val().length);
    });
    let qaTotalChar = qaInitialText;
    let qaPreviousLength = qaInitialText;
    let qaCharHidden = 0;

    $(document).on('input', '.qa-text-count', function () {

        var qaTotalSourceCount = parseInt($("#totalSourceCount").text());
        if (qaTotalSourceCount.length != 0) {
            qaCharHidden = qaTotalSourceCount - qaTotalChar;
        }
        let qaCurrentLength = 0;
        $('.qa-text-count').each(function (index) {
            qaCurrentLength = qaCurrentLength + parseInt($(this).val().length);
        });

        let toatalQa = 0;
        $('.single-qa-box').each(function (index) {
            toatalQa++;
        });

        if (qaCurrentLength > qaPreviousLength) {
            qaTotalChar += qaCurrentLength - qaPreviousLength;
        } else if (qaCurrentLength < qaPreviousLength) {
            qaTotalChar -= qaPreviousLength - qaCurrentLength;
        }
        qaPreviousLength = qaCurrentLength;

        qaCharHidden = qaCharHidden + qaTotalChar;

        $("#totalSourceCount").text(qaCharHidden);
        $("#qaCountShow").text(toatalQa);
        $("#qaSourceCountShow").text(qaTotalChar);
    });

    let sectionCount = 0;

    $(document).on('click', '#sourceQuestionAddButton', function () {
        sectionCount++;
        let newQaBlock = $('.single-qa-box:first').clone();
        newQaBlock.find('input').val('');
        newQaBlock.find('textarea').val('');
        newQaBlock.find('input').attr('name', `qas_list[${sectionCount}][question]`);
        newQaBlock.find('textarea').attr('name', `qas_list[${sectionCount}][answer]`);
        $('#qa-sections-container').prepend(newQaBlock);
        updateQABoxIndices();
    });

    $(document).on('click', '.qa-section-delete', function () {
        sectionCount--;
        var qaBox = $(this).closest('.single-qa-box');
        var questionLength = qaBox.find('input').val().length;
        var ansLength = qaBox.find('textarea').val().length;
        var totaloldLen = questionLength+ansLength;
        if (totaloldLen != 0){
            var totalSCount = parseInt($("#totalSourceCount").text());
            var totalQACount = parseInt($("#qaCountShow").text());
            var totalQACharCount = parseInt($("#qaSourceCountShow").text());

            $("#totalSourceCount").text(totalSCount - totaloldLen);
            $("#qaCountShow").text(totalQACount - 1);
            $("#qaSourceCountShow").text(totalQACharCount - totaloldLen);
        }
        qaBox.remove();
        updateQABoxIndices();
    });

    function updateQABoxIndices() {
        $('.single-qa-box').each(function (index) {
            const questionInput = $(this).find('.qas-list-question]');
            if (questionInput.length) {
                questionInput.attr('name', `qas_list[${index}][question]`);
                questionInput.attr('id', `Questions_${index}`);
            }
            // Update the answer textarea name and id
            const answerTextarea = $(this).find('.qas-list-answer');
            if (answerTextarea.length) {
                answerTextarea.attr('name', `qas_list[${index}][answer]`);
                answerTextarea.attr('id', `Answer_${index}`);
            }
        });
    }

    function updateUrlBoxIndices() {
        $('.single-url-box').each(function (index) {
            const lengthInput = $(this).find('.source-url-length');
            if (lengthInput.length) {
                lengthInput.attr('name', `source_url[${index}][length]`);
            }
            const answerTextarea = $(this).find('.source-url-url');
            if (answerTextarea.length) {
                answerTextarea.attr('name', `source_url[${index}][url]`);
            }
        });
    }

    $(document).on('click', '.pdf-source-remove', function () {
        var length = $(this).siblings('.pdfSourceLength').val();

        var totalSourceCount = parseInt($("#totalSourceCount").text());
        var pdfUrlCountShow = parseInt($("#pdfUrlCountShow").text());
        var pdfFileSourceCountShow = parseInt($("#pdfFileSourceCountShow").text());

        if (totalSourceCount > 0){
            $("#totalSourceCount").text(totalSourceCount - length);
        }
        if (pdfFileSourceCountShow > 0){
            $("#pdfUrlCountShow").text(pdfUrlCountShow - 1);
            $("#pdfFileSourceCountShow").text(pdfFileSourceCountShow - length);
        }
        $(this).parent('.bd-file-item-show').remove();
        $(".source-pdf-section").text('Choose file');
    });

    $(document).on('click', '.training-chatbot-button', function () {
        commonAjaxHelper('POST', $("#chatbotTrain").val(), {
            totalChar: $(this).data('total-character'),
            chatbotId: $("#chatbotId").val()
        }, chatTrainResponse, chatTrainResponse);
    });

    function chatTrainResponse(response){
        if (response.status === 'success') {
            toastr.success(response.message);
        } else {
            toastr.error(response.responseJSON.message);
        }
    }


    /*---------------------------------
    flatpickr area start
    -----------------------------------*/

    $(".log-date-rang").flatpickr(
        {
            mode: "range",
            dateFormat: "Y-m-d",
            defaultDate: ["2024-11-10", "2024-12-20"]
        }
    );

    /*---------------------------------
      flatpickr area end
    -----------------------------------*/


    $(document).on('change', '#selectedFont', function () {
        $("#bubblePreview").css('font-family', $(this).val());
    })

    $(document).on('change','#customFont', function(event) {
        const file = event.target.files[0];
        if (file) {
            const fileReader = new FileReader();

            fileReader.onload = function(e) {
                const fontUrl = e.target.result;

                // Create a unique font name
                const fontName = file.name.replace(/\.[^/.]+$/, "");

                // Create a new style element
                const style = `
                @font-face {
                    font-family: '${fontName}';
                    src: url('${fontUrl}');
                }
                .chat-bot-font-action {
                    font-family: '${fontName}';
                }
            `;
                // Remove existing styles related to font classes
                $('head').find('style.chat-bot-font-style').remove();

                // Append the new style to the head
                $('<style>', {
                    class: 'chat-bot-font-style',
                    text: style
                }).appendTo('head');

                // Remove any conflicting font classes
                $('.chat-bot-font-action').removeClass('arial times-new courier');
            };

            fileReader.readAsDataURL(file);
        }
    });

    $(document).on('change', '#brandingRemoveChecked', function () {
        if ($('#brandingRemoveChecked').is(':checked')){
            $(".branding-text-footer").addClass('d-none');
        }else{
            $(".branding-text-footer").removeClass('d-none');
        }
    })


})(window.jQuery);

