"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useRef, useEffect, useCallback } from "react";
import Link from "next/link";
import { Input } from "../../ui/input";
import { Button } from "../../ui/button";
import { Badge } from "../../ui/badge";
import { ScrollArea } from "../../ui/scroll-area";
import {
  Search,
  X,
  Settings,
  FileText,
  Loader2,
  AlertCircle,
  ArrowRight
} from "lucide-react";
import { useEntitySearch } from "../../../hooks/useEntitySearch";
import { formatSearchResult } from "../../../lib/search-highlighting";
import { cn } from "../../../lib/utils";
import { createTestId, createCyId, createAriaLabel } from "../../../lib/test";
import { useTranslations } from "next-intl";
const getTypeIcon = (result) => {
  if (result.type === "entity") {
    return /* @__PURE__ */ jsx(FileText, { className: "h-4 w-4" });
  }
  switch (result.category) {
    case "Settings":
      return /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" });
    case "Navigation":
      return /* @__PURE__ */ jsx(ArrowRight, { className: "h-4 w-4" });
    default:
      return /* @__PURE__ */ jsx(Search, { className: "h-4 w-4" });
  }
};
const getTypeLabel = (result, locale = "es") => {
  if (result.type === "entity") {
    return locale === "en" ? "Entity" : "Entidad";
  }
  switch (result.category) {
    case "Settings":
      return locale === "en" ? "Setting" : "Configuraci\xF3n";
    case "Navigation":
      return locale === "en" ? "Page" : "P\xE1gina";
    case "Entities":
      return locale === "en" ? "Entity" : "Entidad";
    default:
      return locale === "en" ? "Result" : "Resultado";
  }
};
const getPriorityColor = (priority) => {
  switch (priority) {
    case "high":
      return "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";
    case "medium":
      return "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400";
    case "low":
      return "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400";
    default:
      return "bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-400";
  }
};
function SearchResultItem({ result, onSelect, searchQuery }) {
  const handleSelect = useCallback(() => {
    onSelect();
  }, [onSelect]);
  const { highlightedTitle, highlightedDescription } = formatSearchResult(
    result.title,
    result.description,
    searchQuery
  );
  return /* @__PURE__ */ jsx(
    Link,
    {
      href: result.url,
      className: "block p-3 hover:bg-muted/50 transition-colors group focus:outline-none focus:ring-2 focus:ring-accent",
      onClick: handleSelect,
      role: "option",
      "aria-label": createAriaLabel(
        "{type}: {title}{description}{limits}",
        {
          type: getTypeLabel(result, "es"),
          title: result.title,
          description: result.description ? ` - ${result.description}` : "",
          limits: result.limitInfo ? ` (${result.limitInfo.current}/${result.limitInfo.max})` : ""
        }
      ),
      ...createTestId("search", "result", "item") && { "data-testid": createTestId("search", "result", "item") },
      ...createCyId("search", "result") && { "data-cy": createCyId("search", "result") },
      "data-result-id": result.id,
      "data-result-type": result.type,
      "data-entity-type": result.entityType,
      children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2 mt-0.5", children: /* @__PURE__ */ jsx("div", { className: cn(
          "p-1 rounded flex items-center justify-center",
          result.type === "entity" ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"
        ), children: getTypeIcon(result) }) }),
        /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 space-y-1", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              "h4",
              {
                className: "text-sm font-medium truncate group-hover:text-foreground",
                dangerouslySetInnerHTML: { __html: highlightedTitle }
              }
            ),
            result.limitInfo && /* @__PURE__ */ jsxs(
              Badge,
              {
                variant: result.limitInfo.canCreate ? "secondary" : "destructive",
                className: "text-xs",
                children: [
                  result.limitInfo.current,
                  "/",
                  result.limitInfo.max === "unlimited" ? "\u221E" : result.limitInfo.max
                ]
              }
            ),
            result.priority && result.priority !== "low" && /* @__PURE__ */ jsx(
              Badge,
              {
                variant: "secondary",
                className: cn("text-xs", getPriorityColor(result.priority)),
                children: result.priority
              }
            )
          ] }),
          result.description && /* @__PURE__ */ jsx(
            "p",
            {
              className: "text-xs text-muted-foreground line-clamp-2",
              dangerouslySetInnerHTML: { __html: highlightedDescription || result.description }
            }
          ),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: getTypeLabel(result) }),
            result.category && /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs", children: result.category }),
            result.type === "entity" && /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "text-xs text-primary", children: result.entityType })
          ] })
        ] }),
        /* @__PURE__ */ jsx(ArrowRight, { className: "h-4 w-4 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity" })
      ] })
    }
  );
}
function SearchDropdown() {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  const [statusMessage, setStatusMessage] = useState("");
  const inputRef = useRef(null);
  const t = useTranslations("common");
  const dropdownRef = useRef(null);
  const {
    query,
    setQuery,
    results,
    isSearching,
    clearSearch,
    hasResults,
    isEmpty
  } = useEntitySearch();
  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setIsOpen(false);
        setSelectedIndex(-1);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);
  const handleClose = useCallback(() => {
    setIsOpen(false);
    setSelectedIndex(-1);
    clearSearch();
    setStatusMessage("B\xFAsqueda cerrada");
  }, [clearSearch]);
  useEffect(() => {
    const handleKeyDown = (event) => {
      if (!isOpen) return;
      switch (event.key) {
        case "ArrowDown":
          event.preventDefault();
          setSelectedIndex(
            (prev) => prev < results.length - 1 ? prev + 1 : 0
          );
          break;
        case "ArrowUp":
          event.preventDefault();
          setSelectedIndex(
            (prev) => prev > 0 ? prev - 1 : results.length - 1
          );
          break;
        case "Enter":
          if (selectedIndex >= 0 && results[selectedIndex]) {
            window.location.href = results[selectedIndex].url;
            handleClose();
          }
          break;
        case "Escape":
          handleClose();
          break;
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, selectedIndex, results, handleClose]);
  const handleInputChange = useCallback((value) => {
    setQuery(value);
    setSelectedIndex(-1);
    if (value.trim().length > 0) {
      setIsOpen(true);
      setStatusMessage(`Buscando: ${value}`);
    } else {
      setIsOpen(false);
      setStatusMessage("");
    }
  }, [setQuery]);
  const showDropdown = isOpen && (hasResults || isSearching || !isEmpty && !hasResults);
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx(
      "div",
      {
        "aria-live": "polite",
        "aria-atomic": "true",
        className: "sr-only",
        ...createTestId("search", "status", "message") && { "data-testid": createTestId("search", "status", "message") },
        children: statusMessage
      }
    ),
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: "relative w-full",
        ref: dropdownRef,
        ...createTestId("search", "container") && { "data-testid": createTestId("search", "container") },
        ...createCyId("search", "dropdown") && { "data-cy": createCyId("search", "dropdown") },
        children: [
          /* @__PURE__ */ jsxs("div", { className: "relative", children: [
            /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground", "aria-hidden": "true" }),
            /* @__PURE__ */ jsx(
              Input,
              {
                ref: inputRef,
                placeholder: t("search.placeholder"),
                value: query,
                onChange: (e) => handleInputChange(e.target.value),
                onFocus: () => query.trim().length > 0 && setIsOpen(true),
                className: "pl-10 pr-10 bg-muted/50 border-0 focus-visible:ring-1",
                role: "combobox",
                "aria-expanded": isOpen,
                "aria-haspopup": "listbox",
                "aria-owns": isOpen ? "search-results" : void 0,
                "aria-autocomplete": "list",
                "aria-label": t("search.label"),
                ...createTestId("search", "input") && { "data-testid": createTestId("search", "input") },
                ...createCyId("search", "input") && { "data-cy": createCyId("search", "input") }
              }
            ),
            !isEmpty && /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "sm",
                className: "absolute right-1 top-1/2 transform -translate-y-1/2 h-7 w-7 p-0",
                onClick: handleClose,
                "aria-label": t("search.clear"),
                ...createTestId("search", "clear", "button") && { "data-testid": createTestId("search", "clear", "button") },
                ...createCyId("search", "clear") && { "data-cy": createCyId("search", "clear") },
                children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3", "aria-hidden": "true" })
              }
            ),
            isSearching && /* @__PURE__ */ jsx("div", { className: "absolute right-3 top-1/2 transform -translate-y-1/2", children: /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin text-muted-foreground" }) })
          ] }),
          showDropdown && /* @__PURE__ */ jsxs(
            "div",
            {
              className: "absolute top-full left-0 right-0 mt-1 bg-popover border border-border rounded-md shadow-lg z-50",
              id: "search-results",
              role: "listbox",
              "aria-label": t("search.results"),
              ...createTestId("search", "dropdown", "content") && { "data-testid": createTestId("search", "dropdown", "content") },
              ...createCyId("search", "results") && { "data-cy": createCyId("search", "results") },
              children: [
                /* @__PURE__ */ jsx(ScrollArea, { className: "max-h-96", children: isSearching ? /* @__PURE__ */ jsxs("div", { className: "p-4 text-center", children: [
                  /* @__PURE__ */ jsx(Loader2, { className: "h-6 w-6 animate-spin mx-auto mb-2 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("search.searching") })
                ] }) : hasResults ? /* @__PURE__ */ jsx("div", { className: "py-2", children: results.map((result, index) => /* @__PURE__ */ jsx(
                  "div",
                  {
                    className: cn(
                      selectedIndex === index && "bg-muted/50"
                    ),
                    children: /* @__PURE__ */ jsx(
                      SearchResultItem,
                      {
                        result,
                        onSelect: handleClose,
                        searchQuery: query
                      }
                    )
                  },
                  result.id
                )) }) : /* @__PURE__ */ jsxs("div", { className: "p-4 text-center", children: [
                  /* @__PURE__ */ jsx(AlertCircle, { className: "h-6 w-6 mx-auto mb-2 text-muted-foreground" }),
                  /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("search.noResults", { query }) }),
                  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground mt-1", children: t("search.tryDifferent") })
                ] }) }),
                hasResults && /* @__PURE__ */ jsx("div", { className: "border-t border-border p-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between text-xs text-muted-foreground", children: [
                  /* @__PURE__ */ jsxs("span", { children: [
                    results.length,
                    " resultado",
                    results.length !== 1 ? "s" : ""
                  ] }),
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                    /* @__PURE__ */ jsx("span", { children: "\u2191\u2193 navegar" }),
                    /* @__PURE__ */ jsx("span", { children: "\u21B5 seleccionar" }),
                    /* @__PURE__ */ jsx("span", { children: "esc cerrar" })
                  ] })
                ] }) })
              ]
            }
          )
        ]
      }
    )
  ] });
}
export {
  SearchDropdown
};
