function initLightbox() {
    Fancybox.bind("[data-fancybox]", {
        Toolbar: {
            display: {
                left: ["infobar"],
                middle: [],
                right: ["iterateZoom", "slideshow", "thumbs", "close"],
            },
        },
    });
}

$(document).ready(function() {
    $(document).on('submit', '#aiConversation', function(e) {
        e.preventDefault();

        let prompt = $('#prompt').val().trim();
        if ( !prompt.length ) {
            return;
        }

        // let conversationId = $('#conversationId').val();
        let form = $('#aiConversation')[0];
        let formData = new FormData(form);

        $('#systemPrompt').prop('disabled', true);
        $('#systemPrompt').removeClass('bg-light-subtle');
        $('#systemPrompt').addClass('bg-body');

        $('#prompt').prop('disabled', true);
        $('#aiSendMessage').prop('disabled', true);
        $('#aiSendMessage').html(loaderSm);

        $.ajax({
            url: '/clients/admin/ajax/send-ai-message.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                // console.log(data);

                let response = JSON.parse(data);
                let conversationId = response.conversationId;
                let optionText = response.optionText;
                let html = response.html;
                let conversationTokens = response.conversationTokens;
                console.log(response.raw);

                if ( window.history.pushState ) {
                    let url = new URL(window.location.href);
                    url.search = '?page=ai&conversationId=' + conversationId;
                    window.history.replaceState({ path: url.href }, '', url.href);
                }

                $('#conversationId').val(conversationId);
                if ( !$('#selectConversationId').val() ) {
                    $('#selectConversationId option:first-child').after($('<option>', { value: conversationId, text: optionText }));
                    $('#selectConversationId').val(conversationId);
                }
                if ( $('#newConversationWrapper').length ) {
                    $('#response').html(html);
                } else {
                    $('#response').append(html);
                }
                $('#conversationTokens').text(conversationTokens);
                let id = $('.AIResponse').last().attr('id');
                document.getElementById(id).scrollIntoView({block: 'start'});

                $('#prompt').val('');
                $('#prompt').prop('disabled', false);
                $('#prompt').attr('placeholder', 'Continue your conversation...');

                $('#files').val('');
                $('#files').change();

                $('#aiSendMessage').prop('disabled', false);
                $('#aiSendMessage').html('<i class="bi bi-send"></i>');

                // $('#aiCopyPrompt').find('i').removeClass('text-danger');
                // $('#aiClearPrompt').find('i').removeClass('text-danger');

                const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
                const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))

                initObserver();
                initLightbox();
            },
            error: function (e) {
                console.log(e);

                $('#prompt').prop('disabled', false);

                $('#aiSendMessage').prop('disabled', false);
                $('#aiSendMessage').html('<i class="bi bi-send"></i>');

                // $('#aiCopyPrompt').find('i').removeClass('text-danger');
                // $('#aiClearPrompt').find('i').removeClass('text-danger');
            }
        });
    });

    $("#prompt").keypress(function(e) {
        if ( e.which === 13 && !e.shiftKey ) {
            e.preventDefault();
            $("#aiConversation").submit();
        }
    });

    $("#prompt").keyup(function(e) {
        if ( $(this).val().trim() ) {
            $('#aiSendMessage').find('i').addClass('text-danger');
            // $('#aiCopyPrompt').find('i').addClass('text-danger');
            // $('#aiClearPrompt').find('i').addClass('text-danger');
        } else {
            $('#aiSendMessage').find('i').removeClass('text-danger');
            // $('#aiCopyPrompt').find('i').removeClass('text-danger');
            // $('#aiClearPrompt').find('i').removeClass('text-danger');
        }
    });

    $("#aiClearPrompt").click(function(e) {
        $("#prompt").val('');
        $('#aiSendMessage').find('i').removeClass('text-danger');
        // $('#aiCopyPrompt').find('i').removeClass('text-danger');
        // $('#aiClearPrompt').find('i').removeClass('text-danger');
    });

    $('#selectConversationId').on('change', function(e) {
        if ( this.value ) {
            window.location = 'https://bigtimberbuilders.com/clients/admin/?page=ai&conversationId='+this.value;
        } else {
            window.location = 'https://bigtimberbuilders.com/clients/admin/?page=ai';
        }
    });

    $(document).on('change', '#files', function(e) {
        let files = document.getElementById('files').files;
        let string = '';
        if ( files.length ) {
            for ( let i = 0; i < files.length; i++ ) {
                let comma = ( (i + 1) === files.length )
                    ? ''
                    : ', '
                ;
                string += files[i].name + comma;
            }
            $('#aiAttachment').find('i').remove();
            $('#aiAttachment').prepend('<i class="bi bi-x text-danger"></i>');
            $('#selectedFiles').text(string);
        } else {
            $('#selectedFiles').text('');
            $('#aiAttachment').find('i').remove();
            $('#aiAttachment').prepend('<i class="bi bi-paperclip"></i>');
        }
    });

    $(document).on('click', '#aiAttachment', function(e) {
        let files = document.getElementById('files').files;
        if ( files.length ) {
            e.preventDefault();

            $('#files').val('');
            $('#selectedFiles').html('');
            $('#aiAttachment').find('i').remove();
            $('#aiAttachment').prepend('<i class="bi bi-paperclip"></i>');
        }
    });

    $('#prompt').on('focus', function(e) {
        autosize(this);
    });
    $('#prompt').on('blur', function(e) {
        let h = this.offsetHeight;
        autosize.destroy(this);

        this.style.height       = h + 'px';
        this.style.overflow     = 'hidden';
        this.style.overflow     = 'hidden';
        this.style.overflowWrap = 'break-word';
        this.style.textAlign    = 'start';
    });
    $('#prompt').on('autosize:resized', function(e) {
        let h = document.getElementById('promptRow').offsetHeight;
        $('#conversationTokensContainer').css('padding-bottom', h + 'px');
    });

    $('#systemPrompt').on('focus', function(e) {
        autosize(this);
    });
    $('#systemPrompt').on('blur', function(e) {
        let h = this.offsetHeight;
        autosize.destroy(this);

        this.style.height       = h + 'px';
        this.style.overflow     = 'hidden';
        this.style.overflow     = 'hidden';
        this.style.overflowWrap = 'break-word';
        this.style.textAlign    = 'start';
    });

    var aiClipboard = new ClipboardJS('.aiCopyResponse');
    aiClipboard.on('success', function(e) {
        $(e.trigger).html('<i class="bi bi-check text-success"></i>');
        setTimeout(function() {
            $(e.trigger).html('<i class="bi bi-copy"></i>');
        }, 2000);
    });

    if ( $('#prompt').length ) {
        let h = document.getElementById('promptRow').offsetHeight;
        $('#conversationTokensContainer').css('padding-bottom', h + 'px');
    }

    initLightbox();
});