"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo } from "react";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
import { Badge } from "../ui/badge";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Copy, Check, Search, Tag, ExternalLink, ChevronDown, ChevronRight, FileCode2 } from "lucide-react";
import { useTranslations } from "next-intl";
import { TAGS_REGISTRY, COVERAGE_SUMMARY } from "@nextsparkjs/registries/testing-registry";
import { sel } from "../../lib/test";
import { cn } from "../../lib/utils";
const CATEGORY_DISPLAY_ORDER = [
  "layers",
  "priorities",
  "features",
  "flows",
  "blocks",
  "roles",
  "operations",
  "other"
];
const CATEGORY_COLORS = {
  layers: "bg-blue-100 text-blue-800 hover:bg-blue-200 dark:bg-blue-900 dark:text-blue-300",
  priorities: "bg-amber-100 text-amber-800 hover:bg-amber-200 dark:bg-amber-900 dark:text-amber-300",
  features: "bg-violet-100 text-violet-800 hover:bg-violet-200 dark:bg-violet-900 dark:text-violet-300",
  flows: "bg-emerald-100 text-emerald-800 hover:bg-emerald-200 dark:bg-emerald-900 dark:text-emerald-300",
  blocks: "bg-pink-100 text-pink-800 hover:bg-pink-200 dark:bg-pink-900 dark:text-pink-300",
  roles: "bg-cyan-100 text-cyan-800 hover:bg-cyan-200 dark:bg-cyan-900 dark:text-cyan-300",
  operations: "bg-orange-100 text-orange-800 hover:bg-orange-200 dark:bg-orange-900 dark:text-orange-300",
  other: "bg-gray-100 text-gray-800 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-300"
};
function TagsOverview() {
  const t = useTranslations("devtools.tags");
  const [searchQuery, setSearchQuery] = useState("");
  const [copiedTag, setCopiedTag] = useState(null);
  const [expandedCategories, setExpandedCategories] = useState(
    new Set(CATEGORY_DISPLAY_ORDER)
  );
  const [expandedTag, setExpandedTag] = useState(null);
  const totalTags = useMemo(() => {
    let count = 0;
    for (const category of CATEGORY_DISPLAY_ORDER) {
      const categoryData = TAGS_REGISTRY[category];
      if (categoryData) {
        count += Object.keys(categoryData).length;
      }
    }
    return count;
  }, []);
  const filteredTagsByCategory = useMemo(() => {
    const result = {};
    for (const category of CATEGORY_DISPLAY_ORDER) {
      const categoryData = TAGS_REGISTRY[category];
      if (!categoryData) continue;
      const filteredTags = {};
      for (const [key, data] of Object.entries(categoryData)) {
        if (searchQuery) {
          const query = searchQuery.toLowerCase();
          const matchesTag = key.toLowerCase().includes(query) || data.tag.toLowerCase().includes(query);
          const matchesFile = data.files.some(
            (file) => file.toLowerCase().includes(query)
          );
          if (!matchesTag && !matchesFile) {
            continue;
          }
        }
        filteredTags[key] = data;
      }
      if (Object.keys(filteredTags).length > 0) {
        result[category] = filteredTags;
      }
    }
    return result;
  }, [searchQuery]);
  const filteredTagCount = useMemo(() => {
    let count = 0;
    for (const category of Object.keys(filteredTagsByCategory)) {
      count += Object.keys(filteredTagsByCategory[category]).length;
    }
    return count;
  }, [filteredTagsByCategory]);
  const copyGrepCommand = (tag) => {
    const command = `npx cypress run --env grepTags="${tag}"`;
    navigator.clipboard.writeText(command);
    setCopiedTag(tag);
    setTimeout(() => setCopiedTag(null), 2e3);
  };
  const toggleCategory = (category) => {
    setExpandedCategories((prev) => {
      const next = new Set(prev);
      if (next.has(category)) {
        next.delete(category);
      } else {
        next.add(category);
      }
      return next;
    });
  };
  const getLinkForTag = (category, key) => {
    if (category === "features") {
      return `/devtools/features`;
    }
    if (category === "blocks") {
      return `/devtools/blocks/${key}`;
    }
    return null;
  };
  const toggleTagExpand = (tagKey) => {
    setExpandedTag((prev) => prev === tagKey ? null : tagKey);
  };
  const getFileName = (path) => {
    return path.split("/").pop() || path;
  };
  const getShortPath = (path) => {
    const segments = path.split("/");
    if (segments.length <= 4) return path;
    return ".../" + segments.slice(-4).join("/");
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", "data-cy": sel("devtools.tags.viewer"), children: [
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
      /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "pt-4", children: [
        /* @__PURE__ */ jsx("div", { className: "text-2xl font-bold text-violet-600 dark:text-violet-400", children: totalTags }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("totalTags") })
      ] }) }),
      /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "pt-4", children: [
        /* @__PURE__ */ jsx("div", { className: "text-2xl font-bold text-blue-600 dark:text-blue-400", children: COVERAGE_SUMMARY.tags.testFiles }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("testFiles") })
      ] }) })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "relative", children: [
      /* @__PURE__ */ jsx(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          placeholder: t("search"),
          value: searchQuery,
          onChange: (e) => setSearchQuery(e.target.value),
          className: "pl-10",
          "data-cy": sel("devtools.tags.search")
        }
      )
    ] }),
    /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("showing", { count: filteredTagCount }) }),
    /* @__PURE__ */ jsx("div", { className: "space-y-6", children: CATEGORY_DISPLAY_ORDER.map((category) => {
      const tags = filteredTagsByCategory[category];
      if (!tags || Object.keys(tags).length === 0) return null;
      const isExpanded = expandedCategories.has(category);
      const tagCount = Object.keys(tags).length;
      return /* @__PURE__ */ jsxs(Card, { "data-cy": sel("devtools.tags.category", { category }), children: [
        /* @__PURE__ */ jsx(CardHeader, { className: "pb-2", children: /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: () => toggleCategory(category),
            className: "flex items-center justify-between w-full text-left",
            children: [
              /* @__PURE__ */ jsxs(CardTitle, { className: "text-lg flex items-center gap-2", children: [
                /* @__PURE__ */ jsx(Tag, { className: "h-4 w-4 text-violet-600 dark:text-violet-400" }),
                t(`categories.${category}`),
                /* @__PURE__ */ jsx(Badge, { variant: "secondary", className: "ml-2", children: tagCount })
              ] }),
              /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: isExpanded ? "\u2212" : "+" })
            ]
          }
        ) }),
        isExpanded && /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3", children: [
          /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: Object.entries(tags).map(([key, data]) => {
            const link = getLinkForTag(category, key);
            const isCopied = copiedTag === data.tag;
            const isExpanded2 = expandedTag === `${category}-${key}`;
            const tagKey = `${category}-${key}`;
            return /* @__PURE__ */ jsxs("div", { className: "relative group", children: [
              /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                /* @__PURE__ */ jsxs(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    className: cn(
                      CATEGORY_COLORS[category],
                      "font-mono text-sm px-3 py-1 h-auto",
                      isExpanded2 && "ring-2 ring-offset-1 ring-violet-500"
                    ),
                    onClick: () => toggleTagExpand(tagKey),
                    title: t("expandHint"),
                    "data-cy": sel("devtools.tags.tag", { tag: key }),
                    children: [
                      isExpanded2 ? /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3 mr-1" }) : /* @__PURE__ */ jsx(ChevronRight, { className: "h-3 w-3 mr-1" }),
                      data.tag,
                      /* @__PURE__ */ jsxs("span", { className: "ml-2 text-xs opacity-70", children: [
                        "(",
                        data.testCount,
                        ")"
                      ] })
                    ]
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    className: "h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",
                    onClick: (e) => {
                      e.stopPropagation();
                      copyGrepCommand(data.tag);
                    },
                    title: t("copyHint"),
                    children: isCopied ? /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 text-green-600" }) : /* @__PURE__ */ jsx(Copy, { className: "h-3 w-3" })
                  }
                )
              ] }),
              link && /* @__PURE__ */ jsx(
                Link,
                {
                  href: link,
                  className: "absolute -top-1 -right-1 bg-white dark:bg-gray-800 rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",
                  title: "View details",
                  children: /* @__PURE__ */ jsx(ExternalLink, { className: "h-3 w-3 text-violet-600" })
                }
              )
            ] }, key);
          }) }),
          Object.entries(tags).map(([key, data]) => {
            const tagKey = `${category}-${key}`;
            if (expandedTag !== tagKey) return null;
            return /* @__PURE__ */ jsxs(
              "div",
              {
                className: "mt-3 p-4 bg-muted/50 rounded-lg border border-border animate-in fade-in slide-in-from-top-2 duration-200",
                "data-cy": sel("devtools.tags.files-panel", { tag: key }),
                children: [
                  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-3", children: [
                    /* @__PURE__ */ jsx(FileCode2, { className: "h-4 w-4 text-muted-foreground" }),
                    /* @__PURE__ */ jsxs("span", { className: "text-sm font-medium", children: [
                      t("testFiles"),
                      " (",
                      data.files.length,
                      ")"
                    ] })
                  ] }),
                  /* @__PURE__ */ jsx("ul", { className: "space-y-1.5", children: data.files.map((file, idx) => {
                    const fileName = getFileName(file);
                    const shortPath = getShortPath(file);
                    const isHighlighted = searchQuery && file.toLowerCase().includes(searchQuery.toLowerCase());
                    return /* @__PURE__ */ jsxs(
                      "li",
                      {
                        className: cn(
                          "text-xs font-mono px-2 py-1.5 rounded",
                          isHighlighted ? "bg-yellow-100 dark:bg-yellow-900/30 text-yellow-900 dark:text-yellow-200" : "bg-background hover:bg-muted"
                        ),
                        title: file,
                        children: [
                          /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: shortPath.replace(fileName, "") }),
                          /* @__PURE__ */ jsx("span", { className: "font-medium", children: fileName })
                        ]
                      },
                      idx
                    );
                  }) })
                ]
              },
              `panel-${key}`
            );
          })
        ] })
      ] }, category);
    }) }),
    filteredTagCount === 0 && /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "flex flex-col items-center justify-center py-12", children: [
      /* @__PURE__ */ jsx(Search, { className: "h-12 w-12 text-muted-foreground mb-4" }),
      /* @__PURE__ */ jsx("p", { className: "text-lg font-medium", children: t("noResults") }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("noResultsHint") })
    ] }) }),
    copiedTag && /* @__PURE__ */ jsx("div", { className: "fixed bottom-4 right-4 bg-green-600 text-white px-4 py-2 rounded-md shadow-lg animate-in fade-in slide-in-from-bottom-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
      /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }),
      t("copied")
    ] }) })
  ] });
}
export {
  TagsOverview
};
