"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { Suspense } from "react";
import { Layers, X } from "lucide-react";
import { useTranslations } from "next-intl";
import { useQuery } from "@tanstack/react-query";
import Link from "next/link";
import { Button } from "../../ui/button.js";
import { cn } from "../../../lib/utils/index.js";
import { sel } from "../../../lib/test/index.js";
import { getBlockComponent, normalizeBlockProps } from "../../../lib/blocks/loader.js";
function PatternLoadingSkeleton() {
  return /* @__PURE__ */ jsx("div", { className: "w-full py-12 px-4 animate-pulse bg-muted/20 border-2 border-dashed border-muted-foreground/30 rounded-lg", children: /* @__PURE__ */ jsxs("div", { className: "max-w-7xl mx-auto", children: [
    /* @__PURE__ */ jsx("div", { className: "h-8 bg-muted rounded w-3/4 mb-4" }),
    /* @__PURE__ */ jsx("div", { className: "h-4 bg-muted rounded w-full mb-2" }),
    /* @__PURE__ */ jsx("div", { className: "h-4 bg-muted rounded w-5/6" })
  ] }) });
}
function BlockSkeleton() {
  return /* @__PURE__ */ jsx("div", { className: "w-full py-12 px-4 animate-pulse", children: /* @__PURE__ */ jsxs("div", { className: "max-w-7xl mx-auto", children: [
    /* @__PURE__ */ jsx("div", { className: "h-8 bg-muted rounded w-3/4 mb-4" }),
    /* @__PURE__ */ jsx("div", { className: "h-4 bg-muted rounded w-full mb-2" }),
    /* @__PURE__ */ jsx("div", { className: "h-4 bg-muted rounded w-5/6" })
  ] }) });
}
function getTeamId() {
  if (typeof window !== "undefined") {
    return localStorage.getItem("activeTeamId");
  }
  return null;
}
function buildApiHeaders() {
  const headers = {};
  const teamId = getTeamId();
  if (teamId) {
    headers["x-team-id"] = teamId;
  }
  return headers;
}
function PatternReferencePreview({
  patternRef,
  isSelected,
  onSelect,
  onRemove
}) {
  var _a;
  const t = useTranslations("patterns");
  const { data: patternData, isLoading, isError } = useQuery({
    queryKey: ["patterns", patternRef.ref],
    queryFn: async () => {
      const response = await fetch(`/api/v1/patterns/${patternRef.ref}`, {
        headers: buildApiHeaders()
      });
      if (!response.ok) {
        throw new Error(`Failed to fetch pattern: ${response.statusText}`);
      }
      return response.json();
    },
    staleTime: 1e3 * 60 * 5
    // 5 minutes
  });
  if (isLoading) {
    return /* @__PURE__ */ jsx(PatternLoadingSkeleton, {});
  }
  if (isError || !(patternData == null ? void 0 : patternData.data)) {
    return /* @__PURE__ */ jsx(
      "div",
      {
        className: "w-full py-12 px-4 bg-destructive/10 border-2 border-dashed border-destructive/20 rounded-lg cursor-pointer",
        onClick: onSelect,
        "data-cy": sel("blockEditor.patternReference.container", { ref: patternRef.ref }),
        children: /* @__PURE__ */ jsxs("div", { className: "max-w-7xl mx-auto text-center", children: [
          /* @__PURE__ */ jsx("p", { className: "text-destructive", children: t("messages.notFound") }),
          onRemove && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              className: "mt-4",
              onClick: (e) => {
                e.stopPropagation();
                onRemove();
              },
              "data-cy": sel("blockEditor.patternReference.remove", { ref: patternRef.ref }),
              children: t("actions.removeReference")
            }
          )
        ] })
      }
    );
  }
  const pattern = patternData.data;
  return /* @__PURE__ */ jsxs(
    "div",
    {
      className: cn(
        "group relative cursor-pointer transition-[border-color] duration-150",
        "border-2 rounded-lg overflow-hidden",
        isSelected ? "border-primary border-solid" : "border-dashed border-muted-foreground/30",
        "hover:border-primary/50"
      ),
      onClick: onSelect,
      "data-cy": sel("blockEditor.patternReference.container", { ref: patternRef.ref }),
      children: [
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: "absolute bottom-2 left-2 z-20 bg-primary text-primary-foreground text-xs px-2 py-1 rounded shadow-md flex items-center gap-1",
            "data-cy": sel("blockEditor.patternReference.badge", { ref: patternRef.ref }),
            children: [
              /* @__PURE__ */ jsx(Layers, { className: "h-3 w-3" }),
              /* @__PURE__ */ jsxs("span", { children: [
                t("labels.patternPrefix"),
                ": ",
                pattern.title
              ] })
            ]
          }
        ),
        /* @__PURE__ */ jsxs(
          "div",
          {
            className: cn(
              "absolute top-2 right-2 z-20 flex items-center gap-2 transition-opacity",
              isSelected ? "opacity-100" : "opacity-0 group-hover:opacity-100"
            ),
            children: [
              /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "secondary",
                  size: "sm",
                  className: "h-6 text-xs shadow-md",
                  asChild: true,
                  onClick: (e) => e.stopPropagation(),
                  "data-cy": sel("blockEditor.patternReference.editLink", { ref: patternRef.ref }),
                  children: /* @__PURE__ */ jsxs(Link, { href: `/dashboard/patterns/${patternRef.ref}/edit`, target: "_blank", rel: "noopener noreferrer", children: [
                    t("actions.editPattern"),
                    " \u2192"
                  ] })
                }
              ),
              onRemove && /* @__PURE__ */ jsx(
                Button,
                {
                  variant: "destructive",
                  size: "icon",
                  className: "h-6 w-6 shadow-md",
                  onClick: (e) => {
                    e.stopPropagation();
                    onRemove();
                  },
                  "data-cy": sel("blockEditor.patternReference.remove", { ref: patternRef.ref }),
                  children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
                }
              )
            ]
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "pointer-events-none", children: [
          (_a = pattern.blocks) == null ? void 0 : _a.map((block) => {
            const BlockComponent = getBlockComponent(block.blockSlug);
            if (!BlockComponent) {
              return /* @__PURE__ */ jsx(
                "div",
                {
                  className: "w-full py-8 px-4 bg-destructive/10 border border-destructive/20",
                  children: /* @__PURE__ */ jsx("div", { className: "max-w-7xl mx-auto text-center", children: /* @__PURE__ */ jsxs("p", { className: "text-destructive text-sm", children: [
                    "Block not found: ",
                    /* @__PURE__ */ jsx("code", { className: "font-mono", children: block.blockSlug })
                  ] }) })
                },
                block.id
              );
            }
            const normalizedProps = normalizeBlockProps(block.props);
            return /* @__PURE__ */ jsx(Suspense, { fallback: /* @__PURE__ */ jsx(BlockSkeleton, {}), children: /* @__PURE__ */ jsx(BlockComponent, { ...normalizedProps }) }, block.id);
          }),
          (!pattern.blocks || pattern.blocks.length === 0) && /* @__PURE__ */ jsx("div", { className: "w-full py-12 px-4 text-center text-muted-foreground text-sm", children: t("messages.emptyPattern") })
        ] })
      ]
    }
  );
}
export {
  PatternReferencePreview
};
