/**
 * Search history component matching the Angular `search-history` component.
 *
 * Displays recent searches in a collapsible accordion section.
 * Uses useSearchHistory hook for localStorage-backed history.
 *
 * @module
 */

import { type FC, useState, useCallback } from "react";
import { useNavigate, useParams } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { useSearchHistory, type SearchHistoryItem } from "@/shared/hooks/useSearchHistory.js";
import "./SearchHistory.scss";

export const SearchHistory: FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const routeParams = useParams<{ lang: string }>();
  const lang = routeParams.lang ?? "ru";

  const { items } = useSearchHistory(lang);
  const [expanded, setExpanded] = useState(false);

  const handleItemClick = useCallback(
    (item: SearchHistoryItem) => {
      void navigate(item.url);
    },
    [navigate],
  );

  if (items.length === 0) return null;

  return (
    <section className="frame search-history" data-testid="search-history">
      <div className="p-accordion">
        <div className={`p-accordion-tab${expanded ? " p-accordion-tab--active" : ""}`}>
          <div className={`p-accordion-header${expanded ? " p-highlight" : ""}`}>
            <a
              role="button"
              tabIndex={0}
              onClick={() => setExpanded((prev) => !prev)}
              onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") setExpanded((prev) => !prev); }}
            >
              <span className="p-header">
                <span>{t("BOARD.YOU_SEARCH")}</span>
                <span className={`arrow-icon${expanded ? " arrow-icon--rotated" : ""}`}>
                  <svg viewBox="0 0 12 8" width="12" height="8">
                    <path d="M1 1L6 6L11 1" stroke="currentColor" strokeWidth="1.5" fill="none" />
                  </svg>
                </span>
              </span>
            </a>
          </div>
          {expanded && (
            <div className="p-accordion-content">
              <div className="search-history__content">
                {items.map((item) => (
                  <div
                    key={item.url}
                    className="search-history__item"
                    role="button"
                    tabIndex={0}
                    onClick={() => handleItemClick(item)}
                    onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") handleItemClick(item); }}
                    data-testid="search-history-item"
                  >
                    <span className="search-history__label">{item.label}</span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
};
