"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
import { Input } from "../../ui/input.js";
import { Search, ExpandIcon, ShrinkIcon } from "lucide-react";
import { Button } from "../../ui/button.js";
import { Separator } from "../../ui/separator.js";
import { cn } from "../../../lib/utils/index.js";
import { parseBDDDocument } from "./parser.js";
import { BDDHeader } from "./BDDHeader.js";
import { BDDTestCard } from "./BDDTestCard.js";
import { BDDTableOfContents } from "./BDDTableOfContents.js";
import { useTranslations } from "next-intl";
const LANGUAGE_STORAGE_KEY = "bdd-viewer-language";
function BDDTestViewer({ content, className }) {
  const t = useTranslations("devtools.tests");
  const [document, setDocument] = useState(null);
  const [openTests, setOpenTests] = useState(/* @__PURE__ */ new Set());
  const [searchQuery, setSearchQuery] = useState("");
  const [activeTestId, setActiveTestId] = useState(null);
  const testRefs = useRef(/* @__PURE__ */ new Map());
  const [language, setLanguage] = useState("en");
  useEffect(() => {
    const saved = localStorage.getItem(LANGUAGE_STORAGE_KEY);
    if (saved && (saved === "en" || saved === "es")) {
      setLanguage(saved);
    }
  }, []);
  const handleLanguageChange = useCallback((lang) => {
    setLanguage(lang);
    localStorage.setItem(LANGUAGE_STORAGE_KEY, lang);
  }, []);
  useEffect(() => {
    const parsed = parseBDDDocument(content);
    setDocument(parsed);
    if (parsed.tests.length > 0) {
      setOpenTests(/* @__PURE__ */ new Set([parsed.tests[0].id]));
      setActiveTestId(parsed.tests[0].id);
    }
  }, [content]);
  const hasMultipleLanguages = useMemo(() => {
    if (!document) return false;
    return document.tests.some(
      (test) => {
        var _a, _b;
        return ((_a = test.scenarios) == null ? void 0 : _a.en) && ((_b = test.scenarios) == null ? void 0 : _b.es);
      }
    );
  }, [document]);
  const filteredTests = useMemo(() => {
    if (!document) return [];
    if (!searchQuery.trim()) return document.tests;
    const query = searchQuery.toLowerCase();
    return document.tests.filter((test) => {
      var _a;
      return test.id.toLowerCase().includes(query) || test.title.toLowerCase().includes(query) || test.scenario.toLowerCase().includes(query) || ((_a = test.metadata.tags) == null ? void 0 : _a.some((tag) => tag.toLowerCase().includes(query)));
    });
  }, [document, searchQuery]);
  const handleToggleTest = useCallback((testId) => {
    setOpenTests((prev) => {
      const next = new Set(prev);
      if (next.has(testId)) {
        next.delete(testId);
      } else {
        next.add(testId);
      }
      return next;
    });
    setActiveTestId(testId);
  }, []);
  const handleSelectTest = useCallback((testId) => {
    setOpenTests((prev) => {
      const next = new Set(prev);
      next.add(testId);
      return next;
    });
    setActiveTestId(testId);
    requestAnimationFrame(() => {
      const ref = testRefs.current.get(testId);
      if (ref) {
        ref.scrollIntoView({ behavior: "smooth", block: "start" });
      }
    });
  }, []);
  const handleExpandAll = useCallback(() => {
    if (!document) return;
    setOpenTests(new Set(document.tests.map((t2) => t2.id)));
  }, [document]);
  const handleCollapseAll = useCallback(() => {
    setOpenTests(/* @__PURE__ */ new Set());
  }, []);
  if (!document) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-64", children: /* @__PURE__ */ jsx("div", { className: "animate-pulse text-muted-foreground", children: "Loading..." }) });
  }
  const allExpanded = document.tests.length > 0 && openTests.size === document.tests.length;
  const hasTOC = document.tests.length > 3;
  return /* @__PURE__ */ jsxs("div", { className: cn("flex gap-6 h-full", className), "data-cy": "bdd-test-viewer", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 space-y-6 overflow-y-auto pr-2", children: [
      /* @__PURE__ */ jsx(
        BDDHeader,
        {
          feature: document.feature,
          testCount: document.tests.length,
          language,
          onLanguageChange: handleLanguageChange,
          hasMultipleLanguages
        }
      ),
      /* @__PURE__ */ jsx(Separator, {}),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4", children: [
        /* @__PURE__ */ jsxs("div", { className: "relative flex-1 max-w-sm", 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,
            {
              type: "search",
              placeholder: t("searchPlaceholder"),
              value: searchQuery,
              onChange: (e) => setSearchQuery(e.target.value),
              className: "pl-9",
              "data-cy": "bdd-search"
            }
          )
        ] }),
        /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: /* @__PURE__ */ jsx(
          Button,
          {
            variant: "outline",
            size: "sm",
            onClick: allExpanded ? handleCollapseAll : handleExpandAll,
            "data-cy": "bdd-expand-toggle",
            children: allExpanded ? /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(ShrinkIcon, { className: "h-4 w-4 mr-2" }),
              t("collapseAll")
            ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
              /* @__PURE__ */ jsx(ExpandIcon, { className: "h-4 w-4 mr-2" }),
              t("expandAll")
            ] })
          }
        ) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "space-y-3 pb-6", children: filteredTests.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-center py-12 text-muted-foreground", children: searchQuery ? t("noMatchingTests") : t("noTests") }) : filteredTests.map((test, index) => /* @__PURE__ */ jsx(
        "div",
        {
          "data-test-id": test.id,
          ref: (el) => {
            if (el) testRefs.current.set(test.id, el);
          },
          children: /* @__PURE__ */ jsx(
            BDDTestCard,
            {
              test,
              index,
              isOpen: openTests.has(test.id),
              onToggle: () => handleToggleTest(test.id),
              language
            }
          )
        },
        test.id
      )) })
    ] }),
    hasTOC && /* @__PURE__ */ jsx("aside", { className: "hidden lg:block w-64 shrink-0 self-start sticky top-0", children: /* @__PURE__ */ jsx("div", { className: "max-h-[calc(100vh-14rem)] overflow-y-auto", children: /* @__PURE__ */ jsx(
      BDDTableOfContents,
      {
        tests: document.tests,
        activeTestId,
        onSelectTest: handleSelectTest
      }
    ) }) })
  ] });
}
export {
  BDDTestViewer
};
