import React, { useState, useCallback, useRef } from "react";
import { Modal } from "./Modal";
import { SearchBox } from "./SearchBox";
import { Results } from "./Results";
import { Footer } from "./Footer";
import { DocSearchButton } from "./DocSearchButton";
import { useDocSearch } from "../hooks/useDocSearch";
import { useSeekoraSearch } from "../hooks/useSeekoraSearch";
import { useKeyboard } from "../hooks/useKeyboard";
export function DocSearch({ storeId, storeSecret, seekoraApiEndpoint, apiEndpoint, apiKey, sources, placeholder = "Search documentation...", maxResults = 10, debounceMs = 200, onSelect, onClose, translations = {}, renderButton = true, buttonComponent: ButtonComponent = DocSearchButton, initialOpen = false, disableShortcut = false, shortcutKey = "k", processGroupedResults, className, analyticsWriteKey, ingestHost, orgcode, xstoreid, userId, }) {
    const [isOpen, setIsOpen] = useState(initialOpen);
    const scrollSelectionIntoViewRef = useRef(false);
    const useSeekoraSDK = !!storeId;
    const seekoraSearch = useSeekoraSearch({
        storeId: storeId || "",
        storeSecret,
        apiEndpoint: seekoraApiEndpoint,
        maxResults,
        debounceMs,
        analyticsTags: ["docsearch"],
        analyticsWriteKey,
        ingestHost,
        orgcode,
        xstoreid,
        userId,
    });
    const legacySearch = useDocSearch({
        apiEndpoint,
        apiKey,
        sources,
        maxResults,
        debounceMs,
        processGroupedResults,
    });
    const { query, suggestions, isLoading, error, selectedIndex, setQuery, selectNext, selectPrev, setSelectedIndex, reset, getSelectedItem, } = useSeekoraSDK ? seekoraSearch : legacySearch;
    const groupedSuggestions = useSeekoraSDK
        ? undefined
        : legacySearch.groupedSuggestions;
    const results = useSeekoraSDK ? suggestions : legacySearch.results;
    const mode = useSeekoraSDK ? "suggestions" : legacySearch.mode;
    const searchSources = useSeekoraSDK
        ? [{ id: "seekora", name: "Results", endpoint: "" }]
        : legacySearch.sources;
    const handleOpen = useCallback(() => setIsOpen(true), []);
    const handleClose = useCallback(() => {
        setIsOpen(false);
        reset();
        onClose?.();
    }, [reset, onClose]);
    const handleSelect = useCallback((hit) => {
        if (useSeekoraSDK && seekoraSearch.trackDocClick) {
            seekoraSearch.trackDocClick(hit, selectedIndex + 1);
        }
        if (onSelect) {
            onSelect(hit);
        }
        else {
            window.location.href = hit.url;
        }
        handleClose();
    }, [onSelect, handleClose, useSeekoraSDK, seekoraSearch, selectedIndex]);
    const handleEnter = useCallback(() => {
        const selectedItem = getSelectedItem();
        if (selectedItem)
            handleSelect(selectedItem);
    }, [getSelectedItem, handleSelect]);
    const handleSelectNext = useCallback(() => {
        scrollSelectionIntoViewRef.current = true;
        selectNext();
    }, [selectNext]);
    const handleSelectPrev = useCallback(() => {
        scrollSelectionIntoViewRef.current = true;
        selectPrev();
    }, [selectPrev]);
    const { handleModalKeyDown } = useKeyboard({
        isOpen,
        onOpen: handleOpen,
        onClose: handleClose,
        onSelectNext: handleSelectNext,
        onSelectPrev: handleSelectPrev,
        onEnter: handleEnter,
        disableShortcut,
        shortcutKey,
    });
    const handleKeyDown = useCallback((event) => handleModalKeyDown(event), [handleModalKeyDown]);
    const displayHits = mode === "results" ? results : suggestions;
    return (React.createElement(React.Fragment, null,
        renderButton && (React.createElement(ButtonComponent, { onClick: handleOpen, placeholder: translations.buttonText || placeholder, className: className })),
        React.createElement(Modal, { isOpen: isOpen, onClose: handleClose, className: className },
            React.createElement("div", { className: "seekora-docsearch-modal", onKeyDown: handleKeyDown },
                React.createElement("header", { className: "seekora-docsearch-header" },
                    React.createElement(SearchBox, { value: query, onChange: setQuery, placeholder: placeholder, onClear: reset }),
                    React.createElement("button", { type: "button", className: "seekora-docsearch-close", onClick: handleClose, "aria-label": "Close search" },
                        React.createElement("span", { className: "seekora-docsearch-close-text" }, "esc"))),
                React.createElement("div", { className: "seekora-docsearch-body" },
                    React.createElement(Results, { hits: displayHits, groupedHits: groupedSuggestions, selectedIndex: selectedIndex, onSelect: handleSelect, onHover: setSelectedIndex, scrollSelectionIntoViewRef: scrollSelectionIntoViewRef, query: query, isLoading: isLoading, error: error, translations: translations, sources: searchSources })),
                React.createElement(Footer, { translations: translations })))));
}
