"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { Label } from "@open-mercato/ui/primitives/label";
import { Checkbox } from "@open-mercato/ui/primitives/checkbox";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle
} from "@open-mercato/ui/primitives/dialog";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from "@open-mercato/ui/backend/utils/apiCall";
import { buildOptimisticLockHeader } from "@open-mercato/ui/backend/utils/optimisticLock";
import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger
} from "@open-mercato/ui/primitives/accordion";
import {
  AppearanceSelector
} from "@open-mercato/core/modules/dictionaries/components/AppearanceSelector";
import {
  renderDictionaryColor,
  renderDictionaryIcon
} from "@open-mercato/core/modules/dictionaries/components/dictionaryAppearance";
function normalizePipeline(raw) {
  return {
    id: typeof raw.id === "string" ? raw.id : "",
    name: typeof raw.name === "string" ? raw.name : "",
    isDefault: raw.isDefault === true || raw.is_default === true,
    organizationId: typeof raw.organizationId === "string" ? raw.organizationId : typeof raw.organization_id === "string" ? raw.organization_id : "",
    tenantId: typeof raw.tenantId === "string" ? raw.tenantId : typeof raw.tenant_id === "string" ? raw.tenant_id : "",
    updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : typeof raw.updated_at === "string" ? raw.updated_at : null
  };
}
function normalizeStage(raw) {
  return {
    id: typeof raw.id === "string" ? raw.id : "",
    pipelineId: typeof raw.pipelineId === "string" ? raw.pipelineId : typeof raw.pipeline_id === "string" ? raw.pipeline_id : "",
    label: typeof raw.label === "string" ? raw.label : "",
    order: typeof raw.order === "number" ? raw.order : 0,
    color: typeof raw.color === "string" && raw.color.trim().length ? raw.color.trim() : null,
    icon: typeof raw.icon === "string" && raw.icon.trim().length ? raw.icon.trim() : null,
    updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : typeof raw.updated_at === "string" ? raw.updated_at : null
  };
}
function PipelineSettings() {
  const t = useT();
  const scopeVersion = useOrganizationScopeVersion();
  const { confirm, ConfirmDialogElement } = useConfirmDialog();
  const [pipelines, setPipelines] = React.useState([]);
  const [loadingPipelines, setLoadingPipelines] = React.useState(false);
  const [pipelineDialog, setPipelineDialog] = React.useState(null);
  const [pipelineForm, setPipelineForm] = React.useState({ name: "", isDefault: false });
  const [submittingPipeline, setSubmittingPipeline] = React.useState(false);
  const [expandedPipelineId, setExpandedPipelineId] = React.useState(null);
  const [stages, setStages] = React.useState({});
  const [loadingStages, setLoadingStages] = React.useState({});
  const [stageDialog, setStageDialog] = React.useState(null);
  const [stageForm, setStageForm] = React.useState({ label: "", color: null, icon: null });
  const [submittingStage, setSubmittingStage] = React.useState(false);
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: "customers-pipeline-settings",
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const pipelineMutationContext = React.useMemo(
    () => ({
      formId: "customers-pipeline-settings",
      resourceKind: "customers.pipeline",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const stageMutationContext = React.useMemo(
    () => ({
      formId: "customers-pipeline-settings",
      resourceKind: "customers.pipeline_stage",
      retryLastMutation
    }),
    [retryLastMutation]
  );
  const loadPipelines = React.useCallback(async () => {
    setLoadingPipelines(true);
    try {
      const data = await readApiResultOrThrow(
        "/api/customers/pipelines",
        void 0,
        { errorMessage: t("customers.pipelines.errors.loadFailed", "Failed to load pipelines"), fallback: { items: [] } }
      );
      const items = Array.isArray(data?.items) ? data.items : [];
      setPipelines(items.map((item) => normalizePipeline(item)));
    } finally {
      setLoadingPipelines(false);
    }
  }, [t]);
  const loadStages = React.useCallback(async (pipelineId) => {
    setLoadingStages((prev) => ({ ...prev, [pipelineId]: true }));
    try {
      const data = await readApiResultOrThrow(
        `/api/customers/pipeline-stages?pipelineId=${encodeURIComponent(pipelineId)}`,
        void 0,
        { errorMessage: t("customers.pipelines.errors.stagesLoadFailed", "Failed to load stages"), fallback: { items: [] } }
      );
      const items = Array.isArray(data?.items) ? data.items : [];
      setStages((prev) => ({
        ...prev,
        [pipelineId]: items.map((item) => normalizeStage(item))
      }));
    } finally {
      setLoadingStages((prev) => ({ ...prev, [pipelineId]: false }));
    }
  }, [t]);
  React.useEffect(() => {
    void loadPipelines();
  }, [loadPipelines, scopeVersion]);
  React.useEffect(() => {
    if (expandedPipelineId) {
      void loadStages(expandedPipelineId);
    }
  }, [expandedPipelineId, loadStages]);
  const openCreatePipeline = React.useCallback(() => {
    setPipelineForm({ name: "", isDefault: false });
    setPipelineDialog({ mode: "create" });
  }, []);
  const openEditPipeline = React.useCallback((pipeline) => {
    setPipelineForm({ name: pipeline.name, isDefault: pipeline.isDefault });
    setPipelineDialog({ mode: "edit", entry: pipeline });
  }, []);
  const closePipelineDialog = React.useCallback(() => {
    setPipelineDialog(null);
  }, []);
  const handlePipelineSubmit = React.useCallback(async () => {
    if (!pipelineForm.name.trim()) return;
    setSubmittingPipeline(true);
    try {
      if (pipelineDialog?.mode === "create") {
        await runMutation({
          operation: async () => {
            const res = await apiCall("/api/customers/pipelines", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ name: pipelineForm.name.trim(), isDefault: pipelineForm.isDefault })
            });
            if (!res.ok) {
              await raiseCrudError(res.response, t("customers.pipelines.errors.createFailed", "Failed to create pipeline"));
            }
          },
          context: pipelineMutationContext,
          mutationPayload: { action: "create", name: pipelineForm.name.trim(), isDefault: pipelineForm.isDefault }
        });
        flash(t("customers.pipelines.flash.created", "Pipeline created"), "success");
      } else if (pipelineDialog?.mode === "edit") {
        await runMutation({
          operation: async () => {
            const res = await withScopedApiRequestHeaders(
              buildOptimisticLockHeader(pipelineDialog.entry.updatedAt),
              () => apiCall("/api/customers/pipelines", {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ id: pipelineDialog.entry.id, name: pipelineForm.name.trim(), isDefault: pipelineForm.isDefault })
              })
            );
            if (!res.ok) {
              await raiseCrudError(res.response, t("customers.pipelines.errors.updateFailed", "Failed to update pipeline"));
            }
          },
          context: pipelineMutationContext,
          mutationPayload: { action: "update", id: pipelineDialog.entry.id, name: pipelineForm.name.trim(), isDefault: pipelineForm.isDefault }
        });
        flash(t("customers.pipelines.flash.updated", "Pipeline updated"), "success");
      }
      setPipelineDialog(null);
      await loadPipelines();
    } catch {
      return;
    } finally {
      setSubmittingPipeline(false);
    }
  }, [pipelineDialog, pipelineForm, loadPipelines, pipelineMutationContext, runMutation, t]);
  const handleDeletePipeline = React.useCallback(async (pipeline) => {
    const confirmed = await confirm({
      title: t("customers.pipelines.confirm.deleteTitle", "Delete pipeline"),
      text: t("customers.pipelines.confirm.deleteDesc", "Are you sure you want to delete this pipeline? This cannot be undone."),
      confirmText: t("customers.pipelines.confirm.deleteConfirm", "Delete"),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutation({
        operation: async () => {
          const res = await withScopedApiRequestHeaders(
            buildOptimisticLockHeader(pipeline.updatedAt),
            () => apiCall("/api/customers/pipelines", {
              method: "DELETE",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ id: pipeline.id })
            })
          );
          if (!res.ok) {
            const body = res.result ?? {};
            const msg = typeof body.error === "string" ? body.error : t("customers.pipelines.errors.deleteFailed", "Failed to delete pipeline");
            throw new Error(msg);
          }
        },
        context: pipelineMutationContext,
        mutationPayload: { action: "delete", id: pipeline.id }
      });
    } catch (err) {
      const msg = err instanceof Error && err.message ? err.message : t("customers.pipelines.errors.deleteFailed", "Failed to delete pipeline");
      flash(msg, "error");
      return;
    }
    flash(t("customers.pipelines.flash.deleted", "Pipeline deleted"), "success");
    if (expandedPipelineId === pipeline.id) setExpandedPipelineId(null);
    await loadPipelines();
  }, [confirm, expandedPipelineId, loadPipelines, pipelineMutationContext, runMutation, t]);
  const openCreateStage = React.useCallback((pipelineId) => {
    setStageForm({ label: "", color: null, icon: null });
    setStageDialog({ mode: "create", pipelineId });
  }, []);
  const openEditStage = React.useCallback((stage) => {
    setStageForm({ label: stage.label, color: stage.color, icon: stage.icon });
    setStageDialog({ mode: "edit", entry: stage });
  }, []);
  const closeStageDialog = React.useCallback(() => {
    setStageDialog(null);
  }, []);
  const handleStageSubmit = React.useCallback(async () => {
    if (!stageForm.label.trim()) return;
    setSubmittingStage(true);
    try {
      const appearance = {};
      if (stageForm.color) appearance.color = stageForm.color;
      if (stageForm.icon) appearance.icon = stageForm.icon;
      if (stageDialog?.mode === "create") {
        const targetPipelineId = stageDialog.pipelineId;
        await runMutation({
          operation: async () => {
            const res = await apiCall("/api/customers/pipeline-stages", {
              method: "POST",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ pipelineId: targetPipelineId, label: stageForm.label.trim(), ...appearance })
            });
            if (!res.ok) {
              await raiseCrudError(res.response, t("customers.pipelines.errors.stageCreateFailed", "Failed to create stage"));
            }
          },
          context: stageMutationContext,
          mutationPayload: { action: "create", pipelineId: targetPipelineId, label: stageForm.label.trim(), ...appearance }
        });
        flash(t("customers.pipelines.flash.stageCreated", "Stage created"), "success");
        await loadStages(targetPipelineId);
      } else if (stageDialog?.mode === "edit") {
        const targetStage = stageDialog.entry;
        await runMutation({
          operation: async () => {
            const res = await withScopedApiRequestHeaders(
              buildOptimisticLockHeader(targetStage.updatedAt),
              () => apiCall("/api/customers/pipeline-stages", {
                method: "PUT",
                headers: { "content-type": "application/json" },
                body: JSON.stringify({ id: targetStage.id, label: stageForm.label.trim(), ...appearance })
              })
            );
            if (!res.ok) {
              await raiseCrudError(res.response, t("customers.pipelines.errors.stageUpdateFailed", "Failed to update stage"));
            }
          },
          context: stageMutationContext,
          mutationPayload: { action: "update", id: targetStage.id, label: stageForm.label.trim(), ...appearance }
        });
        flash(t("customers.pipelines.flash.stageUpdated", "Stage updated"), "success");
        await loadStages(targetStage.pipelineId);
      }
      setStageDialog(null);
    } catch {
      return;
    } finally {
      setSubmittingStage(false);
    }
  }, [stageDialog, stageForm, loadStages, runMutation, stageMutationContext, t]);
  const handleDeleteStage = React.useCallback(async (stage) => {
    const confirmed = await confirm({
      title: t("customers.pipelines.confirm.stageDeleteTitle", "Delete stage"),
      text: t("customers.pipelines.confirm.stageDeleteDesc", "Are you sure you want to delete this stage?"),
      confirmText: t("customers.pipelines.confirm.stageDeleteConfirm", "Delete"),
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await runMutation({
        operation: async () => {
          const res = await withScopedApiRequestHeaders(
            buildOptimisticLockHeader(stage.updatedAt),
            () => apiCall("/api/customers/pipeline-stages", {
              method: "DELETE",
              headers: { "content-type": "application/json" },
              body: JSON.stringify({ id: stage.id })
            })
          );
          if (!res.ok) {
            const body = res.result ?? {};
            const msg = typeof body.error === "string" ? body.error : t("customers.pipelines.errors.stageDeleteFailed", "Failed to delete stage");
            throw new Error(msg);
          }
        },
        context: stageMutationContext,
        mutationPayload: { action: "delete", id: stage.id }
      });
    } catch (err) {
      const msg = err instanceof Error && err.message ? err.message : t("customers.pipelines.errors.stageDeleteFailed", "Failed to delete stage");
      flash(msg, "error");
      return;
    }
    flash(t("customers.pipelines.flash.stageDeleted", "Stage deleted"), "success");
    await loadStages(stage.pipelineId);
  }, [confirm, loadStages, runMutation, stageMutationContext, t]);
  const handleMoveStage = React.useCallback(async (stage, direction) => {
    const pipelineStages = stages[stage.pipelineId] ?? [];
    const idx = pipelineStages.findIndex((s) => s.id === stage.id);
    if (idx < 0) return;
    const swapIdx = direction === "up" ? idx - 1 : idx + 1;
    if (swapIdx < 0 || swapIdx >= pipelineStages.length) return;
    const reordered = [...pipelineStages];
    const temp = reordered[idx];
    reordered[idx] = reordered[swapIdx];
    reordered[swapIdx] = temp;
    const orderedStages = reordered.map((s, i) => ({ id: s.id, order: i }));
    try {
      await runMutation({
        operation: async () => {
          const res = await apiCall("/api/customers/pipeline-stages/reorder", {
            method: "POST",
            headers: { "content-type": "application/json" },
            body: JSON.stringify({ stages: orderedStages })
          });
          if (!res.ok) {
            throw new Error(t("customers.pipelines.errors.reorderFailed", "Failed to reorder stages"));
          }
        },
        context: stageMutationContext,
        mutationPayload: { action: "reorder", stages: orderedStages }
      });
    } catch (err) {
      const msg = err instanceof Error && err.message ? err.message : t("customers.pipelines.errors.reorderFailed", "Failed to reorder stages");
      flash(msg, "error");
      return;
    }
    await loadStages(stage.pipelineId);
  }, [stages, loadStages, runMutation, stageMutationContext, t]);
  const handleKeyDown = React.useCallback(
    (handler) => (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
        e.preventDefault();
        handler();
      }
    },
    []
  );
  const appearanceLabels = React.useMemo(() => ({
    colorLabel: t("customers.pipelines.stageForm.color", "Color"),
    colorClearLabel: t("customers.pipelines.stageForm.colorClear", "Remove color"),
    iconLabel: t("customers.pipelines.stageForm.icon", "Icon"),
    iconPlaceholder: t("customers.pipelines.stageForm.iconPlaceholder", "e.g. lucide:star"),
    iconPickerTriggerLabel: t("customers.pipelines.stageForm.iconPicker", "Pick icon"),
    iconSearchPlaceholder: t("customers.pipelines.stageForm.iconSearch", "Search icons\u2026"),
    iconSearchEmptyLabel: t("customers.pipelines.stageForm.iconSearchEmpty", "No icons found"),
    iconSuggestionsLabel: t("customers.pipelines.stageForm.iconSuggestions", "Suggestions"),
    iconClearLabel: t("customers.pipelines.stageForm.iconClear", "Remove icon"),
    previewEmptyLabel: t("customers.pipelines.stageForm.previewEmpty", "No appearance set")
  }), [t]);
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("h3", { className: "text-base font-semibold", children: t("customers.pipelines.title", "Sales Pipelines") }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customers.pipelines.description", "Manage sales pipelines and their stages.") })
      ] }),
      /* @__PURE__ */ jsx(Button, { size: "sm", onClick: openCreatePipeline, children: t("customers.pipelines.actions.create", "Add pipeline") })
    ] }),
    loadingPipelines ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx(Spinner, { className: "h-4 w-4" }),
      t("customers.pipelines.loading", "Loading pipelines\u2026")
    ] }) : pipelines.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customers.pipelines.empty", "No pipelines yet. Create one to get started.") }) : /* @__PURE__ */ jsx(
      Accordion,
      {
        type: "single",
        collapsible: true,
        value: expandedPipelineId ?? "",
        onValueChange: (next) => setExpandedPipelineId(next || null),
        className: "space-y-2",
        children: pipelines.map((pipeline) => {
          const pipelineStages = stages[pipeline.id] ?? [];
          const isLoadingStages = loadingStages[pipeline.id] ?? false;
          return /* @__PURE__ */ jsxs(AccordionItem, { value: pipeline.id, children: [
            /* @__PURE__ */ jsx(AccordionTrigger, { triggerIcon: "chevron", children: /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: pipeline.name }),
              pipeline.isDefault ? /* @__PURE__ */ jsx("span", { className: "rounded-full bg-primary/10 px-2 py-0.5 text-xs text-primary", children: t("customers.pipelines.defaultBadge", "Default") }) : null
            ] }) }),
            /* @__PURE__ */ jsxs(AccordionContent, { children: [
              /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center justify-between", children: [
                /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-muted-foreground uppercase tracking-wide", children: t("customers.pipelines.stages.title", "Stages") }),
                /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => openCreateStage(pipeline.id), children: t("customers.pipelines.stages.add", "Add stage") })
              ] }),
              isLoadingStages ? /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-sm text-muted-foreground", children: [
                /* @__PURE__ */ jsx(Spinner, { className: "h-3 w-3" }),
                t("customers.pipelines.stages.loading", "Loading\u2026")
              ] }) : pipelineStages.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("customers.pipelines.stages.empty", "No stages yet.") }) : /* @__PURE__ */ jsx("div", { className: "divide-y divide-border rounded-md border bg-background", children: pipelineStages.map((stage, idx) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 px-3 py-2", children: [
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsx("span", { className: "w-5 text-center text-xs text-muted-foreground", children: idx + 1 }),
                  stage.color ? renderDictionaryColor(stage.color, "h-3 w-3 rounded-full") : null,
                  stage.icon ? renderDictionaryIcon(stage.icon, "h-4 w-4") : null,
                  /* @__PURE__ */ jsx("span", { className: "text-sm", children: stage.label })
                ] }),
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "ghost",
                      size: "icon",
                      className: "h-7 w-7",
                      disabled: idx === 0,
                      onClick: () => void handleMoveStage(stage, "up"),
                      title: t("customers.pipelines.stages.moveUp", "Move up"),
                      children: "\u2191"
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "ghost",
                      size: "icon",
                      className: "h-7 w-7",
                      disabled: idx === pipelineStages.length - 1,
                      onClick: () => void handleMoveStage(stage, "down"),
                      title: t("customers.pipelines.stages.moveDown", "Move down"),
                      children: "\u2193"
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "ghost",
                      size: "sm",
                      onClick: () => openEditStage(stage),
                      children: t("customers.pipelines.stages.edit", "Edit")
                    }
                  ),
                  /* @__PURE__ */ jsx(
                    Button,
                    {
                      variant: "ghost",
                      size: "sm",
                      className: "text-destructive hover:text-destructive",
                      onClick: () => void handleDeleteStage(stage),
                      children: t("customers.pipelines.stages.delete", "Delete")
                    }
                  )
                ] })
              ] }, stage.id)) }),
              /* @__PURE__ */ jsxs("div", { className: "mt-4 flex items-center justify-end gap-2 border-t pt-3", children: [
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    onClick: () => openEditPipeline(pipeline),
                    children: t("customers.pipelines.actions.edit", "Edit pipeline")
                  }
                ),
                /* @__PURE__ */ jsx(
                  Button,
                  {
                    variant: "ghost",
                    size: "sm",
                    className: "text-destructive hover:text-destructive",
                    onClick: () => void handleDeletePipeline(pipeline),
                    children: t("customers.pipelines.actions.delete", "Delete pipeline")
                  }
                )
              ] })
            ] })
          ] }, pipeline.id);
        })
      }
    ),
    /* @__PURE__ */ jsx(Dialog, { open: pipelineDialog !== null, onOpenChange: (open) => {
      if (!open) closePipelineDialog();
    }, children: /* @__PURE__ */ jsxs(DialogContent, { onKeyDown: handleKeyDown(handlePipelineSubmit), children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: pipelineDialog?.mode === "create" ? t("customers.pipelines.dialog.createTitle", "Create pipeline") : t("customers.pipelines.dialog.editTitle", "Edit pipeline") }) }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4 py-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "pipeline-name", children: t("customers.pipelines.form.name", "Name") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "pipeline-name",
              value: pipelineForm.name,
              onChange: (e) => setPipelineForm((prev) => ({ ...prev, name: e.target.value })),
              placeholder: t("customers.pipelines.form.namePlaceholder", "e.g. New Business"),
              autoFocus: true
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(
            Checkbox,
            {
              id: "pipeline-default",
              checked: pipelineForm.isDefault,
              onCheckedChange: (checked) => setPipelineForm((prev) => ({ ...prev, isDefault: checked === true }))
            }
          ),
          /* @__PURE__ */ jsx(Label, { htmlFor: "pipeline-default", className: "cursor-pointer", children: t("customers.pipelines.form.isDefault", "Set as default pipeline") })
        ] })
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: closePipelineDialog, disabled: submittingPipeline, children: t("customers.pipelines.dialog.cancel", "Cancel") }),
        /* @__PURE__ */ jsxs(Button, { onClick: () => void handlePipelineSubmit(), disabled: submittingPipeline || !pipelineForm.name.trim(), children: [
          submittingPipeline ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : null,
          t("customers.pipelines.dialog.save", "Save")
        ] })
      ] })
    ] }) }),
    ConfirmDialogElement,
    /* @__PURE__ */ jsx(Dialog, { open: stageDialog !== null, onOpenChange: (open) => {
      if (!open) closeStageDialog();
    }, children: /* @__PURE__ */ jsxs(DialogContent, { onKeyDown: handleKeyDown(handleStageSubmit), children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: stageDialog?.mode === "create" ? t("customers.pipelines.stageDialog.createTitle", "Add stage") : t("customers.pipelines.stageDialog.editTitle", "Edit stage") }) }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-4 py-2", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsx(Label, { htmlFor: "stage-label", children: t("customers.pipelines.stageForm.label", "Label") }),
          /* @__PURE__ */ jsx(
            Input,
            {
              id: "stage-label",
              value: stageForm.label,
              onChange: (e) => setStageForm((prev) => ({ ...prev, label: e.target.value })),
              placeholder: t("customers.pipelines.stageForm.labelPlaceholder", "e.g. Discovery"),
              autoFocus: true
            }
          )
        ] }),
        /* @__PURE__ */ jsx(
          AppearanceSelector,
          {
            color: stageForm.color,
            icon: stageForm.icon,
            onColorChange: (next) => setStageForm((prev) => ({ ...prev, color: next })),
            onIconChange: (next) => setStageForm((prev) => ({ ...prev, icon: next })),
            labels: appearanceLabels
          }
        )
      ] }),
      /* @__PURE__ */ jsxs(DialogFooter, { children: [
        /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: closeStageDialog, disabled: submittingStage, children: t("customers.pipelines.stageDialog.cancel", "Cancel") }),
        /* @__PURE__ */ jsxs(Button, { onClick: () => void handleStageSubmit(), disabled: submittingStage || !stageForm.label.trim(), children: [
          submittingStage ? /* @__PURE__ */ jsx(Spinner, { className: "mr-2 h-4 w-4" }) : null,
          t("customers.pipelines.stageDialog.save", "Save")
        ] })
      ] })
    ] }) })
  ] });
}
export {
  PipelineSettings as default
};
//# sourceMappingURL=PipelineSettings.js.map
