// $('#searchForm div').addClass('divSearch');

$(document).ready(function() {
    // Remove any existing submit handlers from the search form
    $('#searchForm').off('submit');

    //#region More button and menu
    // Create the three-dots button
    var moreButton = $('<button type="button" class="btn btn-secondary" ' +
        'id="moreButton" aria-label="More options">' +
        '<i class="bi bi-three-dots-vertical"></i>' +
        '</button>');
    // Append the button to the body or another container
    $('body').append(moreButton);

    $('#moreButton').css({
        position: 'absolute',
        top: '20px',
        right: '20px',
        fontSize: 'x-large',
        color: '#ffffff',
        backgroundColor: '#85bc20',
        border: 'none',
    });

    // Create the menu
    var moreMenu = $('<div id="moreMenu" class="dropdown-menu">' +
        '<button class="dropdown-item" id="learnWebhelp"><i class="bi bi-mortarboard"></i>Learn about Webhelp features  <i class="bi bi-box-arrow-up-right"></i></button>' +
        '<div class="dropdown-divider"></div>' + 
        '<button class="dropdown-item" id="clearSessionStorage"><i class="bi bi-arrow-clockwise"></i>Reload page (F5)</button>' +
        '<button class="dropdown-item" id="clearLocalStorage"><i class="bi bi-trash"></i>Clear local storage and reload page</button>' +
        '<div class="dropdown-divider" id="logoutSeparator" hidden></div>' + 
        '<button class="dropdown-item" id="printButton"><i class="bi bi-printer"></i>Print page (Ctrl+P)</button>' +
        '<div class="dropdown-divider" id="logoutSeparator" hidden></div>' + 
        '<button class="dropdown-item" id="logoutButton" hidden><i class="bi bi-door-closed"></i>Logout</button>' +
        '</div>');
        
    // Style the menu
    moreMenu.css({
        position: 'absolute',
        display: 'none', // Initially hidden
        backgroundColor: '#ffffff',
        border: '1px solid #ccc',
        borderRadius: '8px',
        padding: '10px',
        boxShadow: '0 4px 8px rgba(0, 0, 0, 0.1)',
        zIndex: 1000,
        width: 'fit-content',
    });

    // Append the menu to the body
    $('body').append(moreMenu);

    $("#logoutButton").click(function() {
        window.location.href = "/Logout.ashx";
    });

    // Toggle the menu on button click
    $('#moreButton').click(function() {
        // Get button position and size
        var buttonOffset = $(this).offset();
        var buttonHeight = $(this).outerHeight();
        var buttonWidth = $(this).outerWidth();
        
        // Position the menu right-aligned with the button
        moreMenu.css({
            top: buttonOffset.top + buttonHeight, // Position it below the button
            left: buttonOffset.left + buttonWidth - moreMenu.outerWidth() // Right-align it with the button
        });

        // Show/hide the menu
        moreMenu.toggle();
    });

    // Add hover effect to change background color
    $('#moreButton').hover(
        function() { // On mouse over
            $(this).css('backgroundColor', '#a3d34f'); // Lighter shade of #85bc20
        },
        function() { // On mouse out
            $(this).css('backgroundColor', '#85bc20'); // Original color
        }
    );

    // Attach function to Webhelp Learning
    $('#learnWebhelp').click(function() {
        window.open('/InfoDev/Using%20InfoDev%20WebHelp/index.html', '_blank');
    });

    // Attach function to clear local storage
    $('#clearLocalStorage').click(function() {
        localStorage.clear(); // Clears local storage for the current domain
        alert('Local storage cleared!');
        location.reload(true); // Force a reload, bypassing cache
    });

    // Attach function to clear session storage and reload page
    $('#clearSessionStorage').click(function() {
        // Clear session storage for the current domain
        // sessionStorage.clear();
        location.reload(true); // Force a reload, bypassing cache
    });

    // Attach function to print button
    $('#printButton').click(function() {
        window.print();
    });

    // Hide the menu when clicking outside of it
    $(document).click(function(event) {
        var target = $(event.target);
        // Check if the click is outside of the moreButton or moreMenu
        if (!target.closest('#moreButton').length && !target.closest('#moreMenu').length) {
            moreMenu.hide(); // Hide the menu
        }
    });

    // Append the button to the right side of the header
    $('#searchForm').append(moreButton); // Append button to the flex container
    //#endregion

    // Check if search mode controls exist, if not create them
    if ($('.search-mode-control').length === 0) {
        console.log('No search mode controls found in header.js, creating them');
        
        // Modify the textToSearch input to add padding for our buttons
        $('#textToSearch').css({
          'padding-right': '120px' // Adjusted padding to prevent overflow
        });

        // Create a wrapper for the search box to allow absolute positioning
        if (!$('#textToSearch').parent().hasClass('search-input-wrapper')) {
            $('#textToSearch').wrap('<div class="search-input-wrapper"></div>');
        }
        
        $('.search-input-wrapper').css({
          'position': 'relative',
          'display': 'inline-block',
          'width': '100%'
        });
        
        // Create segmented control for search modes
        const searchModeControl = $(`
            <span class="search-mode-control">
              <button type="button" class="search-mode-btn active" id="fullTextSearchBtn">
                <span class="search-btn-text">
                <i class="bi bi-search"></i>
                </span>
              </button>
              <button type="button" class="search-mode-btn" id="aiChatBtn">
                <span class="search-btn-text">
                    <i class="bi bi-chat"></i>
                </span>
              </button>
            </span>
          `);
        
        // Insert control inside the search input wrapper
        $('.search-input-wrapper').append(searchModeControl);
        
        // Style the control for in-input positioning with improved alignment
        $('.search-mode-control').css({
          'position': 'absolute',
          'display': 'inline-flex',
          'right': '12px', 
          'top': '50%',
          'transform': 'translateY(-50%)',
          'height': '88%',
          'z-index': '10',
        //   'background-color': 'white',
          'border-radius': '0', // Remove border radius from container
          'overflow': 'hidden',
        //   'border': '1px solid #ccc',
          'box-sizing': 'border-box',
          'margin': '0',
          'padding': '0'
        });
        
        $('.search-mode-btn').css({
          'background': '#eaeaea',
          'border': 'none',
          'border-right': '1px solid #ccc',
          'padding': '0 8px',
          'margin': '0',
          'cursor': 'pointer',
          'height': '100%', // Ensure 100% height
          'color': '#333',
          'font-weight': 'normal',
          'min-width': '50px',
          'font-size': '12px',
          'text-align': 'center',
          'display': 'flex',
          'align-items': 'center',
          'justify-content': 'center',
          'box-sizing': 'border-box',
          'border-radius': '0' // Reset border radius for all buttons
        });
        
        $('.search-mode-btn:first-child').css({
            'border-radius': '0' // Square corners for first button
        });
        
        $('.search-mode-btn:last-child').css({
            'border-right': 'none',
            'border-top-right-radius': '3px',
            'border-bottom-right-radius': '3px'
        });
        
        $('.search-mode-btn.active').css({
          'background-color': '#007ac3',
          'color': 'white'
        });

        /* Make sure the SVG is visible and properly sized */
        $('#aiChatBtn svg').css({
            'display': 'inline-block',
            'vertical-align': 'middle',
            'margin-right': '4px',
            'fill': 'currentColor'
        });
        
        $('#aiChatBtn').css({
            'display': 'flex',
            'align-items': 'center',
        });
        
        // Ensure the button text is centered and doesn't have extra space
        $('.search-btn-text').css({
          'display': 'inline-block',
          'line-height': '1',
          'padding': '0',
          'margin': '0'
        });
        
        // Add hidden input field to track the current search mode (if not already present)
        if ($('#searchMode').length === 0) {
            $('#searchForm').append('<input type="hidden" id="searchMode" name="searchMode" value="fullText">');
        }
    }
    
    // Handle search mode toggle with event delegation - only set up once
    $(document).off('click', '.search-mode-btn').on('click', '.search-mode-btn', function() {
        console.log('Search mode button clicked:', $(this).attr('id'));
        
        // Remove active class from all buttons
        $('.search-mode-btn').removeClass('active').css({
            'background-color': '#eaeaea',
            'color': '#333'
        });
        
        // Add active class to clicked button
        $(this).addClass('active').css({
            'background-color': '#007ac3',
            'color': 'white'
        });
        
        // Update search mode value
        const mode = $(this).attr('id') === 'fullTextSearchBtn' ? 'fullText' : 'aiChat';
        $('#searchMode').val(mode);
        
        // Update placeholder text based on the selected mode
        if (mode === 'fullText') {
            $('#textToSearch').attr('placeholder', 'Search');
        } else {
            $('#textToSearch').attr('placeholder', 'Ask AI a question...');
        }
    });

    // Call CollapseHeaderTOC after the document is ready
    CollapseHeaderTOC();

    function CollapseHeaderTOC() {
    if (
        Variables.IsAssumptions ||
        Variables.IsAuthRNArchives ||
        Variables.IsExpereImpGuide ||
        Variables.IsFormsDesignUG ||
        Variables.IsMortgage || 
        Variables.IsSecAdmin || 
        Variables.IsSecAdminSelfHosted || 
        Variables.IsVanceo
    ) {
        // Set the divSearch to use flexbox
        $('.divSearch').css({
            'display': 'flex', // Use flexbox for layout
            'align-items': 'center', // Center items vertically
            'position': 'absolute', // Set position to absolute
            'width': '400px'
        });

        // Report the height of the header toc and adjust
        $('.wh_top_menu').addClass("collapse");
        var b = $('<input type="button" class="btn btn-primary" id="collapsebutton" value="Hide TOC"/>');

        // Append the button to the divSearch
        if (Variables.IsExpereImpGuide) {
            $('div.divSearch').append(b); // Append button to divSearch
        } else {
            $(b).insertAfter('#btnLogout'); // If not, insert after #btnLogout
        }

        $('#collapsebutton').click(function() {
            if ($('#collapsebutton').attr('value') == 'Show TOC') {
                $('.wh_top_menu').removeClass("collapse");
                $('#collapsebutton').attr('value', 'Hide TOC');
            } else {
                $('.wh_top_menu').addClass("collapse");
                $('#collapsebutton').attr('value', 'Show TOC');
            }
        });

        var toc_height = $('.wh_top_menu').height();
        if (toc_height >= 60) {
            $('.wh_top_menu').addClass("collapse");
            $('#collapsebutton').attr('value', 'Show TOC');
        } else {
            $('.wh_top_menu').removeClass("collapse");
            $('#collapsebutton').attr('value', 'Hide TOC');
        }
    }
    }

    // Intercept the search form submission
    $('#searchForm').off('submit').on('submit', function(event) {
        console.log('searchForm submitted');
        
        // Get the current search mode
        const searchMode = $('#searchMode').val();
        
        // Capture the search term
        const searchTerm = $('#textToSearch').val();
        
        // Handle based on selected mode
        if (searchMode === 'fullText' || !searchMode) {
            // Send the search term to the PHP file via AJAX for analytics
            $.ajax({
                type: 'POST',
                url: '/feedback/submit-search.php',
                data: { 
                    searchTerm: searchTerm,
                    searchMode: 'fullText' 
                },
                dataType: 'json',
                success: function(response) {
                    console.log('search term submitted');
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.error("Error submitting search term:", textStatus, errorThrown);
                }
            });
            
            // Continue with default search form submission
            return true;
        } else {
            // Prevent the default form submission for AI chat
            event.preventDefault();
            
            // Handle AI chat functionality
            handleAIChatRequest(searchTerm);
        }
    });

    // Function to handle AI chat requests
    function handleAIChatRequest(query) {
        // Show a loading indicator
        const searchResultsContainer = $('.wh_search_results') || $('.wh_content_area');
        searchResultsContainer.html('<div class="ai-chat-loader">Consulting AI, please wait...</div>');
        
        // Call your AI function here
        processAIChatQuery(query, searchResultsContainer);
    }

    // Function placeholder for AI chat query processing
    function processAIChatQuery(query, resultContainer) {
        // TODO: Implement the actual AI chat functionality
        console.log("Processing AI chat query:", query);
        
        // This is a placeholder - replace with actual AI implementation
        // For now, we'll just display a message to show the function is being called
        setTimeout(function() {
            const demoResponse = {
                answer: "This is a placeholder response for your query: '" + query + "'. The actual AI functionality will be implemented here.",
                references: [
                    { title: "Sample Documentation", url: "#" }
                ]
            };
            displayAIResponse(demoResponse, query);
        }, 1000);
    }
    
    // Function to handle AI chat requests
    function handleAIChatRequest(query) {
        // Show a loading indicator
        const searchResultsContainer = $('.wh_search_results') || $('.wh_content_area');
        searchResultsContainer.html('<div class="ai-chat-loader">Consulting AI, please wait...</div>');

        // Send the query to your AI endpoint using fetch
        fetch('https://6gb7q5qvl4vnvpotkkpxnsu4uy0tmxby.lambda-url.us-east-1.on.aws/agent/a-experewebhelpagent/send_message', {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
                'x-user-id': 'test',
                'x-authentication': 'api-key 71153F8904B611F34801E016:7eabb93e40460261b8642ef1e1732fb2',
                'x-workspace-id': 'lotsofexpereience',
            },
            body: JSON.stringify({
                "input": {
                    "expyId": "lotsofexpereience",
                    "source": "Expere_Webhelp_RE4",
                    "persistent": true,
                    "messages": [
                        {
                            "role": "user",
                            "payload": {
                                "content":"What are the first steps"
                            },
                            "context": {
                                "contentFilters": []
                            }
                        }
                    ]
                }
            }),
        })
        .then(response => response.json())
        .then(parsedResponse => {
            // Forward the parsed response to the displayAIResponse function
            displayAIResponse(parsedResponse, query);
        })
        .catch(error => {
            console.error("Error with AI chat:", error);
            searchResultsContainer.html('<div class="error-message">Sorry, there was an error connecting to the AI service. Please try again later.</div>');
        });
    }
    
    // Function to display AI chat response
    function displayAIResponse(response, originalQuery) {
        const searchResultsContainer = $('.wh_search_results') || $('.wh_content_area');
        
        // Create a chat-like UI for the response
        const chatUI = `
            <div class="ai-chat-container">
                <h2>AI Assistant Response</h2>
                <div class="chat-exchange">
                    <div class="user-query">
                        <strong>You asked:</strong>
                        <p>${originalQuery}</p>
                    </div>
                    <div class="ai-response">
                        <strong>AI response:</strong>
                        <div class="response-content">${response.answer}</div>
                    </div>
                </div>
                ${response.references ? `
                <div class="ai-references">
                    <h3>Related pages:</h3>
                    <ul>${response.references.map(ref => `<li><a href="${ref.url}">${ref.title}</a></li>`).join('')}</ul>
                </div>` : ''}
                <div class="ai-chat-footer">
                    <button class="btn btn-primary" id="newAiQuestion">Ask another question</button>
                    <button class="btn btn-secondary" id="switchToSearch">Switch to regular search</button>
                </div>
            </div>
        `;
        
        searchResultsContainer.html(chatUI);
        
        // Handle "Ask another question" button
        $('#newAiQuestion').click(function() {
            $('#textToSearch').focus().select();
        });
        
        // Handle "Switch to regular search" button
        $('#switchToSearch').click(function() {
            $('#fullTextSearchBtn').click();
            $('#searchForm').submit();
        });
    }
});

$('#textToSearch').on('keydown', function(event) {
    // Check if the key pressed is Enter (key code 13)
    if (event.keyCode === 13 || event.key === 'Enter') {
      // Get the current search mode
      const currentMode = $('#searchMode').val();
      
      // If the current mode is AI Chat, prevent default form submission
      if (currentMode === 'aiChat') {
        event.preventDefault();
        
        // Get the search term
        const searchTerm = $(this).val();
        
        // Call the AI chat function with the search term
        handleAIChatRequest(searchTerm);
        
        // Return false to prevent further propagation
        return false;
      }
      // For fullText mode, allow the default form submission behavior
    }
  });

// Add styles directly to the head, but only once
$(window).on('load', function() {
    // Check if our styles are already added
    if (!$('#search-mode-styles').length) {
        $('head').append(`
            <style id="search-mode-styles">
                .search-input-wrapper {
                    position: relative;
                    display: inline-block;
                    width: 100%;
                }
                
                .search-mode-control {
                    position: absolute;
                    display: inline-flex;
                    right: 5px;
                    top: 50%;
                    transform: translateY(-50%);
                    height: 100%;
                    z-index: 10;
                    background-color: white;
                    border-radius: 0;
                    overflow: hidden;
                    border: 1px solid #ccc;
                    box-sizing: border-box;
                    margin: 0;
                    padding: 0;
                }
                
                .search-mode-btn {
                    background: #eaeaea;
                    border: none;
                    border-right: 1px solid #ccc;
                    padding: 0 8px;
                    margin: 0;
                    cursor: pointer;
                    height: 100%;
                    color: #333;
                    font-weight: normal;
                    min-width: 50px;
                    font-size: 12px;
                    text-align: center;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    box-sizing: border-box;
                    border-radius: 0;
                }
                
                .search-mode-btn:first-child {
                    border-radius: 0;
                }
                
                .search-mode-btn:last-child {
                    border-right: none;
                    border-top-right-radius: 6px;
                    border-bottom-right-radius: 6px;
                }
                
                .search-mode-btn.active {
                    background-color: #007ac3;
                    color: white;
                }
                
                .search-mode-btn:hover {
                    background-color: #d8d8d8;
                }
                
                .search-mode-btn.active:hover {
                    background-color: #0069a9;
                }
                
                .search-btn-text {
                    display: inline-block;
                    line-height: 1;
                    padding: 0;
                    margin: 0;
                }
                
                /* Fix search form layout */
                #searchForm {
                    display: flex;
                    align-items: center;
                }
                
                .divSearch.input-group {
                    display: flex !important;
                    align-items: center;
                }
                
                /* Add padding to make room for the buttons */
                #textToSearch {
                    padding-right: 120px;
                }
            </style>
        `);
    }
    
    // Remove any duplicate search mode controls
    if ($('.search-mode-control').length > 1) {
        console.warn('Cleaning up duplicate search mode controls');
        $('.search-mode-control:gt(0)').remove();
    }
    
    console.log('Search mode buttons found (window.load):', $('.search-mode-btn').length);
});

