
jQuery(document).ready(function($) {
    let chatHistory = [];

    let chatResults = chatHistory.map(function(item) {
        return '<div class="ai-assistant-for-wpadmin-result user"><div class="ai-assistant-for-wpadmin-result-text">' + item.question + '</div></div>' +
            '<div class="ai-assistant-for-wpadmin-result ai"><div class="ai-assistant-for-wpadmin-result-text">' + item.answer + '</div></div>';
    }
    ).join('');
    $("#ai-assistant-for-wpadmin-results").html(chatResults);
    const $chatbox = $('#ai-assistant-for-wpadmin-chatbox');
    const $container = $('#ai-assistant-for-wpadmin-chatbox-container');
    
    if ($chatbox.length && $container.length) {
        // Dashboard page
        if ($('#welcome-panel').length) {
            $container.insertAfter('#welcome-panel');
        }
    
        // Plugin pages like Akismet
        if ($('.akismet-masthead').length) {
            $container.insertAfter('.akismet-masthead');
        }
    
        // Post edit page
        if ($('.wp-header-end').length) {
            $container.insertAfter('.wp-header-end');
        }
    
        // Settings or admin pages
        if ($('.wrap h1').length) {
            $container.insertAfter('.wrap h1:first');
        } else if ($('.wrap h2').length) {
            $container.insertAfter('.wrap h2:first');
        }

        // Dashboard sitegrond .sg-title
        if ($('.sg-title').length) {
            $container.insertAfter('.sg-title');
        }            
        if ($('.woocommerce-layout__main').length) {
            $container.insertBefore('.woocommerce-layout__main');
        }
        // Final fallback
        if (!$container.parent().length) {
            $('body').append($container);
        }
    }
    
    
    $('#ai-assistant-for-wpadmin-chatbox-input').on('input', function() {
        if ($(this).val().length > 0) {
            $('#ai-assistant-for-wpadmin-chatbox-send').removeClass('disabled');
        } else {
            $('#ai-assistant-for-wpadmin-chatbox-send').addClass('disabled');
        }
    });
    $('#ai-assistant-for-wpadmin-chatbox-send').on('click', function () {
        //avoid sending any prompt request unless the user has atleast 3 words in the prompt #10
        if ($('#ai-assistant-for-wpadmin-chatbox-input').val().trim().split(/\s+/).length < 3) {
            alert('Oops—need more context. Try again with more detail.');
            return;
        }
        if ($(this).hasClass('disabled')) return;
        let $this = $(this);
        // $this.addClass('loading');
        // dipatch loading event
        $this.trigger('loading');
        const question = $('#ai-assistant-for-wpadmin-chatbox-input').val();
        const nonce = $('#ai_assistant_for_the_wpadmin_nonce').val();
        const context = $('#ai-assistant-for-wpadmin-chatbox-context').val();
        const pathUrl = $("#ai-assistant-for-wpadmin-chatbox-path-url").val();
        $('#ai-assistant-for-wpadmin-chatbox-input').val('');
      
        // Append question and loader UI
        const newQuestion = `<div class="ai-assistant-for-wpadmin-result user"><div class="ai-assistant-for-wpadmin-result-text">${question}</div></div>`;
        const newAnswer = `<div class="ai-assistant-for-wpadmin-result ai"><div class="ai-assistant-for-wpadmin-result-text"><span class="loading-icon"></span></div></div>`;
        $('#ai-assistant-for-wpadmin-results').append(newQuestion + newAnswer);
        $('#ai-assistant-for-wpadmin-results').scrollTop($('#ai-assistant-for-wpadmin-results')[0].scrollHeight);
      
        // Placeholder for history
        chatHistory.unshift({ question: question, answer: '<span class="loading-icon"></span>' });
        $.ajax({
          url: ajaxurl,
          type: 'POST',
          data: {
            action: 'handle_chat_message',
            question: question,
            context: context,
            pathUrl: pathUrl,
            nonce: nonce
          },
          success: function (response) {
            // Update UI
            const container = $('#ai-assistant-for-wpadmin-results .ai-assistant-for-wpadmin-result.ai:last .ai-assistant-for-wpadmin-result-text');
            container.html(response.data);
      
            // Highlight code
            container.find('pre code').each(function () {
              const lang = this.className.replace('language-', '') || 'code';
              const pre = $(this).closest('pre');
              pre.wrap('<div class="code-block"></div>');
              const wrapper = pre.parent('.code-block');
              wrapper.prepend(`
                <div class="code-header">
                  <span class="code-lang">${lang}</span>
                  <button class="copy-code">Copy</button>
                </div>
              `);
              hljs.highlightElement(this);
            });
            $this.trigger('loaded');
            // add target="_blank" to all links in the response
            container.find('a').each(function () {
              $(this).attr('target', '_blank');
            });
            // clean 【\d+†source】
            container.html(container.html().replace(/【\d+†source】/g, ''));
            
            chatHistory[0].answer = response.data;
            const $results = $('#ai-assistant-for-wpadmin-results');
            const $lastMessage = $results.children().last();
            const offsetTop = $lastMessage[0].offsetTop;
            const containerHeight = $results.height();
            $results.scrollTop(offsetTop - containerHeight / 2);

          }
        });
    });
    $('#ai-assistant-for-wpadmin-chatbox-send').on('loading', function () {
        $('#ai-assistant-for-wpadmin-chatbox-input').attr('disabled', true);
        $(this).addClass('loading');
    });
    $('#ai-assistant-for-wpadmin-chatbox-send').on('loaded', function () {
        $('#ai-assistant-for-wpadmin-chatbox-input').attr('disabled', false);
        $(this).removeClass('loading');
        $('.ai-assistant-for-wpadmin-chatbox-container').addClass('open');
        $('.ai-assistant-for-wpadmin-chatbox-close').removeClass('hidden');
        $('.ai-assistant-for-wpadmin-chatbox-minimize').removeClass('hidden');
        $('.ai-assistant-for-wpadmin-results').removeClass('hidden');
        $('body').addClass('no-scroll');
    });
      
    // on click enter send message & on click enter with shift add new line
    $('#ai-assistant-for-wpadmin-chatbox-input').on('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            $('#ai-assistant-for-wpadmin-chatbox-send').trigger('click');
        }
    });
    $('#ai-assistant-for-wpadmin-chatbox-input').on('keydown', function(e) {
        if (e.key === 'Enter' && e.shiftKey) {
            e.preventDefault();
            $(this).val($(this).val() + '\n');
        }
    });
    $('.ai-assistant-for-wpadmin-chatbox-close').on('click', function() {
        $('.ai-assistant-for-wpadmin-chatbox-container').removeClass('open');
        $(this).addClass('hidden');
        $('.ai-assistant-for-wpadmin-results').addClass('hidden');
        $('body').removeClass('no-scroll');
    });
    $('.ai-assistant-for-wpadmin-chatbox-minimize').on('click', function () {
        const container = $('.ai-assistant-for-wpadmin-chatbox-container');

        container.addClass('minimized');

        setTimeout(() => {
            container.removeClass('open');
            $(this).addClass('hidden');
            $('.ai-assistant-for-wpadmin-results').addClass('hidden');
            $('body').removeClass('no-scroll');
            $('.ai-assistant-reopen-button').removeClass('hidden');
        }, 300); // match transition duration
    });

    $('.ai-assistant-reopen-button').on('click', function () {
        $('.ai-assistant-for-wpadmin-chatbox-container')
            .removeClass('minimized')
            .addClass('open');

        $('.ai-assistant-for-wpadmin-chatbox-minimize').removeClass('hidden');
        $('.ai-assistant-reopen-button').addClass('hidden');
        $('body').addClass('no-scroll');
    });

    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('.ai-assistant-for-wpadmin-chatbox-container').removeClass('open');
            $('.ai-assistant-for-wpadmin-chatbox-close').addClass('hidden');
            $('.ai-assistant-for-wpadmin-chatbox-minimize').addClass('hidden');
            $('.ai-assistant-for-wpadmin-results').addClass('hidden');
            $('body').removeClass('no-scroll');
        }
    });
    $(document).on('click', '.copy-code', function () {
        const btn = $(this);
        const code = btn.closest('.code-block').find('code').text();
    
        const setCopied = () => {
            const original = btn.html();
            btn.html('Copied');
            setTimeout(() => btn.html(original), 1000);
        };
    
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(code).then(() => {
                setCopied();
            }).catch(() => {
                fallbackCopy(code, btn);
            });
        } else {
            fallbackCopy(code, btn);
        }
    });
    
    function fallbackCopy(text, btn) {
        const textarea = document.createElement('textarea');
        textarea.value = text;
        textarea.style.position = 'fixed';
        textarea.style.opacity = '0';
        document.body.appendChild(textarea);
        textarea.select();
        try {
            document.execCommand('copy');
            const original = btn.html();
            btn.html('Copied');
            setTimeout(() => btn.html(original), 1000);
        } catch (e) {
            btn.html('Failed');
        }
        document.body.removeChild(textarea);
    }
});