import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/*
* Copyright (c) 2020-present SMC Treviso s.r.l. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
import { useTranslation } from "react-i18next";
import { ModalDetail } from "./ModalDetail";
import { useClickAway } from "./useClickAway";
import React from "react";
import { css } from "styled-components";
import { ArrowLeftSvg } from "../svgElement/ArrowLeftSvg";
import { SearchSvg } from "../svgElement/SearchSvg";
import { DeleteLogo } from "./DeleteLogo";
export function SearchMobile({ configuration, spans, selectionsState, selectionsDispatch, onDetail, showSyntax, isMobile, isVisible, btnSearch = false, setIsVisible, }) {
    const autoSelect = configuration.searchAutoselect;
    const replaceText = configuration.searchReplaceText;
    const [openedDropdown, setOpenedDropdown] = React.useState(null);
    const clickAwayRef = React.useRef(null);
    useClickAway([clickAwayRef], () => setOpenedDropdown(null));
    const inputRef = React.useRef(null);
    const [adjustedSelection, setAdjustedSelection] = React.useState({ selectionStart: 0, selectionEnd: 0 });
    React.useLayoutEffect(() => {
        if (inputRef.current) {
            inputRef.current.selectionStart = adjustedSelection.selectionStart;
            inputRef.current.selectionEnd = adjustedSelection.selectionEnd;
        }
    }, [adjustedSelection]);
    const { t } = useTranslation();
    React.useEffect(() => {
        if (isVisible && inputRef.current) {
            inputRef.current?.focus();
        }
    }, [isVisible]);
    const { setText, search, clearSearch } = setValueSearch({
        isBtn: btnSearch,
        selectionsDispatch: selectionsDispatch,
    });
    const componet = (_jsx(React.Fragment, { children: _jsxs("div", { css: css `
          @media (max-width: 480px) {
            padding-inline: 15px;
            display: flex;
            flex-direction: column;
            gap: 20px;
            height: 100%;
            background-color: #d4d4d8;
          }
        `, children: [_jsx("div", { className: "openk9--search-container", css: css `
            margin-top: 12px;
            display: flex;
            align-items: center;
            gap: 10px;
            width: 100%;
            @media (max-width: 480px) {
              flex-direction: column;
              margin-top: 15px;
            }
            .openk9-focusable:has(input:focus) {
              border: 1px solid #c22525;
            }
          `, children: _jsxs("div", { ref: clickAwayRef, className: "openk9-embeddable-search--input-container openk9-focusable", css: css `
              display: flex;
              align-items: center;
              border-radius: 40px;
              width: 100%;
              max-height: 50px;
              @media (max-width: 480px) {
                width: 100%;
                max-height: 40px;
              }
            `, children: [_jsx("button", { css: css `
                border: none;
                background: inherit;
                margin-left: 7px;
                margin-top: 7px;
              `, onClick: () => {
                                    if (setIsVisible)
                                        setIsVisible(false);
                                }, children: _jsx(ArrowLeftSvg, { size: "20" }) }), _jsxs("div", { className: "openk9--search-container-show-syntax", css: css `
                flex-grow: 1;
                position: relative;
                display: flex;
              `, children: [_jsx("div", { className: "openk9--search-show-syntax", css: css `
                  top: 0px;
                  left: 0px;
                  padding: var(--openk9-embeddable-search--input-padding);
                  display: flex;
                  position: absolute;
                ` }), _jsx("label", { htmlFor: "search-openk9-modal", className: "visually-hidden", css: css `
                  border: 0;
                  padding: 0;
                  margin: 0;
                  position: absolute !important;
                  height: 1px;
                  width: 1px;
                  overflow: hidden;
                  clip: rect(
                    1px 1px 1px 1px
                  ); /* IE6, IE7 - a 0 height clip, off to the bottom right of the visible 1px box */
                  clip: rect(
                    1px,
                    1px,
                    1px,
                    1px
                  ); /*maybe deprecated but we need to support legacy browsers */
                  clip-path: inset(50%);
                  white-space: nowrap;
                `, children: "Search" }), _jsx("input", { className: "openk9--input-search", autoComplete: "off", ref: inputRef, enterKeyHint: "search", onKeyUp: (event) => {
                                            if (setIsVisible && event.key === "Enter")
                                                setIsVisible(false);
                                        }, id: "search-openk9-modal", "aria-label": t("insert-text-to-set-the-value-or-use-up-and-down-arrow-keys-to-navigate-the-suggestion-box") ||
                                            "insert text to set the value or use up and down arrow keys to navigate the suggestion box", type: "text", placeholder: t("search") || "search...", value: selectionsState.text, onChange: (event) => {
                                            setText(event.currentTarget.value);
                                        }, css: css `
                  position: relative;
                  flex-grow: 1;
                  border: none;
                  outline: none;
                  padding: var(--openk9-embeddable-search--input-padding);
                  caret-color: black;
                  font-size: inherit;
                  font-family: inherit;
                  background-color: inherit;
                  width: 100%;
                  color: ${autoSelect ? "black" : "black"};
                `, spellCheck: "false", onSelect: (event) => {
                                            if ((event.currentTarget.selectionDirection === "forward" ||
                                                event.currentTarget.selectionDirection === "none") &&
                                                event.currentTarget.selectionStart ===
                                                    event.currentTarget.selectionEnd) {
                                                setOpenedDropdown({
                                                    textPosition: event.currentTarget
                                                        .selectionStart,
                                                    optionPosition: openedDropdown?.optionPosition ?? 0,
                                                });
                                            }
                                        }, onKeyDown: (event) => {
                                            const span = openedDropdown &&
                                                spans.find((span) => openedDropdown.textPosition > span.start &&
                                                    openedDropdown.textPosition <= span.end);
                                            const option = openedDropdown &&
                                                span?.tokens[openedDropdown.optionPosition - 1];
                                            if (event.key === "ArrowDown") {
                                                event.preventDefault();
                                                if (openedDropdown && span) {
                                                    setOpenedDropdown({
                                                        textPosition: openedDropdown.textPosition,
                                                        optionPosition: openedDropdown.optionPosition < span.tokens.length
                                                            ? openedDropdown.optionPosition + 1
                                                            : 0,
                                                    });
                                                }
                                            }
                                            else if (event.key === "ArrowUp") {
                                                event.preventDefault();
                                                if (openedDropdown && openedDropdown.optionPosition > 0) {
                                                    setOpenedDropdown({
                                                        textPosition: openedDropdown.textPosition,
                                                        optionPosition: openedDropdown.optionPosition - 1,
                                                    });
                                                }
                                            }
                                            else if (event.key === "Enter") {
                                                event.preventDefault();
                                                if (span) {
                                                    selectionsDispatch({
                                                        type: "set-selection",
                                                        replaceText,
                                                        selection: {
                                                            text: span.text,
                                                            textOnChange: span.text,
                                                            start: span.start,
                                                            end: span.end,
                                                            token: option ?? null,
                                                            isAuto: false,
                                                        },
                                                    });
                                                    if (replaceText) {
                                                        const text = option &&
                                                            (option.tokenType === "ENTITY"
                                                                ? option.entityName
                                                                : option.value);
                                                        const cursorPosition = span.start + (text?.length ?? 0);
                                                        setAdjustedSelection({
                                                            selectionStart: cursorPosition,
                                                            selectionEnd: cursorPosition,
                                                        });
                                                    }
                                                    else if (event.currentTarget.selectionStart &&
                                                        event.currentTarget.selectionEnd) {
                                                        setAdjustedSelection({
                                                            selectionStart: event.currentTarget.selectionStart,
                                                            selectionEnd: event.currentTarget.selectionEnd,
                                                        });
                                                    }
                                                    setOpenedDropdown(null);
                                                }
                                            }
                                            else if (event.key === "Escape") {
                                                setOpenedDropdown(null);
                                            }
                                        } })] }), _jsxs("div", { css: css `
                display: flex;
              `, children: [_jsx("button", { className: "openk9--search-delete-container-icon", title: "remove text", "aria-label": "remove-text", css: css `
                  align-items: center;
                  background: inherit;
                  border: none;
                `, onClick: () => {
                                            clearSearch();
                                        }, children: _jsx("div", { children: _jsx("span", { className: "openk9--search-delete-span-icon", css: css `
                      cursor: pointer;
                      @media (max-width: 480px) {
                        margin-top: 7px;
                      }
                    `, children: _jsx(DeleteLogo, {}) }) }) }), _jsx("button", { className: "openk9--search-delete-container-icon", title: "search", "aria-label": "search", css: css `
                  padding-right: 16px;
                  display: flex;
                  flex-direction: row;
                  padding: 4px 8px;
                  gap: 4px;
                  align-items: center;
                  margin-right: 8px;
                  background: inherit;
                  border: none;
                `, children: _jsx("div", { children: _jsx("span", { className: "openk9--search-delete-span-icon", css: css `
                      cursor: pointer;
                      @media (max-width: 480px) {
                        margin-top: 7px;
                      }
                    `, children: _jsx(SearchSvg, {}) }) }) })] })] }) }), _jsx("div", { children: spans.map((span, index) => {
                        const isOpen = openedDropdown !== null &&
                            openedDropdown.textPosition > span.start &&
                            openedDropdown.textPosition <= span.end;
                        const optionIndex = openedDropdown?.optionPosition ?? null;
                        const selection = selectionsState.selection.find((selection) => selection.start === span.start && selection.end === span.end);
                        const selected = selection?.token ?? null;
                        const onSelect = (token) => {
                            selectionsDispatch({
                                type: "set-selection",
                                replaceText,
                                selection: {
                                    text: span.text,
                                    textOnChange: span.text,
                                    start: span.start,
                                    end: span.end,
                                    token,
                                    isAuto: false,
                                },
                            });
                            if (inputRef.current?.selectionStart &&
                                inputRef.current?.selectionEnd) {
                                setAdjustedSelection({
                                    selectionStart: inputRef.current.selectionStart,
                                    selectionEnd: inputRef.current.selectionEnd,
                                });
                            }
                            setOpenedDropdown(null);
                        };
                        const onSelectText = (token) => {
                            if (token)
                                if (inputRef.current?.selectionStart &&
                                    inputRef.current?.selectionEnd) {
                                    setAdjustedSelection({
                                        selectionStart: inputRef.current.selectionStart,
                                        selectionEnd: inputRef.current.selectionEnd,
                                    });
                                }
                            setOpenedDropdown(null);
                        };
                        const isAutoSelected = selection?.isAuto ?? false;
                        const onOptionIndexChange = (optionIndex) => {
                            setOpenedDropdown((openedDropdown) => openedDropdown
                                ? { ...openedDropdown, optionPosition: optionIndex }
                                : openedDropdown);
                        };
                        return (_jsx(TokenSelectMobile, { span: span, isOpen: isOpen, onOptionIndexChange: onOptionIndexChange, optionIndex: optionIndex, selected: selected, onSelect: onSelect, onSelectText: onSelectText, isAutoSlected: isAutoSelected, setOpenedDropdown: setOpenedDropdown, selectionsDispatch: selectionsDispatch, setIsVisible: setIsVisible }, index));
                    }) })] }) }));
    if (!isVisible)
        return null;
    document.body.style.overflow = "hidden";
    return _jsx(ModalDetail, { padding: "0px", background: "white", content: componet });
}
export const SearchMobileMemo = React.memo(SearchMobile);
export function TokenSelectMobile({ span, onSelect, selected, isOpen, optionIndex, onOptionIndexChange, isAutoSlected, setOpenedDropdown, onSelectText, selectionsDispatch, setIsVisible, }) {
    const isInteractive = span.tokens.length > 0;
    const [subtitle, setSubtitle] = React.useState(false);
    const { t } = useTranslation();
    const entryStyle = (isSelected, isHighlighted) => css `
    padding: 8px 16px;
    border-bottom: 1px solid #b09c9c12;
    :hover {
    }
    cursor: pointer;
    border-left: ${isSelected
        ? `8px solid var(--openk9-embeddable-search--active-color)`
        : "none"};
    padding-left: ${isSelected ? "8px" : "16px"};
  `;
    const deseleziona = (isSelected) => css `
    padding: 8px 16px;
    :hover {
    }
    background-color: ${"var(--openk9-embeddable-search--secondary-background-color)"};
    cursor: ${!isSelected ? "" : "not-allowed"};
  `;
    return (_jsx("div", { className: "openk9-token-select-container", css: css ``, children: isOpen && isInteractive && (_jsxs("div", { className: "openk9-token-select-is-open", css: css `
            left: 0px;
            background-color: var(
              --openk9-embeddable-search--primary-background-color
            );
            border: 1px solid var(--openk9-embeddable-search--border-color);
            border-radius: 4px;
            z-index: 2;
          `, children: [_jsx("div", { className: "openk9-enter-token", onMouseEnter: () => {
                        onOptionIndexChange(0);
                    }, css: css `
              ${deseleziona(selected === null)};
              padding: 0;
            `, children: selected && (_jsx("button", { className: "openk9-token-select-uncheck", css: css `
                  display: flex;
                  justify-content: space-between;
                  align-items: baseline;
                  color: var(--openk9-embeddable-search--secondary-text-color);
                  text-decoration: underline;
                  cursor: ${selected && subtitle ? "pointer" : "auto"};
                  width: 100%;
                  height: 100%;
                  border: none;
                  padding: 8px 16px;
                `, children: _jsx("div", { onClick: () => {
                                if (selected)
                                    onSelect(null);
                            }, children: t("uncheck") }) })) }), span.tokens.map((option, index) => {
                    const isSelected = option.tokenType === selected?.tokenType &&
                        option.value === selected.value;
                    const isHighlighted = optionIndex === index + 1;
                    return (_jsxs("div", { onClick: () => {
                            if (option.tokenType === "AUTOCOMPLETE") {
                                if (setIsVisible)
                                    setIsVisible(false);
                                onSelectText(option);
                            }
                            else {
                                if (setIsVisible)
                                    setIsVisible(false);
                                onSelect(option);
                            }
                        }, className: "openk9-token-select-container-highlighted", css: css `
                  ${entryStyle(isSelected, isHighlighted)};
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                  border-top: ${index !== 0 ? "0.5px solid #E4E4E7;" : "none"};
                `, children: ["keywordName" in option && (_jsxs(React.Fragment, { children: [_jsx("div", { css: css `
                        padding-inline: 5px;
                        border: ${index !== 0
                                            ? "0.5px solid #E4E4E7;"
                                            : "none"};
                      ` }), _jsxs("strong", { className: "openk9-token-select-highlighted", css: css `
                        margin-right: 8px;
                      `, children: [option.keywordName, ":"] })] })), _jsx(FactoryTokenType, { option: option })] }, index));
                })] })) }));
}
const statusStyles = {
    "can-select": css `
    color: var(--openk9-embeddable-search--primary-color);
  `,
    "auto-selected": css `
    color: lightseagreen;
  `,
    "has-selected": css `
    color: dodgerblue;
  `,
    "not-interactive": css `
    color: black;
  `,
};
function getTokenLabel(token) {
    switch (token.tokenType) {
        case "DATASOURCE":
            return token.value;
        case "DOCTYPE":
            return token.value;
        case "ENTITY":
            return token.entityName;
        case "TEXT":
            return token.value;
        case "FILTER":
            return token.value;
    }
}
function FactoryTokenType({ option, }) {
    switch (option.tokenType) {
        case "AUTOCOMPLETE":
            return (_jsx(React.Fragment, { children: _jsx("div", { className: "openk9-token-select-factory-autocomplete", css: css `
              display: flex;
              font-family: "Helvetica";
              font-style: normal;
              font-weight: 400;
              font-size: 15px;
              line-height: 17px;
            `, children: option.value }) }));
            break;
        case "AUTOCORRECT":
            return (_jsxs("span", { className: "openk9-token-select-factory-autocorrect", children: ["Did you mean? ", _jsx("strong", { children: option.value })] }));
        default:
            return (_jsxs(React.Fragment, { children: [_jsx("div", { className: "openk9-token-select-factory-create", css: css `
              display: flex;
              font-family: "Helvetica";
              font-style: normal;
              font-weight: 400;
              font-size: 15px;
              line-height: 17px;
              max-width: 60%;
            `, children: getTokenLabel(option) }), _jsx("div", { className: "openk9-token-select-factory-container-option-label", css: css `
              display: flex;
              justify-content: center;
              align-items: center;
              padding: 4px 8px;
              gap: 4px;
              height: 15px;
              background: #ffffff;
              border: 1px solid
                var(--openk9-embeddable-search--secondary-active-color);
              border-radius: 20px;
              margin-left: 10px;
            `, children: _jsx("div", { className: "openk9-token-select-factory-option-label", css: css `
                color: var(--openk9-embeddable-search--secondary-active-color);
                margin-bottom: 13px;
                font-size: 12px;
                display: block;
                margin-block-start: 1em;
                margin-block-end: 1em;
                margin-inline-start: 0px;
                margin-inline-end: 0px;
              `, children: option.label }) })] }));
            break;
    }
}
function setValueSearch({ isBtn, selectionsDispatch, }) {
    const setText = (text) => !isBtn
        ? selectionsDispatch({
            type: "set-text",
            text: text,
            textOnchange: text,
        })
        : selectionsDispatch({
            type: "set-text-btn",
            textOnchange: text,
        });
    const search = (text) => selectionsDispatch({
        type: "set-text",
        text: text,
        textOnchange: text,
    });
    const clearSearch = () => selectionsDispatch({
        type: "reset-search",
    });
    return { setText, search, clearSearch };
}
