// $('#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
    if ($('#moreButton').length === 0) {
        var moreButton = $('<button type="button" class="btn btn-secondary" id="moreButton" aria-label="More options"><i class="bi bi-three-dots"></i></button>');

        // Anchor to the header flex container so CollapseHeaderTOC's
        // position:absolute on .divSearch does not affect button placement
        var headerContainer = $('.wh_header_flex_container');
        if (headerContainer.length === 0) headerContainer = $('.wh_header');
        headerContainer.css('position', 'relative');
        headerContainer.append(moreButton);
    }
    // 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>' +
        '<button class="dropdown-item" id="downloadPdfButton" hidden><i class="bi bi-file-earmark-pdf"></i>Download PDF</button>' +
        '<div class="dropdown-divider" id="downloadPdfSeparator" 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();
    });

    // Check whether a PDF exists at the document root using the naming convention:
    // the PDF is always named the same as its parent document folder.
    (function() {
        var knownSubdirs = ['topics', 'tasks', 'oxygen-webhelp', 'images', 'js', 'css'];
        var segments = window.location.pathname.split('/').filter(function(s) { return s !== ''; });
        var docRootSegments = null;

        for (var i = segments.length - 1; i >= 0; i--) {
            if (knownSubdirs.indexOf(segments[i].toLowerCase()) !== -1) {
                docRootSegments = segments.slice(0, i);
                break;
            }
        }

        // Fallback: doc root is the directory of the current file
        if (!docRootSegments) docRootSegments = segments.slice(0, -1);
        if (docRootSegments.length === 0) return;

        var docRootName = docRootSegments[docRootSegments.length - 1];
        var pdfUrl = '/' + docRootSegments.join('/') + '/' + docRootName + '.pdf';

        fetch(pdfUrl, { method: 'HEAD' })
            .then(function(response) {
                if (response.ok) {
                    $('#downloadPdfButton')
                        .removeAttr('hidden');
                    $('#downloadPdfSeparator')
                        .removeAttr('hidden');
                    $('#downloadPdfButton')
                        .click(function() {
                            var a = document.createElement('a');
                            a.href = pdfUrl;
                            a.download = '';
                            document.body.appendChild(a);
                            a.click();
                            document.body.removeChild(a);
                        });
                }
            })
            .catch(function() {});
    })();

    // 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
        }
    });

    //#endregion

    // Add the search button inside the input (right edge) — single actionable submit button
    if ($('#searchBtn').length === 0) {
        // Wrap the input if not already wrapped
        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%' });

        // Pad the input to make room for the button
        $('#textToSearch').css('padding-right', '40px');

        // Create the button
        var searchBtn = $('<button type="submit" id="searchBtn" aria-label="Search"><i class="bi bi-search"></i></button>');
        $('.search-input-wrapper').append(searchBtn);
    }

    /*
    // --- SEARCH / AI TOGGLE BUTTONS (commented out for future use) ---
    // Check if search mode controls exist, if not create them
    if ($('.search-mode-control').length === 0) {
        $('#textToSearch').css({ 'padding-right': '120px' });
        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%' });
        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>
        `);
        $('.search-input-wrapper').append(searchModeControl);
        // ... (styling omitted for brevity — see git history)
        if ($('#searchMode').length === 0) {
            $('#searchForm').append('<input type="hidden" id="searchMode" name="searchMode" value="fullText">');
        }
    }
    // Handle search mode toggle with event delegation
    $(document).off('click', '.search-mode-btn').on('click', '.search-mode-btn', function() {
        $('.search-mode-btn').removeClass('active').css({ 'background-color': '#eaeaea', 'color': '#333' });
        $(this).addClass('active').css({ 'background-color': '#007ac3', 'color': 'white' });
        const mode = $(this).attr('id') === 'fullTextSearchBtn' ? 'fullText' : 'aiChat';
        $('#searchMode').val(mode);
        $('#textToSearch').attr('placeholder', mode === 'fullText' ? 'Search' : 'Ask AI a question...');
    });
    // --- END TOGGLE BUTTONS ---
    */

    // 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;
        }
        // AI chat branch commented out — toggle buttons disabled
        // } else {
        //     event.preventDefault();
        //     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();
        });
    }
});

// AI chat keydown handler commented out — toggle buttons disabled
// $('#textToSearch').on('keydown', function(event) {
//     if (event.keyCode === 13 || event.key === 'Enter') {
//         const currentMode = $('#searchMode').val();
//         if (currentMode === 'aiChat') {
//             event.preventDefault();
//             handleAIChatRequest($(this).val());
//             return false;
//         }
//     }
// });

// Inject search button styles once on load
$(window).on('load', function() {
    if (!$('#search-btn-styles').length) {
        $('head').append(
            '<style id="search-btn-styles">' +
            '#searchBtn {' +
            '    position: absolute;' +
            '    right: 4px;' +
            '    top: 50%;' +
            '    transform: translateY(-50%);' +
            '    height: 88%;' +
            '    width: 34px;' +
            '    display: inline-flex;' +
            '    align-items: center;' +
            '    justify-content: center;' +
            '    background-color: #007ac3;' +
            '    color: #fff;' +
            '    border: none;' +
            '    border-radius: 3px;' +
            '    cursor: pointer;' +
            '    font-size: 14px;' +
            '    padding: 0;' +
            '    z-index: 10;' +
            '}' +
            '#searchBtn:hover { background-color: #0069a9; }' +
            '</style>'
        );
    }

    /*
    // --- TOGGLE BUTTON STYLES (commented out for future use) ---
    if (!$('#search-mode-styles').length) {
        // injected .search-mode-control / .search-mode-btn styles removed
        // see git history to restore
    }
    if ($('.search-mode-control').length > 1) {
        $('.search-mode-control:gt(0)').remove();
    }
    // --- END TOGGLE BUTTON STYLES ---
    */
});


// Stale runtime fix IIFE removed — moreButton is now anchored to
// .wh_header_flex_container in the $(document).ready block above.
