{
    function stripLiteral(literal) {
        return literal.substring(1, literal.lastIndexOf('"')).replaceAll('\\"', '"');
    }
    const searchResultsNode = document.getElementById('search-results');
    function setErrorMessage(errorString) {
        searchResultsNode.innerHTML = `<p>${errorString}</p>
<p>You can try Google search instead</p>
<form method="GET" action="https://www.google.com/search">
<input type="hidden" name="as_sitesearch" value="franz.com/agraph/support/documentation/" />
<input type="text" size="40" name="as_q" value="${searchQuery || ''}" /> &nbsp;
<input type="submit" value="Search" />
</form>
`;
        throw new Error(errorString);
    }
    searchResultsNode.innerText = 'Loading...';
    function sparqlFloatToRounded(str) {
        const match = str.match(/"([^"]+)"/);
        if (match) {
            const floatNumber = parseFloat(match[1]);
            return Math.round(floatNumber * 100);
        }
    }
    function replaceImageTag(str) {
        return str.replace(/<image from (.*?)>/g, '<p><img src="$1" /></p>');
    }
    const version = GLOBAL_AG_VERSION;
    if (!version) {
        setErrorMessage("Failed to determine AG version");
    }
    let searchQuery = new URLSearchParams(window.location.search).get('q');
    searchQuery = searchQuery && searchQuery.trim();
    if (!searchQuery) {
        setErrorMessage("Empty search query");
    }
    const questionPart = `<h3>Question:</h3><p>${searchQuery}</p><h3>Answer:</h3>`;
    searchResultsNode.innerHTML = `${questionPart}<p>Loading...</p>`;
    const requestUrl = new URL('/search-ag-docs', window.location.origin);
    requestUrl.searchParams.set('agversion', version);
    requestUrl.searchParams.set('question', searchQuery);
    fetch(requestUrl.toString())
        .then(response => {
            if (!response.ok) {
                setErrorMessage('Error response for the question');
            }
            return response.json();
        })
        .then(data => {
            if (!Array.isArray(data)) {
                setErrorMessage('Unexpected response structure');
                return;
            }
            if (data.length === 0) {
                setErrorMessage('No search results available');
            }
            const answer = stripLiteral(data[0][0]);
            searchResultsNode.innerHTML = `${questionPart}
<p>${answer}</p>
<h3>Reference(s) to documentation:</h3>
<ol>
    ${data.map(([_, confidence, htmlReference, documentationQuote, displayName]) => {
                const confidenceInPercents = sparqlFloatToRounded(confidence);
                const withConfidenceMessage = confidenceInPercents === undefined ? '' : `with ${confidenceInPercents}% confidence`;
                const htmlReferenceBase = '<http://franz.com/file-with-xpath/';
                const interestingHtmlReference = htmlReference.substring(htmlReferenceBase.length, htmlReference.length - 1).replaceAll('\\\\u0022', '"');
                const [href, encodedXpath] = interestingHtmlReference.split(';');
                const relatedDocLink = `${href}?xpath=${encodedXpath}`;
                return `<li>${relatedDocLink && withConfidenceMessage ? `Related document <a href="${relatedDocLink}">${displayName}</a> ${withConfidenceMessage}:` : ''}
<blockquote>${replaceImageTag(stripLiteral(documentationQuote))}</blockquote>
</li>`
            }).join('')}
</ol>`
        })
        .catch(error => {
            console.error(error);
            setErrorMessage(`Error response for the question`);
        });
}
