import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {useState,useRef,useEffect}from'react';import {createPortal}from'react-dom';import {useNavigate}from'@remix-run/react';import {getCategoryByIdSync,searchArticles}from'../utils/markdownLoader.js';const MAX_RESULTS = 5;
const POPULAR_TERMS = ['Getting started', 'Account setup', 'API documentation', 'Troubleshooting'];
const HelpCenterSearch = ({
  onSearch,
  initialSearchQuery = '',
  showPopularSearches = true,
  className = ''
}) => {
  const navigate = useNavigate();
  const [searchQuery, setSearchQuery] = useState(initialSearchQuery);
  const [searchResults, setSearchResults] = useState([]);
  const [showDropdown, setShowDropdown] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const [dropdownPosition, setDropdownPosition] = useState({
    top: 0,
    left: 0,
    width: 0
  });
  const [searching, setSearching] = useState(false);
  const [searchError, setSearchError] = useState(null);
  const searchContainerRef = useRef(null);
  const inputRef = useRef(null);
  const searchAbortRef = useRef(false);
  useEffect(() => {
    setSearchQuery(initialSearchQuery);
  }, [initialSearchQuery]);
  const updateDropdownPosition = useRef(() => {
    if (searchContainerRef.current) {
      const rect = searchContainerRef.current.getBoundingClientRect();
      setDropdownPosition({
        top: rect.bottom + window.scrollY + 4,
        left: rect.left + window.scrollX,
        width: rect.width
      });
    }
  });
  useEffect(() => {
    const query = searchQuery.trim();
    if (query.length === 0) {
      setSearchResults([]);
      setShowDropdown(false);
      setSearching(false);
      setSearchError(null);
      return;
    }
    searchAbortRef.current = false;
    setSearching(true);
    setSearchError(null);
    const performSearch = async () => {
      try {
        const results = await searchArticles(query);
        if (searchAbortRef.current) return;
        setSearchResults(results.slice(0, MAX_RESULTS));
        setShowDropdown(true);
        setSelectedIndex(-1);
      } catch (err) {
        if (searchAbortRef.current) return;
        console.error('Help center search failed:', err);
        setSearchResults([]);
        setSearchError('Search is temporarily unavailable. Please try again.');
        setShowDropdown(true);
      } finally {
        if (!searchAbortRef.current) setSearching(false);
      }
    };
    performSearch();
    return () => {
      searchAbortRef.current = true;
    };
  }, [searchQuery]);
  useEffect(() => {
    if (showDropdown) {
      updateDropdownPosition.current();
      const handleScroll = () => updateDropdownPosition.current();
      const handleResize = () => updateDropdownPosition.current();
      window.addEventListener('scroll', handleScroll, true);
      window.addEventListener('resize', handleResize);
      return () => {
        window.removeEventListener('scroll', handleScroll, true);
        window.removeEventListener('resize', handleResize);
      };
    }
  }, [showDropdown]);
  useEffect(() => {
    const handleClickOutside = event => {
      const target = event.target;
      if (searchContainerRef.current && !searchContainerRef.current.contains(target)) {
        const dropdown = document.querySelector('[data-search-dropdown]');
        if (!dropdown || !dropdown.contains(target)) {
          setShowDropdown(false);
        }
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);
  const handleSearch = e => {
    e.preventDefault();
    if (onSearch && searchQuery.trim()) {
      onSearch(searchQuery);
    }
    if (searchResults.length > 0) {
      const firstResult = searchResults[0];
      navigate(`/help/${firstResult.categoryId}/${firstResult.slug}`);
      setShowDropdown(false);
    }
  };
  const handleInputChange = e => {
    setSearchQuery(e.target.value);
  };
  const handleInputFocus = () => {
    if (searchResults.length > 0) {
      setShowDropdown(true);
    }
  };
  const handleResultClick = (article, e) => {
    if (e) {
      e.preventDefault();
      e.stopPropagation();
    }
    if (!article?.categoryId || !article?.slug) {
      console.error('Article missing required fields:', article);
      return;
    }
    setShowDropdown(false);
    setSearchQuery('');
    navigate(`/help/${article.categoryId}/${article.slug}`);
  };
  const handleKeyDown = e => {
    if (!showDropdown || searchResults.length === 0) return;
    switch (e.key) {
      case 'ArrowDown':
        e.preventDefault();
        setSelectedIndex(i => i < searchResults.length - 1 ? i + 1 : i);
        break;
      case 'ArrowUp':
        e.preventDefault();
        setSelectedIndex(i => i > 0 ? i - 1 : -1);
        break;
      case 'Enter':
        if (selectedIndex >= 0 && searchResults[selectedIndex]) {
          e.preventDefault();
          handleResultClick(searchResults[selectedIndex]);
        }
        break;
      case 'Escape':
        setShowDropdown(false);
        setSelectedIndex(-1);
        break;
    }
  };
  return jsxs("div", {
    className: className,
    children: [jsx("form", {
      onSubmit: handleSearch,
      className: "relative w-full max-w-2xl mx-auto",
      style: {
        zIndex: 50
      },
      children: jsx("div", {
        ref: searchContainerRef,
        className: "relative w-full",
        children: jsxs("div", {
          className: "flex w-full rounded-2xl bg-white shadow-2xl",
          children: [jsxs("div", {
            className: "relative flex-1",
            children: [jsx("div", {
              className: "pointer-events-none absolute inset-y-0 left-0 flex items-center pl-6 z-10",
              children: jsx("svg", {
                className: "h-6 w-6 text-gray-400",
                fill: "none",
                viewBox: "0 0 24 24",
                stroke: "currentColor",
                children: jsx("path", {
                  strokeLinecap: "round",
                  strokeLinejoin: "round",
                  strokeWidth: 2,
                  d: "M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"
                })
              })
            }), jsx("input", {
              ref: inputRef,
              type: "text",
              className: "h-16 w-full bg-transparent py-6 pl-16 pr-6 text-lg text-gray-900 placeholder-gray-500 outline-none relative z-10",
              placeholder: "Search help center...",
              value: searchQuery,
              onChange: handleInputChange,
              onFocus: handleInputFocus,
              onKeyDown: handleKeyDown
            })]
          }), jsx("button", {
            type: "submit",
            className: "flex items-center justify-center rounded-r-2xl bg-gray-900 px-8 text-lg font-medium text-white transition-colors hover:bg-gray-800 relative z-10",
            children: "Search"
          })]
        })
      })
    }), showPopularSearches && jsxs("div", {
      className: "mt-8 flex flex-wrap justify-center gap-3",
      children: [jsx("span", {
        className: "text-sm text-white/60",
        children: "Popular:"
      }), POPULAR_TERMS.map(term => jsx("button", {
        type: "button",
        onClick: () => {
          setSearchQuery(term);
          setShowDropdown(true);
        },
        className: "rounded-full bg-white/10 px-4 py-2 text-sm text-white/80 transition-colors hover:bg-white/20 hover:text-white",
        children: term
      }, term))]
    }), showDropdown && typeof document !== 'undefined' && createPortal(jsx(Fragment, {
      children: searchError ? jsx("div", {
        "data-search-dropdown": true,
        className: "fixed bg-white rounded-lg shadow-2xl border border-gray-200 z-[9999]",
        style: {
          top: `${dropdownPosition.top}px`,
          left: `${dropdownPosition.left}px`,
          width: `${dropdownPosition.width}px`
        },
        onClick: e => e.stopPropagation(),
        children: jsx("div", {
          className: "px-4 py-6 text-center text-amber-700 text-sm",
          children: searchError
        })
      }) : searchResults.length > 0 ? jsx("div", {
        "data-search-dropdown": true,
        className: "fixed bg-white rounded-lg shadow-2xl border border-gray-200 max-h-96 overflow-y-auto z-[9999]",
        style: {
          top: `${dropdownPosition.top}px`,
          left: `${dropdownPosition.left}px`,
          width: `${dropdownPosition.width}px`
        },
        onClick: e => e.stopPropagation(),
        children: jsx("div", {
          className: "py-1",
          children: searchResults.map((article, index) => {
            const category = getCategoryByIdSync(article.categoryId);
            return jsx("div", {
              onClick: e => {
                e.preventDefault();
                e.stopPropagation();
                handleResultClick(article, e);
              },
              className: `block px-4 py-3 hover:bg-blue-50 transition-colors cursor-pointer border-b border-gray-100 last:border-b-0 ${selectedIndex === index ? 'bg-blue-50' : ''}`,
              role: "button",
              tabIndex: 0,
              onKeyDown: e => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  handleResultClick(article);
                }
              },
              children: jsxs("div", {
                className: "flex flex-col",
                children: [jsx("div", {
                  className: "text-base font-semibold text-gray-900",
                  children: article.title
                }), article.description && jsx("div", {
                  className: "text-sm text-gray-600 mt-0.5",
                  children: article.description
                }), category && jsx("div", {
                  className: "text-xs text-blue-600 mt-1 font-medium",
                  children: category.title
                })]
              })
            }, article.id);
          })
        })
      }) : searchQuery.trim().length > 0 ? jsx("div", {
        "data-search-dropdown": true,
        className: "fixed bg-white rounded-lg shadow-2xl border border-gray-200 z-[9999]",
        style: {
          top: `${dropdownPosition.top}px`,
          left: `${dropdownPosition.left}px`,
          width: `${dropdownPosition.width}px`
        },
        onClick: e => e.stopPropagation(),
        children: jsx("div", {
          className: "px-4 py-6 text-center text-gray-500",
          children: searching ? jsx("p", {
            children: "Searching..."
          }) : jsxs("p", {
            children: ["No results found for \"", searchQuery, "\""]
          })
        })
      }) : null
    }), document.body)]
  });
};export{HelpCenterSearch};//# sourceMappingURL=HelpCenterSearch.js.map
