"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { useState, useCallback, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { v4 as uuidv4 } from "uuid";
import { copyBlockToClipboard, getBlockFromClipboard, hasBlockInClipboard } from "../../../lib/blocks/clipboard.js";
import { Button } from "../../ui/button.js";
import { Input } from "../../ui/input.js";
import { Separator } from "../../ui/separator.js";
import { ArrowLeft, Save, ExternalLink, Eye, Settings } from "lucide-react";
import Link from "next/link";
import { toast } from "sonner";
import { sel } from "../../../lib/test/index.js";
import { BlockPicker } from "./block-picker.js";
import { BlockPreviewCanvas } from "./block-preview-canvas.js";
import { BlockSettingsPanel } from "./block-settings-panel.js";
import { BlockService } from "../../../lib/services/block.service.js";
import { ViewportToggle } from "./viewport-toggle.js";
import { ConfigPanel } from "./config-panel.js";
import { useSidebar } from "../../../contexts/sidebar-context.js";
import { cn } from "../../../lib/utils/index.js";
function getTeamId() {
  if (typeof window !== "undefined") {
    return localStorage.getItem("activeTeamId");
  }
  return null;
}
function buildApiHeaders(includeContentType = false) {
  const headers = {};
  if (includeContentType) {
    headers["Content-Type"] = "application/json";
  }
  const teamId = getTeamId();
  if (teamId) {
    headers["x-team-id"] = teamId;
  }
  headers["x-builder-source"] = "true";
  return headers;
}
function slugify(text) {
  return text.toLowerCase().normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/[^a-z0-9\s-]/g, "").trim().replace(/\s+/g, "-").replace(/-+/g, "-");
}
function BuilderEditorView({ entitySlug, entityConfig, id, mode, onEntityFieldChange: onEntityFieldChangeProp }) {
  var _a;
  const router = useRouter();
  const t = useTranslations("admin.builder");
  const queryClient = useQueryClient();
  const { isCollapsed } = useSidebar();
  const [blocks, setBlocks] = useState([]);
  const [selectedBlockId, setSelectedBlockId] = useState(null);
  const [title, setTitle] = useState("");
  const [slug, setSlug] = useState("");
  const [slugManuallyEdited, setSlugManuallyEdited] = useState(false);
  const [status, setStatus] = useState("draft");
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [viewMode, setViewMode] = useState("preview");
  const [viewportMode, setViewportMode] = useState("desktop");
  const [leftSidebarMode, setLeftSidebarMode] = useState("blocks");
  const [pageSettings, setPageSettings] = useState({
    seo: {},
    customFields: []
  });
  const [entityFields, setEntityFields] = useState({});
  const [validationErrors, setValidationErrors] = useState({});
  const titleInputRef = useRef(null);
  const showFieldsOption = useMemo(() => {
    var _a2, _b, _c;
    return (((_b = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFields) == null ? void 0 : _b.length) ?? 0) > 0 || ((_c = entityConfig.taxonomies) == null ? void 0 : _c.enabled);
  }, [entityConfig]);
  const showPatternsTab = useMemo(() => {
    return entitySlug !== "patterns";
  }, [entitySlug]);
  const showSlug = useMemo(() => {
    var _a2;
    return ((_a2 = entityConfig.builder) == null ? void 0 : _a2.showSlug) !== false;
  }, [entityConfig]);
  const isPublicEntity = useMemo(() => {
    var _a2;
    return !!((_a2 = entityConfig.access) == null ? void 0 : _a2.basePath);
  }, [entityConfig]);
  const availableBlocks = useMemo(() => {
    return BlockService.getForScope(entitySlug);
  }, [entitySlug]);
  const { data: entityData, isLoading } = useQuery({
    queryKey: [entitySlug, id],
    queryFn: async () => {
      const response = await fetch(`/api/v1/${entitySlug}/${id}`, {
        headers: buildApiHeaders()
      });
      if (!response.ok) throw new Error(`Failed to fetch ${entitySlug}`);
      const data = await response.json();
      return data;
    },
    enabled: mode === "edit" && !!id
  });
  useEffect(() => {
    var _a2, _b;
    if (mode === "edit" && (entityData == null ? void 0 : entityData.data)) {
      const entity = entityData.data;
      setTitle(entity.title ?? "");
      setSlug(entity.slug ?? "");
      setSlugManuallyEdited(true);
      setStatus(entity.status || "draft");
      setBlocks(entity.blocks || []);
      setPageSettings(entity.settings || { seo: {}, customFields: [] });
      const fields = {};
      (_b = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFields) == null ? void 0 : _b.forEach((field) => {
        if (entity[field] !== void 0) {
          fields[field] = entity[field];
        }
      });
      setEntityFields(fields);
    }
  }, [entityData, entityConfig, mode]);
  useEffect(() => {
    var _a2, _b;
    if (mode === "create") {
      setHasUnsavedChanges(title.length > 0 || blocks.length > 0 || status !== "draft");
      return;
    }
    if (!(entityData == null ? void 0 : entityData.data)) return;
    const entity = entityData.data;
    const hasChanges = title !== entity.title || slug !== entity.slug || status !== (entity.status || "draft") || JSON.stringify(blocks) !== JSON.stringify(entity.blocks || []) || JSON.stringify(pageSettings) !== JSON.stringify(entity.settings || { seo: {}, customFields: [] }) || JSON.stringify(entityFields) !== JSON.stringify(
      ((_b = (_a2 = entityConfig.builder) == null ? void 0 : _a2.sidebarFields) == null ? void 0 : _b.reduce((acc, field) => {
        if (entity[field] !== void 0) acc[field] = entity[field];
        return acc;
      }, {})) || {}
    );
    setHasUnsavedChanges(hasChanges);
  }, [title, slug, status, blocks, pageSettings, entityFields, entityData, entityConfig, mode]);
  useEffect(() => {
    if (mode === "create" && titleInputRef.current) {
      const timer = setTimeout(() => {
        var _a2;
        (_a2 = titleInputRef.current) == null ? void 0 : _a2.focus();
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [mode]);
  useEffect(() => {
    if (title && validationErrors.title) {
      setValidationErrors((prev) => ({ ...prev, title: false }));
    }
    if (slug && validationErrors.slug) {
      setValidationErrors((prev) => ({ ...prev, slug: false }));
    }
  }, [title, slug, validationErrors.title, validationErrors.slug]);
  const saveMutation = useMutation({
    mutationFn: async (data) => {
      const url = mode === "create" ? `/api/v1/${entitySlug}` : `/api/v1/${entitySlug}/${id}`;
      const response = await fetch(url, {
        method: mode === "create" ? "POST" : "PATCH",
        headers: buildApiHeaders(true),
        body: JSON.stringify(data)
      });
      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || `Failed to save ${entitySlug}`);
      }
      return response.json();
    },
    onSuccess: (response) => {
      var _a2;
      if (mode === "create") {
        const newId = (_a2 = response.data) == null ? void 0 : _a2.id;
        if (newId) {
          toast.success(t("messages.created"));
          router.push(`/dashboard/${entitySlug}/${newId}/edit`);
        }
      } else {
        queryClient.invalidateQueries({ queryKey: [entitySlug, id] });
        queryClient.invalidateQueries({ queryKey: [entitySlug] });
        toast.success(t("messages.saved"));
        setHasUnsavedChanges(false);
      }
    },
    onError: (error) => {
      toast.error(error.message);
    }
  });
  const validateFields = useCallback(() => {
    var _a2;
    const errors = {};
    if (!title.trim()) {
      errors.title = true;
    }
    if (showSlug && !slug.trim()) {
      errors.slug = true;
    }
    setValidationErrors(errors);
    if (errors.title || errors.slug) {
      if (errors.title) {
        (_a2 = titleInputRef.current) == null ? void 0 : _a2.focus();
      }
      return false;
    }
    return true;
  }, [title, slug, showSlug]);
  const handleSave = useCallback(() => {
    if (!validateFields()) return;
    const data = {
      title,
      slug,
      blocks,
      status,
      settings: pageSettings,
      ...entityFields
    };
    saveMutation.mutate(data);
  }, [title, slug, blocks, status, pageSettings, entityFields, saveMutation, validateFields]);
  const handleSaveDraft = useCallback(() => {
    if (!validateFields()) return;
    const data = {
      title,
      slug,
      blocks,
      status: "draft",
      settings: pageSettings,
      ...entityFields
    };
    saveMutation.mutate(data);
  }, [title, slug, blocks, pageSettings, entityFields, saveMutation, validateFields]);
  const handlePublish = useCallback(() => {
    if (!validateFields()) return;
    const data = {
      title,
      slug,
      blocks,
      status: "published",
      settings: pageSettings,
      ...entityFields
    };
    saveMutation.mutate(data);
  }, [title, slug, blocks, pageSettings, entityFields, saveMutation, validateFields]);
  const handleAddBlock = useCallback((blockSlug) => {
    const newBlock = {
      id: uuidv4(),
      blockSlug,
      props: {}
    };
    if (selectedBlockId) {
      const index = blocks.findIndex((b) => b.id === selectedBlockId);
      if (index !== -1) {
        const newBlocks = [...blocks];
        newBlocks.splice(index + 1, 0, newBlock);
        setBlocks(newBlocks);
        setSelectedBlockId(newBlock.id);
        return;
      }
    }
    setBlocks((prev) => [...prev, newBlock]);
    setSelectedBlockId(newBlock.id);
  }, [blocks, selectedBlockId]);
  const handleAddPattern = useCallback((patternId) => {
    const patternRef = {
      type: "pattern",
      ref: patternId,
      id: uuidv4()
      // Unique instance ID
    };
    setBlocks((prev) => [...prev, patternRef]);
    setSelectedBlockId(patternRef.id);
  }, []);
  const handleRemoveBlock = useCallback((blockId) => {
    setBlocks((prev) => prev.filter((b) => b.id !== blockId));
    if (selectedBlockId === blockId) {
      setSelectedBlockId(null);
    }
  }, [selectedBlockId]);
  const [clipboardHasBlock, setClipboardHasBlock] = useState(() => hasBlockInClipboard());
  const handleCopyBlock = useCallback((blockId) => {
    const block = blocks.find((b) => b.id === blockId);
    if (block) {
      copyBlockToClipboard(block);
      setClipboardHasBlock(true);
      toast.success(t("messages.blockCopied"));
    }
  }, [blocks, t]);
  const handlePasteBlock = useCallback(() => {
    const clipboardData = getBlockFromClipboard();
    if (!clipboardData) return;
    const newBlock = {
      id: uuidv4(),
      blockSlug: clipboardData.blockSlug,
      props: { ...clipboardData.props }
    };
    if (selectedBlockId) {
      const index = blocks.findIndex((b) => b.id === selectedBlockId);
      if (index !== -1) {
        const newBlocks = [...blocks];
        newBlocks.splice(index + 1, 0, newBlock);
        setBlocks(newBlocks);
        setSelectedBlockId(newBlock.id);
        toast.success(t("messages.blockPasted"));
        return;
      }
    }
    setBlocks((prev) => [...prev, newBlock]);
    setSelectedBlockId(newBlock.id);
    toast.success(t("messages.blockPasted"));
  }, [blocks, selectedBlockId, t]);
  const handleDuplicateBlock = useCallback((blockId) => {
    const block = blocks.find((b) => b.id === blockId);
    if (block) {
      const duplicated = {
        ...block,
        id: uuidv4(),
        props: { ...block.props }
      };
      const index = blocks.findIndex((b) => b.id === blockId);
      const newBlocks = [...blocks];
      newBlocks.splice(index + 1, 0, duplicated);
      setBlocks(newBlocks);
      setSelectedBlockId(duplicated.id);
    }
  }, [blocks]);
  const handleUpdateBlockProps = useCallback((blockId, props) => {
    setBlocks((prev) => prev.map(
      (block) => block.id === blockId ? { ...block, props } : block
    ));
  }, []);
  const handleReorderBlocks = useCallback((newBlocks) => {
    setBlocks(newBlocks.filter((b) => !("ref" in b)));
  }, []);
  const handleMoveBlockUp = useCallback((blockId) => {
    setBlocks((prev) => {
      const index = prev.findIndex((b) => b.id === blockId);
      if (index <= 0) return prev;
      const newBlocks = [...prev];
      [newBlocks[index - 1], newBlocks[index]] = [newBlocks[index], newBlocks[index - 1]];
      return newBlocks;
    });
  }, []);
  const handleMoveBlockDown = useCallback((blockId) => {
    setBlocks((prev) => {
      const index = prev.findIndex((b) => b.id === blockId);
      if (index < 0 || index >= prev.length - 1) return prev;
      const newBlocks = [...prev];
      [newBlocks[index], newBlocks[index + 1]] = [newBlocks[index + 1], newBlocks[index]];
      return newBlocks;
    });
  }, []);
  const handleEntityFieldChange = useCallback((field, value) => {
    setEntityFields((prev) => ({ ...prev, [field]: value }));
    onEntityFieldChangeProp == null ? void 0 : onEntityFieldChangeProp(field, value);
  }, [onEntityFieldChangeProp]);
  const handleLeftSidebarToggle = useCallback((value) => {
    if (!value || value === leftSidebarMode) {
      setLeftSidebarMode("none");
    } else {
      setLeftSidebarMode(value);
    }
  }, [leftSidebarMode]);
  const handleViewModeChange = useCallback((mode2) => {
    setViewMode(mode2);
    if (mode2 === "settings") {
      setSelectedBlockId(null);
    }
  }, []);
  const selectedBlock = selectedBlockId ? blocks.find((b) => b.id === selectedBlockId) : void 0;
  const publicUrl = useMemo(() => {
    var _a2, _b, _c;
    if (status !== "published" || !slug) return null;
    const basePath = ((_a2 = entityConfig.access) == null ? void 0 : _a2.basePath) ?? ((_c = (_b = entityConfig.builder) == null ? void 0 : _b.public) == null ? void 0 : _c.basePath) ?? "";
    return basePath === "/" ? `/${slug}` : `${basePath}/${slug}`;
  }, [status, slug, entityConfig]);
  const leftSidebarOptions = useMemo(() => {
    const options = [
      {
        value: "blocks",
        label: t("sidebar.blocks"),
        dataCy: "sidebar-blocks"
      }
    ];
    if (showFieldsOption) {
      options.push({
        value: "fields",
        label: t("sidebar.fields"),
        dataCy: "sidebar-fields"
      });
    }
    return options;
  }, [t, showFieldsOption]);
  const statusOptions = useMemo(() => {
    return [
      { value: "draft", label: t("status.draft") },
      { value: "published", label: t("status.published") },
      { value: "scheduled", label: t("status.scheduled") },
      { value: "archived", label: t("status.archived") }
    ];
  }, [t]);
  if (mode === "edit" && isLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex items-center justify-center h-screen", children: /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t("loading") }) });
  }
  return /* @__PURE__ */ jsxs("div", { className: cn(
    "fixed inset-0 pt-14 pb-20 lg:top-16 lg:pt-0 lg:pb-0 flex flex-col bg-background z-20 transition-[width,padding] duration-300",
    isCollapsed ? "lg:left-16" : "lg:left-64"
  ), "data-cy": sel("blockEditor.container"), children: [
    /* @__PURE__ */ jsx(
      "header",
      {
        className: "shrink-0 border-b bg-background h-16 shadow-sm",
        "data-cy": sel("blockEditor.header.container"),
        children: /* @__PURE__ */ jsxs("div", { className: "h-full flex items-center justify-between px-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4 flex-1", children: [
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "ghost",
                size: "icon",
                className: "h-8 w-8",
                asChild: true,
                "data-cy": sel("blockEditor.header.backButton"),
                children: /* @__PURE__ */ jsx(Link, { href: `/dashboard/${entitySlug}`, children: /* @__PURE__ */ jsx(ArrowLeft, { className: "h-4 w-4" }) })
              }
            ),
            /* @__PURE__ */ jsx(Separator, { orientation: "vertical", className: "h-8" }),
            /* @__PURE__ */ jsxs("div", { className: "flex flex-col justify-center", "data-cy": sel("blockEditor.header.titleWrapper"), children: [
              /* @__PURE__ */ jsx(
                Input,
                {
                  id: "builder-title",
                  name: "builder-title",
                  ref: titleInputRef,
                  value: title,
                  onChange: (e) => {
                    const newTitle = e.target.value;
                    setTitle(newTitle);
                    if (!slugManuallyEdited || !slug) {
                      setSlug(slugify(newTitle));
                    }
                  },
                  className: cn(
                    "h-auto py-0 px-0 !text-2xl font-semibold bg-transparent border-none shadow-none rounded-none focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground/50",
                    validationErrors.title && "!text-destructive placeholder:!text-destructive/50"
                  ),
                  placeholder: t("placeholders.title"),
                  "data-cy": sel("blockEditor.header.titleInput")
                }
              ),
              showSlug && /* @__PURE__ */ jsxs(
                "div",
                {
                  className: cn(
                    "flex items-center gap-0.5 text-sm text-muted-foreground",
                    validationErrors.slug && "text-destructive"
                  ),
                  "data-cy": sel("blockEditor.header.slugWrapper"),
                  children: [
                    /* @__PURE__ */ jsx("span", { className: cn("opacity-50", validationErrors.slug && "opacity-100"), "data-cy": sel("blockEditor.header.slugPrefix"), children: "/" }),
                    /* @__PURE__ */ jsx(
                      Input,
                      {
                        id: "builder-slug",
                        name: "builder-slug",
                        value: slug,
                        onChange: (e) => {
                          const newSlug = e.target.value;
                          setSlug(newSlug);
                          if (newSlug !== slugify(title)) {
                            setSlugManuallyEdited(true);
                          }
                        },
                        onBlur: () => {
                          if (!slug.trim()) {
                            setSlugManuallyEdited(false);
                          }
                        },
                        className: cn(
                          "h-auto py-0 px-0 text-sm bg-transparent border-none shadow-none rounded-none focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground/40 w-auto min-w-[60px]",
                          validationErrors.slug && "!text-destructive placeholder:!text-destructive/50"
                        ),
                        placeholder: t("placeholders.slug"),
                        "data-cy": sel("blockEditor.header.slugInput"),
                        style: { width: slug ? `${Math.max(slug.length, 4)}ch` : "60px" }
                      }
                    ),
                    isPublicEntity && publicUrl && /* @__PURE__ */ jsx(
                      Button,
                      {
                        variant: "ghost",
                        size: "icon",
                        className: "h-5 w-5 p-0 ml-1 text-muted-foreground hover:text-foreground",
                        asChild: true,
                        "data-cy": sel("blockEditor.header.externalLink"),
                        children: /* @__PURE__ */ jsx(Link, { href: publicUrl, target: "_blank", children: /* @__PURE__ */ jsx(ExternalLink, { className: "h-3.5 w-3.5" }) })
                      }
                    )
                  ]
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: "bg-muted p-1 rounded-lg flex items-center text-sm font-medium",
                "data-cy": sel("blockEditor.header.viewToggle"),
                children: [
                  /* @__PURE__ */ jsxs(
                    "button",
                    {
                      className: cn(
                        "px-3 py-1.5 rounded-md transition-colors flex items-center gap-2 cursor-pointer",
                        viewMode === "preview" ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10"
                      ),
                      onClick: () => handleViewModeChange("preview"),
                      "data-cy": sel("blockEditor.header.viewPreview"),
                      children: [
                        /* @__PURE__ */ jsx(Eye, { className: "h-3.5 w-3.5" }),
                        /* @__PURE__ */ jsx("span", { children: t("viewMode.preview") })
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxs(
                    "button",
                    {
                      className: cn(
                        "px-3 py-1.5 rounded-md transition-colors flex items-center gap-2 cursor-pointer",
                        viewMode === "settings" ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground hover:bg-muted-foreground/10"
                      ),
                      onClick: () => handleViewModeChange("settings"),
                      "data-cy": sel("blockEditor.header.viewSettings"),
                      children: [
                        /* @__PURE__ */ jsx(Settings, { className: "h-3.5 w-3.5" }),
                        /* @__PURE__ */ jsx("span", { children: t("viewMode.settings") })
                      ]
                    }
                  )
                ]
              }
            ),
            viewMode === "preview" && /* @__PURE__ */ jsx(
              ViewportToggle,
              {
                value: viewportMode,
                onChange: setViewportMode
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 flex-1 justify-end", children: [
            /* @__PURE__ */ jsxs(
              "div",
              {
                className: "flex items-center gap-2 mr-2",
                children: [
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: cn(
                        "w-2 h-2 rounded-full",
                        status === "published" && "bg-green-500",
                        status === "draft" && "bg-gray-400",
                        status === "scheduled" && "bg-blue-500",
                        status === "archived" && "bg-red-500"
                      ),
                      "data-cy": sel("blockEditor.header.statusDot")
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    "span",
                    {
                      className: "text-xs font-medium text-muted-foreground uppercase tracking-wide",
                      "data-cy": sel("blockEditor.header.statusLabel"),
                      children: ((_a = statusOptions.find((o) => o.value === status)) == null ? void 0 : _a.label) || status
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsx(
              Button,
              {
                variant: "outline",
                size: "sm",
                onClick: handleSaveDraft,
                disabled: saveMutation.isPending,
                "data-cy": sel("blockEditor.header.saveButton"),
                children: t("header.actions.saveDraft")
              }
            ),
            /* @__PURE__ */ jsxs(
              Button,
              {
                size: "sm",
                onClick: status === "published" ? handleSave : handlePublish,
                disabled: saveMutation.isPending,
                "data-cy": sel("blockEditor.header.publishButton"),
                children: [
                  /* @__PURE__ */ jsx("span", { children: status === "published" ? t("header.actions.update") : t("header.actions.publish") }),
                  /* @__PURE__ */ jsx(Save, { className: "h-4 w-4 ml-2" })
                ]
              }
            )
          ] })
        ] })
      }
    ),
    /* @__PURE__ */ jsxs("div", { className: "flex flex-1 overflow-hidden", children: [
      /* @__PURE__ */ jsx("div", { className: "w-80 border-r overflow-hidden shrink-0 shadow-sm", children: /* @__PURE__ */ jsx(
        BlockPicker,
        {
          blocks: availableBlocks,
          onAddBlock: handleAddBlock,
          onAddPattern: handleAddPattern,
          entityConfig,
          entityFields,
          onEntityFieldChange: handleEntityFieldChange,
          showFieldsTab: !!showFieldsOption,
          showPatternsTab,
          pageBlocks: blocks,
          selectedBlockId,
          onSelectBlock: setSelectedBlockId,
          onReorderBlocks: handleReorderBlocks,
          onCopyBlock: handleCopyBlock,
          onDuplicateBlock: handleDuplicateBlock,
          onRemoveBlock: handleRemoveBlock,
          onPasteBlock: handlePasteBlock,
          hasClipboardBlock: clipboardHasBlock
        }
      ) }),
      /* @__PURE__ */ jsxs("div", { className: "flex-1 overflow-hidden", children: [
        /* @__PURE__ */ jsx(
          "div",
          {
            className: cn(
              "h-full overflow-y-auto bg-muted/30",
              viewMode !== "preview" && "hidden"
            ),
            "data-cy": sel("blockEditor.previewCanvas.container"),
            children: /* @__PURE__ */ jsx(
              "div",
              {
                className: "mx-auto transition-[width] duration-200 min-h-full",
                style: {
                  width: viewportMode === "mobile" ? "375px" : "100%",
                  maxWidth: "100%"
                },
                "data-cy": sel("blockEditor.previewCanvas.viewport", { mode: viewportMode }),
                children: /* @__PURE__ */ jsx("div", { className: "min-h-full bg-background", children: /* @__PURE__ */ jsx(
                  BlockPreviewCanvas,
                  {
                    blocks,
                    selectedBlockId,
                    onSelectBlock: setSelectedBlockId,
                    onMoveUp: handleMoveBlockUp,
                    onMoveDown: handleMoveBlockDown,
                    onCopy: handleCopyBlock,
                    onDuplicate: handleDuplicateBlock,
                    onRemove: handleRemoveBlock
                  }
                ) })
              }
            )
          }
        ),
        /* @__PURE__ */ jsx("div", { className: cn("h-full", viewMode !== "settings" && "hidden"), children: /* @__PURE__ */ jsx(
          ConfigPanel,
          {
            entityConfig,
            entityFields,
            onEntityFieldChange: handleEntityFieldChange,
            pageSettings,
            onPageSettingsChange: setPageSettings
          }
        ) })
      ] }),
      /* @__PURE__ */ jsx("div", { className: "w-96 border-l overflow-hidden shadow-sm", children: /* @__PURE__ */ jsx(
        BlockSettingsPanel,
        {
          block: selectedBlock,
          onUpdateProps: (props) => {
            if (selectedBlockId) {
              handleUpdateBlockProps(selectedBlockId, props);
            }
          },
          onRemove: () => {
            if (selectedBlockId) {
              handleRemoveBlock(selectedBlockId);
            }
          },
          onClose: () => setSelectedBlockId(null)
        }
      ) })
    ] })
  ] });
}
export {
  BuilderEditorView
};
