"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { WorkflowGraph } from "../../../components/WorkflowGraph.js";
import { NodeEditDialog } from "../../../components/NodeEditDialog.js";
import { EdgeEditDialog } from "../../../components/EdgeEditDialog.js";
import { NodeEditDialogCrudForm } from "../../../components/NodeEditDialogCrudForm.js";
import { EdgeEditDialogCrudForm } from "../../../components/EdgeEditDialogCrudForm.js";
import { useState, useCallback, useEffect } from "react";
import { useRouter, useSearchParams, usePathname } from "next/navigation";
import { graphToDefinition, definitionToGraph, validateWorkflowGraph, generateStepId, generateTransitionId, appendWorkflowEdge } from "../../../lib/graph-utils.js";
import { performDeleteEdgeFlow, performDeleteNodeFlow } from "../../../lib/visual-editor-delete-flow.js";
import { workflowDefinitionDataSchema } from "../../../data/validators.js";
import { Page } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { Label } from "@open-mercato/ui/primitives/label";
import { Switch } from "@open-mercato/ui/primitives/switch";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { TagsInput } from "@open-mercato/ui/backend/inputs/TagsInput";
import { LoadingMessage } from "@open-mercato/ui/backend/detail";
import { Alert, AlertTitle } from "@open-mercato/ui/primitives/alert";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { FormHeader } from "@open-mercato/ui/backend/forms";
import { apiCall, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { buildRecordInjectionContext, useSetCurrentRecordInjectionContext } from "@open-mercato/ui/backend/injection/recordContext";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { CircleQuestionMark, PanelTopClose, PanelTopOpen, Play, Save, Trash2 } from "lucide-react";
import { NODE_TYPE_ICONS, NODE_TYPE_COLORS, NODE_TYPE_LABELS } from "../../../lib/node-type-icons.js";
import { DefinitionTriggersEditor } from "../../../components/DefinitionTriggersEditor.js";
import { MobileVisualEditor } from "../../../components/mobile/MobileVisualEditor.js";
import { useIsMobile } from "@open-mercato/ui/hooks/useIsMobile";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function VisualEditorPage() {
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const pathname = usePathname();
  const definitionId = searchParams.get("id");
  const isMobile = useIsMobile();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [isLoading, setIsLoading] = useState(!!definitionId);
  const [isSaving, setIsSaving] = useState(false);
  const [nodes, setNodes] = useState([]);
  const [edges, setEdges] = useState([]);
  const [selectedNode, setSelectedNode] = useState(null);
  const [selectedEdge, setSelectedEdge] = useState(null);
  const [showMetadata, setShowMetadata] = useState(true);
  const [isCompactViewport, setIsCompactViewport] = useState(false);
  useEffect(() => {
    if (typeof window === "undefined") return;
    const mediaQuery = window.matchMedia("(max-width: 1279px)");
    const applyViewportMode = () => {
      const compact = mediaQuery.matches;
      setIsCompactViewport(compact);
      setShowMetadata(!compact);
    };
    applyViewportMode();
    mediaQuery.addEventListener("change", applyViewportMode);
    return () => {
      mediaQuery.removeEventListener("change", applyViewportMode);
    };
  }, []);
  const [showNodeDialog, setShowNodeDialog] = useState(false);
  const [showEdgeDialog, setShowEdgeDialog] = useState(false);
  const [showClearConfirm, setShowClearConfirm] = useState(false);
  const [workflowId, setWorkflowId] = useState("");
  const [workflowName, setWorkflowName] = useState("");
  const [description, setDescription] = useState("");
  const [version, setVersion] = useState(1);
  const [enabled, setEnabled] = useState(true);
  const [category, setCategory] = useState("");
  const [tags, setTags] = useState([]);
  const [icon, setIcon] = useState("");
  const [effectiveFrom, setEffectiveFrom] = useState("");
  const [effectiveTo, setEffectiveTo] = useState("");
  const [triggers, setTriggers] = useState([]);
  const [source, setSource] = useState(null);
  const [updatedAt, setUpdatedAt] = useState(null);
  const isCodeOnly = source === "code";
  const isCodeOverride = source === "code_override";
  useEffect(() => {
    const loadDefinition = async () => {
      if (!definitionId) {
        setIsLoading(false);
        return;
      }
      try {
        const result = await apiCall(`/api/workflows/definitions/${definitionId}`);
        if (!result.ok) {
          flash(`Failed to load workflow: ${result.result?.error || "Unknown error"}`, "error");
          setIsLoading(false);
          return;
        }
        const definition = result.result?.data;
        setWorkflowId(definition.workflowId);
        setWorkflowName(definition.workflowName || definition.definition.workflowName || "");
        setDescription(definition.description || definition.definition.description || "");
        setVersion(definition.version);
        setEnabled(definition.enabled);
        setCategory(definition.metadata?.category || "");
        setTags(definition.metadata?.tags || []);
        setIcon(definition.metadata?.icon || "");
        setEffectiveFrom(definition.effectiveFrom || "");
        setEffectiveTo(definition.effectiveTo || "");
        const graph = definitionToGraph(definition.definition);
        setNodes(graph.nodes);
        setEdges(graph.edges);
        setTriggers(definition.definition?.triggers || []);
        setSource(definition.source ?? null);
        setUpdatedAt(typeof definition.updatedAt === "string" ? definition.updatedAt : null);
      } catch (error) {
        logger.error("Error loading workflow definition", { err: error });
        flash("Failed to load workflow definition", "error");
      } finally {
        setIsLoading(false);
      }
    };
    loadDefinition();
  }, [definitionId]);
  const handleNodesChange = useCallback((nextNodes) => {
    if (isCodeOnly) return;
    setNodes(nextNodes);
  }, [isCodeOnly]);
  const handleEdgesChange = useCallback((nextEdges) => {
    if (isCodeOnly) return;
    setEdges(nextEdges);
  }, [isCodeOnly]);
  const handleAddNode = useCallback((nodeType) => {
    if (isCodeOnly) return;
    const newNode = {
      id: generateStepId(nodeType),
      type: nodeType,
      position: {
        x: 250 + nodes.length * 50,
        y: 100 + nodes.length * 150
      },
      data: {
        label: getDefaultLabel(nodeType),
        description: "",
        badge: getDefaultBadge(nodeType),
        status: "pending"
      }
    };
    setNodes((nds) => [...nds, newNode]);
  }, [nodes.length, isCodeOnly]);
  const handleNodeClick = useCallback((_event, node) => {
    if (isCodeOnly) return;
    setSelectedNode(node);
    setSelectedEdge(null);
    setShowNodeDialog(true);
  }, [isCodeOnly]);
  const handleEdgeClick = useCallback((_event, edge) => {
    if (isCodeOnly) return;
    setSelectedEdge(edge);
    setSelectedNode(null);
    setShowEdgeDialog(true);
  }, [isCodeOnly]);
  const handleSaveNode = useCallback((nodeId, updates) => {
    setNodes(
      (nds) => nds.map(
        (node) => node.id === nodeId ? { ...node, data: { ...node.data, ...updates } } : node
      )
    );
    flash("Node updated successfully", "success");
  }, []);
  const handleSaveEdge = useCallback((edgeId, updates) => {
    setEdges(
      (eds) => eds.map(
        (edge) => edge.id === edgeId ? { ...edge, data: { ...edge.data, ...updates } } : edge
      )
    );
    flash("Transition updated successfully", "success");
  }, []);
  const handleDeleteEdge = useCallback(async (edgeId) => {
    await performDeleteEdgeFlow(edgeId, {
      confirm,
      t,
      setShowEdgeDialog,
      setSelectedEdge,
      setEdges,
      notifyDeleted: () => flash("Transition deleted successfully", "success")
    });
  }, [confirm, t]);
  const handleDeleteNode = useCallback(async (nodeId) => {
    await performDeleteNodeFlow(nodeId, {
      nodes,
      confirm,
      t,
      setShowNodeDialog,
      setSelectedNode,
      setNodes,
      setEdges,
      notifyDeleted: () => flash("Step deleted successfully", "success")
    });
  }, [confirm, nodes, t]);
  const handleConnect = useCallback((connection) => {
    const newEdge = {
      id: generateTransitionId(connection.source, connection.target),
      source: connection.source,
      target: connection.target,
      type: "smoothstep",
      data: {
        trigger: "auto",
        preConditions: [],
        postConditions: [],
        activities: [],
        label: ""
      }
    };
    setEdges((eds) => appendWorkflowEdge(eds, newEdge));
  }, []);
  const handleValidate = useCallback(() => {
    const graphErrors = validateWorkflowGraph(nodes, edges);
    const allErrors = [...graphErrors];
    try {
      const definitionData = graphToDefinition(nodes, edges, { includePositions: true });
      const result = workflowDefinitionDataSchema.safeParse(definitionData);
      if (!result.success) {
        result.error.issues.forEach((issue) => {
          allErrors.push({
            type: "error",
            message: `Schema validation: ${issue.path.join(".")} - ${issue.message}`
          });
        });
      }
    } catch (error) {
      allErrors.push({
        type: "error",
        message: `Schema validation failed: ${error instanceof Error ? error.message : "Unknown error"}`
      });
    }
    if (allErrors.length === 0) {
      flash("Validation passed! Your workflow is valid and ready to save.", "success");
    } else {
      const firstError = allErrors[0];
      const errorCount = allErrors.length;
      const message = errorCount > 1 ? `${firstError.message} (and ${errorCount - 1} more ${errorCount === 2 ? "issue" : "issues"})` : firstError.message;
      flash(message, firstError.type === "error" ? "error" : "warning");
    }
  }, [nodes, edges]);
  const handleSave = useCallback(async () => {
    if (!workflowId || !workflowName) {
      flash("Workflow ID and Name are required fields", "error");
      return;
    }
    const errors = validateWorkflowGraph(nodes, edges);
    const criticalErrors = errors.filter((e) => e.type === "error");
    if (criticalErrors.length > 0) {
      flash(`Cannot save: ${criticalErrors.length} validation error(s) found. Please fix them first.`, "error");
      return;
    }
    const graphDefinition = graphToDefinition(nodes, edges, { includePositions: true });
    const definitionData = {
      ...graphDefinition,
      triggers: triggers.length > 0 ? triggers : void 0
    };
    const schemaResult = workflowDefinitionDataSchema.safeParse(definitionData);
    if (!schemaResult.success) {
      const firstIssue = schemaResult.error.issues[0];
      flash(`Schema error: ${firstIssue.path.join(".")} - ${firstIssue.message}`, "error");
      return;
    }
    setIsSaving(true);
    try {
      const metadata2 = {};
      if (category) metadata2.category = category;
      if (tags.length > 0) metadata2.tags = tags;
      if (icon) metadata2.icon = icon;
      const isUpdate = !!definitionId;
      let result;
      if (isUpdate) {
        result = await withScopedApiRequestHeaders(
          buildOptimisticLockHeader(updatedAt),
          () => apiCall(`/api/workflows/definitions/${definitionId}`, {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              workflowName,
              description: description || null,
              version,
              definition: definitionData,
              metadata: Object.keys(metadata2).length > 0 ? metadata2 : null,
              enabled,
              effectiveFrom: effectiveFrom || null,
              effectiveTo: effectiveTo || null
            })
          })
        );
      } else {
        result = await apiCall("/api/workflows/definitions", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            workflowId,
            workflowName,
            description: description || null,
            version,
            definition: definitionData,
            metadata: Object.keys(metadata2).length > 0 ? metadata2 : null,
            enabled,
            effectiveFrom: effectiveFrom || null,
            effectiveTo: effectiveTo || null
          })
        });
      }
      if (!result.ok) {
        const conflictError = Object.assign(new Error(t("workflows.messages.saveFailed", "Failed to save")), {
          status: result.status,
          ...result.result && typeof result.result === "object" ? result.result : {}
        });
        if (!surfaceRecordConflict(conflictError, t)) {
          flash(`Failed to save: ${result.result?.error || "Unknown error"}`, "error");
        }
        return;
      }
      const savedDefinition = result.result?.data;
      flash(`Workflow ${isUpdate ? "updated" : "created"} successfully!`, "success");
      setTimeout(() => {
        router.push(`/backend/definitions/${savedDefinition.id}`);
      }, 1500);
    } catch (error) {
      logger.error("Error saving workflow definition", { err: error });
      flash("Failed to save workflow definition. Please try again.", "error");
    } finally {
      setIsSaving(false);
    }
  }, [nodes, edges, workflowId, workflowName, description, version, enabled, category, tags, icon, effectiveFrom, effectiveTo, triggers, definitionId, updatedAt, router]);
  const handleCustomize = useCallback(async () => {
    if (!definitionId) return;
    setIsSaving(true);
    try {
      const result = await apiCall(
        `/api/workflows/definitions/${definitionId}/customize`,
        { method: "POST" }
      );
      if (!result.ok) {
        flash(result.result?.error || "Failed to customize workflow", "error");
        return;
      }
      const newId = result.result?.data?.id;
      if (!newId) return;
      router.push(`/backend/definitions/visual-editor?id=${encodeURIComponent(newId)}`);
      router.refresh();
    } finally {
      setIsSaving(false);
    }
  }, [definitionId, router]);
  const handleResetToCode = useCallback(async () => {
    if (!definitionId) return;
    const confirmed = await confirm({
      title: t("workflows.actions.resetToCode"),
      description: t("workflows.actions.resetConfirm"),
      confirmText: t("workflows.actions.resetToCode"),
      variant: "destructive"
    });
    if (!confirmed) return;
    setIsSaving(true);
    try {
      const result = await apiCall(
        `/api/workflows/definitions/${definitionId}/reset-to-code`,
        { method: "POST" }
      );
      if (!result.ok) {
        flash(result.result?.error || "Failed to reset workflow", "error");
        return;
      }
      const codeId = result.result?.data?.id || (workflowId ? `code:${workflowId}` : null);
      if (!codeId) return;
      router.push(`/backend/definitions/visual-editor?id=${encodeURIComponent(codeId)}`);
      router.refresh();
    } finally {
      setIsSaving(false);
    }
  }, [definitionId, workflowId, router, confirm, t]);
  const handleTest = useCallback(() => {
    const errors = validateWorkflowGraph(nodes, edges);
    const criticalErrors = errors.filter((e) => e.type === "error");
    if (criticalErrors.length > 0) {
      flash(`Cannot test: ${criticalErrors.length} validation error(s) found. Please fix them first.`, "error");
      return;
    }
    flash("Test functionality will be implemented next", "info");
  }, [nodes, edges]);
  const handleLoadExample = useCallback(() => {
    setWorkflowId("approval_workflow");
    setWorkflowName("Simple Approval Workflow");
    setDescription("A basic approval workflow for reviewing and approving requests");
    setVersion(1);
    setEnabled(true);
    setCategory("Approvals");
    setTags(["approval", "review"]);
    const exampleNodes = [
      {
        id: "start",
        type: "start",
        position: { x: 250, y: 50 },
        data: {
          label: "Start",
          description: "Workflow begins",
          status: "pending",
          badge: "Start"
        }
      },
      {
        id: "step1",
        type: "userTask",
        position: { x: 250, y: 250 },
        data: {
          label: "Review Request",
          description: "User reviews the incoming request",
          status: "pending",
          stepNumber: 1,
          badge: "User Task",
          assignedToRoles: ["Reviewer"]
        }
      },
      {
        id: "end",
        type: "end",
        position: { x: 250, y: 450 },
        data: {
          label: "Complete",
          description: "Workflow ends",
          status: "pending",
          badge: "End"
        }
      }
    ];
    const exampleEdges = [
      {
        id: "e-start-step1",
        source: "start",
        target: "step1",
        type: "smoothstep",
        data: {
          trigger: "auto",
          preConditions: [],
          postConditions: [],
          activities: []
        }
      },
      {
        id: "e-step1-end",
        source: "step1",
        target: "end",
        type: "smoothstep",
        data: {
          trigger: "auto",
          preConditions: [],
          postConditions: [],
          activities: []
        }
      }
    ];
    setNodes(exampleNodes);
    setEdges(exampleEdges);
    flash("Example workflow loaded", "success");
  }, []);
  const handleClear = useCallback(() => {
    if (nodes.length > 0 || edges.length > 0 || workflowId || workflowName) {
      setShowClearConfirm(true);
    }
  }, [nodes.length, edges.length, workflowId, workflowName]);
  const confirmClear = useCallback(() => {
    setNodes([]);
    setEdges([]);
    setWorkflowId("");
    setWorkflowName("");
    setDescription("");
    setVersion(1);
    setEnabled(true);
    setCategory("");
    setTags([]);
    setIcon("");
    setEffectiveFrom("");
    setEffectiveTo("");
    setTriggers([]);
    setShowClearConfirm(false);
    flash("Canvas cleared", "success");
  }, []);
  useSetCurrentRecordInjectionContext(
    buildRecordInjectionContext({
      resourceKind: "workflows.definition",
      resourceId: definitionId,
      updatedAt,
      path: pathname
    })
  );
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { className: "flex items-center justify-center min-h-[50vh]", children: /* @__PURE__ */ jsx(LoadingMessage, { label: "Loading workflow definition..." }) });
  }
  const metadata = {
    workflowId,
    workflowName,
    description,
    version,
    enabled,
    category,
    tags,
    icon,
    effectiveFrom,
    effectiveTo,
    triggers
  };
  const metadataHandlers = {
    setWorkflowId,
    setWorkflowName,
    setDescription,
    setVersion,
    setEnabled,
    setCategory,
    setTags,
    setIcon,
    setEffectiveFrom,
    setEffectiveTo,
    setTriggers
  };
  const sharedDialogs = /* @__PURE__ */ jsxs(Fragment, { children: [
    process.env.NEXT_PUBLIC_WORKFLOW_CRUDFORM_ENABLED === "true" ? /* @__PURE__ */ jsx(NodeEditDialogCrudForm, { node: selectedNode, isOpen: showNodeDialog, onClose: () => setShowNodeDialog(false), onSave: handleSaveNode, onDelete: handleDeleteNode }) : /* @__PURE__ */ jsx(NodeEditDialog, { node: selectedNode, isOpen: showNodeDialog, onClose: () => setShowNodeDialog(false), onSave: handleSaveNode, onDelete: handleDeleteNode }),
    process.env.NEXT_PUBLIC_WORKFLOW_CRUDFORM_ENABLED === "true" ? /* @__PURE__ */ jsx(EdgeEditDialogCrudForm, { edge: selectedEdge, isOpen: showEdgeDialog, onClose: () => setShowEdgeDialog(false), onSave: handleSaveEdge, onDelete: handleDeleteEdge }) : /* @__PURE__ */ jsx(EdgeEditDialog, { edge: selectedEdge, isOpen: showEdgeDialog, onClose: () => setShowEdgeDialog(false), onSave: handleSaveEdge, onDelete: handleDeleteEdge }),
    /* @__PURE__ */ jsx(Dialog, { open: showClearConfirm, onOpenChange: setShowClearConfirm, children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-md", children: [
      /* @__PURE__ */ jsxs(DialogHeader, { children: [
        /* @__PURE__ */ jsx(DialogTitle, { children: t("workflows.visualEditor.clearTitle") }),
        /* @__PURE__ */ jsx(DialogDescription, { children: t("workflows.visualEditor.clearDescription") })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => setShowClearConfirm(false), children: t("common.cancel", "Cancel") }),
        /* @__PURE__ */ jsx(Button, { variant: "destructive", onClick: confirmClear, children: t("common.clear", "Clear") })
      ] })
    ] }) })
  ] });
  if (isMobile) {
    return /* @__PURE__ */ jsxs(Page, { className: "flex h-[100svh] flex-col space-y-0 overflow-hidden", children: [
      /* @__PURE__ */ jsx(
        MobileVisualEditor,
        {
          definitionId,
          isSaving,
          nodes,
          edges,
          onNodesChange: handleNodesChange,
          onEdgesChange: handleEdgesChange,
          onNodeClick: handleNodeClick,
          onEdgeClick: handleEdgeClick,
          onConnect: handleConnect,
          onAddNode: handleAddNode,
          onSave: handleSave,
          onValidate: handleValidate,
          onTest: handleTest,
          onLoadExample: handleLoadExample,
          onClear: handleClear,
          metadata,
          metadataHandlers
        }
      ),
      sharedDialogs,
      ConfirmDialogElement
    ] });
  }
  return /* @__PURE__ */ jsxs(Page, { className: "space-y-0 overflow-x-hidden", children: [
    /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3", children: /* @__PURE__ */ jsx(
      FormHeader,
      {
        mode: "detail",
        backHref: "/backend/definitions",
        backLabel: t("workflows.definitions.backToList", "Back to definitions"),
        title: definitionId ? workflowName || t("workflows.definitions.singular") : t("workflows.backend.definitions.visual_editor.title"),
        subtitle: definitionId ? t("workflows.definitions.detail.summary", "Editing workflow definition") : t("workflows.definitions.create.summary", "Create and edit workflow definitions visually with a drag-and-drop interface"),
        actionsContent: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-end gap-1 md:gap-2", children: [
          /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: () => setShowMetadata(!showMetadata),
              disabled: isSaving,
              className: "h-8 px-2 text-xs",
              "aria-label": showMetadata ? t("workflows.visualEditor.hideMetadata") : t("workflows.visualEditor.showMetadata"),
              children: [
                showMetadata ? /* @__PURE__ */ jsx(PanelTopClose, { className: "mr-1.5 h-4 w-4" }) : /* @__PURE__ */ jsx(PanelTopOpen, { className: "mr-1.5 h-4 w-4" }),
                showMetadata ? t("workflows.visualEditor.hideMetadata") : t("workflows.visualEditor.showMetadata")
              ]
            }
          ),
          !isCodeOnly && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleLoadExample,
              disabled: isSaving,
              className: "h-8 text-xs",
              children: t("workflows.visualEditor.loadExample")
            }
          ),
          !isCodeOnly && /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "destructive",
              size: "sm",
              onClick: handleClear,
              disabled: isSaving,
              className: "h-8 px-2 text-xs",
              "aria-label": t("workflows.visualEditor.clear"),
              children: [
                /* @__PURE__ */ jsx(Trash2, { className: "mr-1.5 h-4 w-4" }),
                t("workflows.visualEditor.clear")
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleValidate,
              disabled: isSaving,
              className: "h-8 px-2 text-xs",
              "aria-label": t("workflows.visualEditor.validate"),
              children: [
                /* @__PURE__ */ jsx(CircleQuestionMark, { className: "mr-1.5 h-4 w-4" }),
                t("workflows.visualEditor.validate")
              ]
            }
          ),
          !isCodeOnly && /* @__PURE__ */ jsxs(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleTest,
              disabled: isSaving,
              className: "h-8 text-xs",
              children: [
                /* @__PURE__ */ jsx(Play, { className: "mr-1.5 h-4 w-4" }),
                t("workflows.visualEditor.runTest")
              ]
            }
          ),
          isCodeOverride && /* @__PURE__ */ jsx(
            Button,
            {
              variant: "outline",
              size: "sm",
              onClick: handleResetToCode,
              disabled: isSaving,
              className: "h-8 text-xs",
              children: t("workflows.actions.resetToCode")
            }
          ),
          isCodeOnly ? /* @__PURE__ */ jsx(
            Button,
            {
              size: "sm",
              onClick: handleCustomize,
              disabled: isSaving,
              className: "h-8 px-2 text-xs md:px-3",
              children: t("workflows.actions.customize")
            }
          ) : /* @__PURE__ */ jsxs(
            Button,
            {
              size: "sm",
              onClick: handleSave,
              disabled: isSaving,
              className: "h-8 px-2 text-xs md:px-3",
              "aria-label": isSaving ? t("workflows.mobile.saving") : definitionId ? t("workflows.common.update") : t("workflows.common.save"),
              children: [
                /* @__PURE__ */ jsx(Save, { className: "mr-1.5 h-4 w-4" }),
                isSaving ? t("workflows.mobile.saving") : definitionId ? t("workflows.common.update") : t("workflows.common.save")
              ]
            }
          )
        ] })
      }
    ) }),
    (isCodeOnly || isCodeOverride) && /* @__PURE__ */ jsxs("div", { className: "shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3", children: [
      isCodeOnly && /* @__PURE__ */ jsx(Alert, { variant: "info", children: /* @__PURE__ */ jsx(AlertTitle, { children: t("workflows.source.code.readonlyBanner") }) }),
      isCodeOverride && /* @__PURE__ */ jsx(Alert, { variant: "warning", children: /* @__PURE__ */ jsx(AlertTitle, { children: t("workflows.source.code_override.banner") }) })
    ] }),
    showMetadata && /* @__PURE__ */ jsxs("div", { className: isCompactViewport ? "shrink-0 border-b border-border bg-background px-3 py-2 max-h-[60svh] overflow-y-auto overscroll-contain md:px-6 md:py-3" : "shrink-0 border-b border-border bg-background px-3 py-2 md:px-6 md:py-3", children: [
      /* @__PURE__ */ jsxs("fieldset", { disabled: isCodeOnly, className: "rounded-lg border bg-card p-3 disabled:opacity-70 md:p-4", children: [
        /* @__PURE__ */ jsx("h2", { className: "mb-3 text-xs font-semibold uppercase text-muted-foreground", children: t("workflows.visualEditor.workflowMetadata") }),
        /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 md:gap-4", children: [
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: "workflowId", className: "text-xs", children: [
              t("workflows.form.workflowId"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "workflowId",
                value: workflowId,
                onChange: (e) => setWorkflowId(e.target.value),
                placeholder: "checkout_workflow",
                disabled: !!definitionId,
                className: "h-8 text-sm"
              }
            ),
            definitionId && /* @__PURE__ */ jsx("p", { className: "text-overline text-muted-foreground", children: t("workflows.visualEditor.readOnly") })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: "workflowName", className: "text-xs", children: [
              t("workflows.form.workflowName"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "workflowName",
                value: workflowName,
                onChange: (e) => setWorkflowName(e.target.value),
                placeholder: "Checkout Process",
                className: "h-8 text-sm"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "category", className: "text-xs", children: t("workflows.form.category") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "category",
                value: category,
                onChange: (e) => setCategory(e.target.value),
                placeholder: "E-Commerce",
                className: "h-8 text-sm"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1 sm:col-span-2 lg:col-span-3", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "description", className: "text-xs", children: t("workflows.form.description") }),
            /* @__PURE__ */ jsx(
              Textarea,
              {
                id: "description",
                value: description,
                onChange: (e) => setDescription(e.target.value),
                placeholder: t("workflows.form.placeholders.description"),
                rows: 2,
                className: "min-h-[60px] text-sm"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsxs(Label, { htmlFor: "version", className: "text-xs", children: [
              t("workflows.form.version"),
              " *"
            ] }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "version",
                type: "number",
                value: version,
                onChange: (e) => setVersion(parseInt(e.target.value) || 1),
                min: 1,
                disabled: !!definitionId,
                className: "h-8 text-sm"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { className: "text-xs", children: t("common.enabled", "Enabled") }),
            /* @__PURE__ */ jsxs("div", { className: "flex h-8 items-center gap-2", children: [
              /* @__PURE__ */ jsx(
                Switch,
                {
                  id: "enabled",
                  checked: enabled,
                  onCheckedChange: setEnabled
                }
              ),
              /* @__PURE__ */ jsx(Label, { htmlFor: "enabled", className: "cursor-pointer text-xs font-normal", children: enabled ? t("common.on", "On") : t("common.off", "Off") })
            ] })
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { className: "text-xs", children: t("workflows.form.tags") }),
            /* @__PURE__ */ jsx(
              TagsInput,
              {
                value: tags,
                onChange: setTags,
                placeholder: t("workflows.form.placeholders.tags")
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "icon", className: "text-xs", children: t("workflows.form.icon") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "icon",
                value: icon,
                onChange: (e) => setIcon(e.target.value),
                placeholder: "ShoppingCart",
                className: "h-8 text-sm"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "effectiveFrom", className: "text-xs", children: t("workflows.form.effectiveFrom") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "effectiveFrom",
                type: "date",
                value: effectiveFrom,
                onChange: (e) => setEffectiveFrom(e.target.value),
                className: "h-8 text-sm"
              }
            )
          ] }),
          /* @__PURE__ */ jsxs("div", { className: "min-w-0 space-y-1", children: [
            /* @__PURE__ */ jsx(Label, { htmlFor: "effectiveTo", className: "text-xs", children: t("workflows.form.effectiveTo") }),
            /* @__PURE__ */ jsx(
              Input,
              {
                id: "effectiveTo",
                type: "date",
                value: effectiveTo,
                onChange: (e) => setEffectiveTo(e.target.value),
                className: "h-8 text-sm"
              }
            )
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsx("fieldset", { disabled: isCodeOnly, className: "mt-3 disabled:opacity-70", children: /* @__PURE__ */ jsx(
        DefinitionTriggersEditor,
        {
          value: triggers,
          onChange: setTriggers
        }
      ) })
    ] }),
    isCompactViewport ? /* @__PURE__ */ jsxs("div", { className: "px-3 py-3 md:px-6 md:py-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "relative min-w-0", children: [
        /* @__PURE__ */ jsx("div", { className: "h-[64svh] min-h-[360px] rounded-lg border bg-card", children: /* @__PURE__ */ jsx(
          WorkflowGraph,
          {
            initialNodes: nodes,
            initialEdges: edges,
            onNodesChange: handleNodesChange,
            onEdgesChange: handleEdgesChange,
            onNodeClick: handleNodeClick,
            onEdgeClick: handleEdgeClick,
            onConnect: handleConnect,
            editable: !isCodeOnly,
            height: "100%"
          }
        ) }),
        nodes.length === 0 && /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-0 flex items-center justify-center px-4", children: /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
          /* @__PURE__ */ jsx("h2", { className: "mb-2 text-lg font-semibold text-foreground", children: t("workflows.visualEditor.startBuilding") }),
          /* @__PURE__ */ jsx("p", { className: "mb-4 text-sm text-muted-foreground", children: t("workflows.visualEditor.tapToAddBelow") }),
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: handleLoadExample,
              className: "pointer-events-auto text-sm text-primary hover:underline",
              children: t("workflows.visualEditor.loadExampleWorkflow")
            }
          )
        ] }) })
      ] }),
      !isCodeOnly && /* @__PURE__ */ jsxs("div", { className: "mt-3 rounded-lg border bg-card p-3", children: [
        /* @__PURE__ */ jsx("h2", { className: "mb-2 text-xs font-semibold uppercase text-muted-foreground", children: t("workflows.visualEditor.stepPalette") }),
        /* @__PURE__ */ jsx("p", { className: "mb-3 text-xs text-muted-foreground", children: t("workflows.visualEditor.tapToAdd") }),
        /* @__PURE__ */ jsx("div", { className: "flex gap-2 overflow-x-auto pb-1", children: ["start", "userTask", "automated", "waitForSignal", "waitForTimer", "subWorkflow", "end"].map((nodeType) => {
          const Icon = NODE_TYPE_ICONS[nodeType];
          return /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode(nodeType),
              className: "flex shrink-0 items-center gap-1 rounded-md border bg-background px-2 py-1 text-xs hover:bg-muted active:bg-muted/50",
              children: [
                /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5" }),
                /* @__PURE__ */ jsx("span", { children: NODE_TYPE_LABELS[nodeType].title })
              ]
            },
            nodeType
          );
        }) })
      ] })
    ] }) : /* @__PURE__ */ jsxs("div", { className: "flex min-h-[72svh] min-w-0 flex-1 border-t border-border", children: [
      !isCodeOnly && /* @__PURE__ */ jsx("div", { className: "w-[24rem] shrink-0 overflow-y-auto border-r border-border bg-background p-6", children: /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
        /* @__PURE__ */ jsx("h2", { className: "mb-2 text-sm font-semibold uppercase text-muted-foreground", children: t("workflows.visualEditor.stepPalette") }),
        /* @__PURE__ */ jsx("p", { className: "mb-4 text-xs text-muted-foreground", children: t("workflows.visualEditor.clickToAdd") }),
        /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("start"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.start} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.start;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.start.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.start.description })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("userTask"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.userTask} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.userTask;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.userTask.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.userTask.description })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("automated"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.automated} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.automated;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.automated.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.automated.description })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("waitForSignal"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.waitForSignal} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.waitForSignal;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.waitForSignal.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.waitForSignal.description })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("waitForTimer"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.waitForTimer} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.waitForTimer;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.waitForTimer.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.waitForTimer.description })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("subWorkflow"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.subWorkflow} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.subWorkflow;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.subWorkflow.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.subWorkflow.description })
              ]
            }
          ),
          /* @__PURE__ */ jsxs(
            "button",
            {
              onClick: () => handleAddNode("end"),
              className: "group relative w-full cursor-pointer rounded-xl border-2 border-border bg-background px-4 py-3 text-left transition-all hover:border-muted-foreground/30 hover:shadow-md",
              children: [
                /* @__PURE__ */ jsx("div", { className: `absolute right-2 top-2 ${NODE_TYPE_COLORS.end} opacity-60 transition-opacity group-hover:opacity-100`, children: (() => {
                  const Icon = NODE_TYPE_ICONS.end;
                  return /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" });
                })() }),
                /* @__PURE__ */ jsx("div", { className: "text-sm font-semibold text-foreground", children: NODE_TYPE_LABELS.end.title }),
                /* @__PURE__ */ jsx("div", { className: "mt-0.5 text-xs text-muted-foreground", children: NODE_TYPE_LABELS.end.description })
              ]
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(Alert, { variant: "info", className: "mt-6", children: [
          /* @__PURE__ */ jsx(AlertTitle, { className: "text-xs", children: t("workflows.visualEditor.howToUse", "How to use:") }),
          /* @__PURE__ */ jsx("div", { className: "mt-2", children: /* @__PURE__ */ jsxs("ul", { className: "list-inside list-disc space-y-1 text-xs", children: [
            /* @__PURE__ */ jsx("li", { children: t("workflows.visualEditor.hint.addSteps", "Click step types to add them") }),
            /* @__PURE__ */ jsx("li", { children: t("workflows.visualEditor.hint.dragSteps", "Drag steps to position them") }),
            /* @__PURE__ */ jsx("li", { children: t("workflows.visualEditor.hint.connectSteps", "Connect steps by dragging from handles") }),
            /* @__PURE__ */ jsx("li", { children: t("workflows.visualEditor.hint.editSteps", "Click steps and transitions to edit them") }),
            /* @__PURE__ */ jsx("li", { children: t("workflows.visualEditor.hint.validate", "Validate before saving") })
          ] }) })
        ] })
      ] }) }),
      /* @__PURE__ */ jsx("div", { className: "min-w-0 flex-1 p-6", children: /* @__PURE__ */ jsxs("div", { className: "relative h-[72svh] min-h-[640px]", children: [
        /* @__PURE__ */ jsx("div", { className: "h-full rounded-lg border bg-card", children: /* @__PURE__ */ jsx(
          WorkflowGraph,
          {
            initialNodes: nodes,
            initialEdges: edges,
            onNodesChange: handleNodesChange,
            onEdgesChange: handleEdgesChange,
            onNodeClick: handleNodeClick,
            onEdgeClick: handleEdgeClick,
            onConnect: handleConnect,
            editable: !isCodeOnly,
            height: "100%"
          }
        ) }),
        nodes.length === 0 && /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-0 flex items-center justify-center px-4", children: /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
          /* @__PURE__ */ jsx("h2", { className: "mb-2 text-xl font-semibold text-foreground", children: t("workflows.visualEditor.startBuilding") }),
          /* @__PURE__ */ jsx("p", { className: "mb-4 text-muted-foreground", children: t("workflows.visualEditor.clickToAddFromPalette") }),
          /* @__PURE__ */ jsx(
            "button",
            {
              onClick: handleLoadExample,
              className: "pointer-events-auto text-sm text-primary hover:underline",
              children: t("workflows.visualEditor.loadExampleWorkflow")
            }
          )
        ] }) })
      ] }) })
    ] }),
    sharedDialogs,
    ConfirmDialogElement
  ] });
}
function getDefaultLabel(nodeType) {
  const labels = {
    start: "Start",
    end: "End",
    userTask: "New User Task",
    automated: "New Automated Task",
    decision: "Decision Point",
    waitForSignal: "Wait for Signal",
    waitForTimer: "Wait for Timer"
  };
  return labels[nodeType] || "New Step";
}
function getDefaultBadge(nodeType) {
  const badges = {
    start: "Start",
    end: "End",
    userTask: "User Task",
    automated: "Automated",
    decision: "Decision",
    waitForSignal: "Wait for Signal",
    waitForTimer: "Wait for Timer"
  };
  return badges[nodeType] || "Task";
}
export {
  VisualEditorPage as default
};
//# sourceMappingURL=page.js.map
