"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useMemo } from "react";
import { FileTree } from "./FileTree.js";
import { MarkdownViewer } from "./MarkdownViewer.js";
import { BDDTestViewer } from "./bdd/index.js";
import { TestCoverageDashboard } from "./TestCoverageDashboard.js";
import { cn } from "../../lib/utils/index.js";
import { sel } from "../../lib/test/index.js";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle
} from "../ui/card.js";
import { Button } from "../ui/button.js";
import { Loader2, FileText, AlertCircle, ArrowLeft, LayoutDashboard } from "lucide-react";
import { useTranslations } from "next-intl";
import { useTreeNavigation } from "../../hooks/useTreeNavigation.js";
function pathExistsInTree(tree, path) {
  for (const node of tree) {
    if (node.path === path) {
      return true;
    }
    if (node.children && pathExistsInTree(node.children, path)) {
      return true;
    }
  }
  return false;
}
function TestCasesViewer({ initialPath }) {
  const t = useTranslations("devtools.tests");
  const [tree, setTree] = useState([]);
  const [fileContent, setFileContent] = useState(null);
  const [isLoadingTree, setIsLoadingTree] = useState(true);
  const [isLoadingFile, setIsLoadingFile] = useState(false);
  const [error, setError] = useState(null);
  const {
    selectedPath,
    expandedFolders,
    navigateToFile,
    toggleFolder,
    clearSelection
  } = useTreeNavigation({ basePath: "/devtools/tests" });
  const pathNotFound = useMemo(() => {
    if (!selectedPath || isLoadingTree || tree.length === 0) return false;
    return !pathExistsInTree(tree, selectedPath);
  }, [selectedPath, tree, isLoadingTree]);
  useEffect(() => {
    async function loadTree() {
      try {
        setIsLoadingTree(true);
        const response = await fetch("/api/devtools/tests");
        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.error || "Failed to load test files");
        }
        setTree(data.data.tree || []);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load test files");
      } finally {
        setIsLoadingTree(false);
      }
    }
    loadTree();
  }, []);
  useEffect(() => {
    if (!selectedPath || pathNotFound) {
      setFileContent(null);
      return;
    }
    async function loadFile() {
      setIsLoadingFile(true);
      setError(null);
      try {
        const response = await fetch(`/api/devtools/tests/${selectedPath}`);
        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.error || "Failed to load file");
        }
        setFileContent(data.data);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load file");
        setFileContent(null);
      } finally {
        setIsLoadingFile(false);
      }
    }
    loadFile();
  }, [selectedPath, pathNotFound]);
  if (isLoadingTree) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-96", "data-cy": "devtools-tests-loading", children: /* @__PURE__ */ jsx(Loader2, { className: "h-8 w-8 animate-spin text-violet-600 dark:text-violet-400" }) });
  }
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: "grid grid-cols-1 lg:grid-cols-12 gap-6 h-[calc(100vh-12rem)]",
      "data-cy": "devtools-tests-viewer",
      children: [
        /* @__PURE__ */ jsx("div", { className: "lg:col-span-3", children: /* @__PURE__ */ jsxs(Card, { className: "h-full", children: [
          /* @__PURE__ */ jsxs(CardHeader, { className: "pb-3", children: [
            /* @__PURE__ */ jsxs(CardTitle, { className: "text-lg flex items-center gap-2", children: [
              /* @__PURE__ */ jsx(FileText, { className: "h-5 w-5 text-violet-600 dark:text-violet-400" }),
              t("fileTree")
            ] }),
            /* @__PURE__ */ jsx(CardDescription, { children: t("fileTreeDescription") })
          ] }),
          /* @__PURE__ */ jsxs(CardContent, { className: "overflow-y-auto h-[calc(100%-5rem)]", "data-cy": "devtools-tests-tree", children: [
            selectedPath && /* @__PURE__ */ jsxs(
              Button,
              {
                variant: "ghost",
                size: "sm",
                onClick: clearSelection,
                className: "w-full justify-start gap-2 mb-4",
                "data-cy": sel("devtools.tests.dashboardButton"),
                children: [
                  /* @__PURE__ */ jsx(LayoutDashboard, { className: "h-4 w-4" }),
                  t("dashboard.backToDashboard")
                ]
              }
            ),
            tree.length === 0 ? /* @__PURE__ */ jsx("div", { className: "text-center py-8", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("noTests") }) }) : /* @__PURE__ */ jsx(
              FileTree,
              {
                nodes: tree,
                selectedPath: selectedPath || void 0,
                expandedFolders,
                onSelectFile: navigateToFile,
                onToggleFolder: toggleFolder
              }
            )
          ] })
        ] }) }),
        /* @__PURE__ */ jsx("div", { className: "lg:col-span-9", children: /* @__PURE__ */ jsx(Card, { className: "h-full", children: /* @__PURE__ */ jsxs(CardContent, { className: cn(
          "p-6 h-full",
          // BDD viewer handles its own scrolling, others need overflow
          (selectedPath == null ? void 0 : selectedPath.endsWith(".bdd.md")) ? "" : "overflow-y-auto"
        ), children: [
          pathNotFound && /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex flex-col items-center justify-center h-full text-center",
              "data-cy": "devtools-tests-not-found",
              children: [
                /* @__PURE__ */ jsx(AlertCircle, { className: "h-16 w-16 text-amber-500 mb-4" }),
                /* @__PURE__ */ jsx("p", { className: "text-lg font-medium text-amber-600 dark:text-amber-400", children: t("fileNotFound") }),
                /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mt-2 max-w-md", children: t("fileNotFoundDescription", { path: selectedPath || "" }) }),
                /* @__PURE__ */ jsxs(
                  Button,
                  {
                    variant: "outline",
                    className: "mt-4",
                    onClick: clearSelection,
                    "data-cy": "devtools-tests-back-to-list",
                    children: [
                      /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4 mr-2" }),
                      t("backToList")
                    ]
                  }
                )
              ]
            }
          ),
          !selectedPath && !pathNotFound && /* @__PURE__ */ jsx(TestCoverageDashboard, {}),
          isLoadingFile && !pathNotFound && /* @__PURE__ */ jsx(
            "div",
            {
              className: "flex items-center justify-center h-full",
              "data-cy": "devtools-tests-file-loading",
              children: /* @__PURE__ */ jsx(Loader2, { className: "h-8 w-8 animate-spin text-violet-600 dark:text-violet-400" })
            }
          ),
          error && !pathNotFound && /* @__PURE__ */ jsxs(
            "div",
            {
              className: "flex flex-col items-center justify-center h-full text-center",
              "data-cy": "devtools-tests-error",
              children: [
                /* @__PURE__ */ jsx(AlertCircle, { className: "h-16 w-16 text-destructive mb-4" }),
                /* @__PURE__ */ jsx("p", { className: "text-lg font-medium text-destructive", children: t("error") }),
                /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mt-2", children: error })
              ]
            }
          ),
          !isLoadingFile && !error && !pathNotFound && fileContent && /* @__PURE__ */ jsx("div", { "data-cy": "devtools-tests-content", children: (selectedPath == null ? void 0 : selectedPath.endsWith(".bdd.md")) ? /* @__PURE__ */ jsx(BDDTestViewer, { content: fileContent.content }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            (() => {
              const frontmatter = fileContent.frontmatter;
              const title = frontmatter == null ? void 0 : frontmatter.title;
              if (title && typeof title === "string") {
                return /* @__PURE__ */ jsxs("div", { className: "mb-6 pb-4 border-b border-border", children: [
                  /* @__PURE__ */ jsx("h1", { className: "text-2xl font-bold text-violet-600 dark:text-violet-400", children: title }),
                  /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground mt-1", children: selectedPath })
                ] });
              }
              return null;
            })(),
            /* @__PURE__ */ jsx(MarkdownViewer, { content: fileContent.content })
          ] }) })
        ] }) }) })
      ]
    }
  );
}
export {
  TestCasesViewer
};
