"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import dynamic from "next/dynamic";
import { FileCode, Loader2, Mail, Pencil, Phone, X } from "lucide-react";
import { PhoneNumberField } from "@open-mercato/ui/backend/inputs/PhoneNumberField";
import { Button } from "@open-mercato/ui/primitives/button";
import { Textarea } from "@open-mercato/ui/primitives/textarea";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { cn } from "@open-mercato/shared/lib/utils";
import { LoadingMessage } from "./LoadingMessage.js";
import { mapCrudServerErrorToFormErrors } from "../utils/serverErrors.js";
import { MarkdownPreview } from "../markdown/index.js";
function resolveInlineErrorMessage(err, fallbackMessage) {
  const { message, fieldErrors } = mapCrudServerErrorToFormErrors(err);
  const firstFieldError = fieldErrors ? Object.values(fieldErrors).find((text) => typeof text === "string" && text.trim().length) : null;
  if (typeof firstFieldError === "string" && firstFieldError.trim().length) {
    return firstFieldError.trim();
  }
  if (typeof message === "string" && message.trim().length) {
    return message.trim();
  }
  if (err instanceof Error && typeof err.message === "string" && err.message.trim().length) {
    return err.message.trim();
  }
  if (typeof err === "string" && err.trim().length) {
    return err.trim();
  }
  return fallbackMessage;
}
const ALLOWED_INLINE_URL_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:", "mailto:", "tel:"]);
function resolveSafeInlineUrlHref(value) {
  const trimmed = value.trim();
  if (!trimmed.length) return null;
  try {
    const parsed = new URL(trimmed);
    return ALLOWED_INLINE_URL_PROTOCOLS.has(parsed.protocol) ? trimmed : null;
  } catch {
    return null;
  }
}
function InlineTextEditor({
  label,
  value,
  placeholder,
  emptyLabel,
  onSave,
  type = "text",
  inputType,
  validator,
  variant = "default",
  activateOnClick = false,
  containerClassName,
  triggerClassName,
  hideLabel = false,
  renderDisplay,
  onEditingChange,
  renderActions,
  saveLabel,
  onDraftChange,
  renderBelowInput
}) {
  const t = useT();
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(value ?? "");
  const [error, setError] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const computedSaveLabel = saveLabel ?? t("ui.detail.inline.saveShortcut", "Save \u2318\u23CE / Ctrl+Enter");
  const fallbackError = React.useMemo(
    () => t("ui.detail.inline.error", "Failed to save value."),
    [t]
  );
  const resolvedType = React.useMemo(() => {
    if (type && typeof type === "string") return type;
    if (inputType && typeof inputType === "string") {
      const normalized = inputType.toLowerCase();
      if (normalized === "email" || normalized === "tel" || normalized === "url") {
        return normalized;
      }
    }
    return "text";
  }, [inputType, type]);
  React.useEffect(() => {
    if (!editing) setDraft(value ?? "");
  }, [editing, value]);
  React.useEffect(() => {
    if (onDraftChange) onDraftChange(draft);
  }, [draft, onDraftChange]);
  const containerClasses = cn(
    "group overflow-hidden",
    variant === "muted" ? "relative rounded border bg-muted/20 p-3" : variant === "plain" ? "relative flex items-center gap-3 rounded-none border-0 p-0" : "rounded-lg border p-4",
    activateOnClick && !editing ? "cursor-pointer" : null,
    containerClassName ?? null
  );
  const readOnlyWrapperClasses = cn(
    "flex-1 min-w-0",
    activateOnClick && !editing ? "cursor-pointer" : null,
    variant === "plain" ? "flex items-center gap-2" : null
  );
  const triggerClasses = cn(
    "shrink-0 transition-opacity duration-150",
    editing ? "opacity-100" : "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100",
    variant === "muted" ? "h-8 w-8" : null,
    triggerClassName ?? null
  );
  const triggerSize = variant === "plain" ? "icon" : "sm";
  const setEditingSafe = React.useCallback(
    (next) => {
      setEditing(next);
      if (onEditingChange) onEditingChange(next);
    },
    [onEditingChange]
  );
  const handleActivate = React.useCallback(() => {
    if (!editing) setEditingSafe(true);
  }, [editing, setEditingSafe]);
  const handleInteractiveClick = React.useCallback(
    (event) => {
      if (!activateOnClick || editing) return;
      const target = event.target;
      const interactiveElement = target.closest('button, input, select, textarea, a, [role="link"]');
      if (interactiveElement) {
        if (interactiveElement.tagName.toLowerCase() === "a") {
          if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
            return;
          }
          event.preventDefault();
        } else {
          return;
        }
      }
      handleActivate();
    },
    [activateOnClick, editing, handleActivate]
  );
  const handleContainerKeyDown = React.useCallback(
    (event) => {
      if (!activateOnClick || editing) return;
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleActivate();
      }
    },
    [activateOnClick, editing, handleActivate]
  );
  const handleSave = React.useCallback(async () => {
    const trimmed = draft.trim();
    if (validator) {
      const validationError = validator(trimmed);
      if (validationError) {
        setError(validationError);
        return;
      }
    }
    setError(null);
    setSaving(true);
    try {
      await onSave(trimmed.length ? trimmed : null);
      setEditingSafe(false);
    } catch (err) {
      setError(resolveInlineErrorMessage(err, fallbackError));
    } finally {
      setSaving(false);
    }
  }, [draft, fallbackError, onSave, setEditingSafe, validator]);
  const interactiveProps = activateOnClick && !editing ? {
    role: "button",
    tabIndex: 0,
    onKeyDown: handleContainerKeyDown
  } : {};
  const displayContent = React.useMemo(() => {
    if (renderDisplay) {
      return renderDisplay({ value, emptyLabel, type: resolvedType });
    }
    const baseValue = value && typeof value === "string" ? value : "";
    const anchorClass = variant === "plain" ? "inline-flex max-w-full min-w-0 items-center gap-2 text-xl font-semibold leading-tight text-primary hover:text-primary/90 hover:underline" : "flex max-w-full min-w-0 items-center gap-2 text-sm text-primary hover:text-primary/90 hover:underline";
    const textClass = variant === "plain" ? "text-2xl font-semibold leading-tight" : "text-sm break-words";
    if (resolvedType === "email") {
      if (!baseValue.length) {
        return /* @__PURE__ */ jsx("p", { className: variant === "plain" ? "text-base text-muted-foreground" : "text-sm text-muted-foreground", children: emptyLabel });
      }
      return /* @__PURE__ */ jsxs("a", { className: anchorClass, href: `mailto:${baseValue}`, children: [
        /* @__PURE__ */ jsx(Mail, { "aria-hidden": true, className: variant === "plain" ? "h-5 w-5" : "h-4 w-4" }),
        /* @__PURE__ */ jsx("span", { className: "truncate min-w-0", children: baseValue })
      ] });
    }
    if (!baseValue.length) {
      return /* @__PURE__ */ jsx("p", { className: variant === "plain" ? "text-base text-muted-foreground" : "text-sm text-muted-foreground", children: emptyLabel });
    }
    if (resolvedType === "tel") {
      const sanitizedValue = baseValue.replace(/[^+\d]/g, "");
      const hrefValue = sanitizedValue.length ? sanitizedValue : baseValue;
      return /* @__PURE__ */ jsxs("a", { className: anchorClass, href: `tel:${hrefValue}`, children: [
        /* @__PURE__ */ jsx(Phone, { "aria-hidden": true, className: variant === "plain" ? "h-5 w-5" : "h-4 w-4" }),
        /* @__PURE__ */ jsx("span", { className: "truncate", children: baseValue })
      ] });
    }
    if (resolvedType === "url") {
      const safeHref = resolveSafeInlineUrlHref(baseValue);
      if (!safeHref) {
        return /* @__PURE__ */ jsx("p", { className: textClass, children: baseValue });
      }
      return /* @__PURE__ */ jsx("a", { className: textClass, href: safeHref, target: "_blank", rel: "noopener noreferrer", children: baseValue });
    }
    return /* @__PURE__ */ jsx("p", { className: textClass, children: baseValue });
  }, [emptyLabel, renderDisplay, resolvedType, value, variant]);
  const editingContainerClass = variant === "plain" ? "mt-0 w-full max-w-sm space-y-3" : "mt-2 space-y-3";
  return /* @__PURE__ */ jsx("div", { className: containerClasses, onClick: handleInteractiveClick, children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2 min-w-0", children: [
    /* @__PURE__ */ jsxs("div", { className: readOnlyWrapperClasses, ...interactiveProps, children: [
      hideLabel ? null : /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: label }),
      editing ? /* @__PURE__ */ jsxs(
        "form",
        {
          className: editingContainerClass,
          onSubmit: (event) => {
            event.preventDefault();
            if (!saving) void handleSave();
          },
          onKeyDown: (event) => {
            if (event.key === "Escape") {
              event.preventDefault();
              setEditingSafe(false);
              setError(null);
              return;
            }
            if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
              event.preventDefault();
              if (!saving) void handleSave();
            }
          },
          children: [
            resolvedType === "tel" ? /* @__PURE__ */ jsx(
              PhoneNumberField,
              {
                value: draft.length ? draft : void 0,
                onValueChange: (next) => {
                  if (error) setError(null);
                  setDraft(next ?? "");
                },
                placeholder,
                autoFocus: true,
                disabled: saving,
                minDigits: 7
              }
            ) : /* @__PURE__ */ jsx(
              "input",
              {
                className: "w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",
                value: draft,
                onChange: (event) => {
                  if (error) setError(null);
                  setDraft(event.target.value);
                },
                placeholder,
                type: inputType ?? resolvedType,
                autoFocus: true
              }
            ),
            error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error }) : null,
            renderBelowInput ? renderBelowInput({ draft, resolvedType, error, saving }) : null,
            /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsxs(Button, { type: "submit", size: "sm", disabled: saving, children: [
                saving ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-3.5 w-3.5 animate-spin" }) : null,
                computedSaveLabel
              ] }),
              /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => setEditingSafe(false), disabled: saving, children: t("ui.detail.inline.cancel", "Cancel") })
            ] })
          ]
        }
      ) : /* @__PURE__ */ jsx("div", { className: variant === "plain" ? "" : "mt-1", children: displayContent })
    ] }),
    renderActions ? /* @__PURE__ */ jsx("div", { className: "flex items-center gap-2", children: renderActions }) : null,
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "ghost",
        size: triggerSize,
        className: triggerClasses,
        onClick: (event) => {
          event.stopPropagation();
          const next = !editing;
          setEditingSafe(next);
        },
        children: editing ? /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
      }
    )
  ] }) });
}
const isTestEnv = typeof process !== "undefined" && process.env.NODE_ENV === "test";
function MarkdownEditorFallback() {
  const t = useT();
  return /* @__PURE__ */ jsx(LoadingMessage, { label: t("ui.detail.inline.editorLoading", "Loading editor\u2026"), className: "min-h-[200px] justify-center" });
}
const MarkdownEditorTestStub = ({ value, onChange }) => /* @__PURE__ */ jsx(
  Textarea,
  {
    "data-testid": "markdown-editor",
    rows: 8,
    value: value ?? "",
    onChange: (event) => onChange?.(event.target.value)
  }
);
const MarkdownEditorComponent = isTestEnv ? MarkdownEditorTestStub : dynamic(() => import("@uiw/react-md-editor"), {
  ssr: false,
  loading: () => /* @__PURE__ */ jsx(MarkdownEditorFallback, {})
});
let markdownPluginsPromise = null;
async function loadMarkdownPlugins() {
  if (isTestEnv) return [];
  if (!markdownPluginsPromise) {
    markdownPluginsPromise = import("remark-gfm").then((mod) => [mod.default ?? mod]).catch(() => []);
  }
  return markdownPluginsPromise;
}
function InlineMultilineEditor({
  label,
  value,
  placeholder,
  emptyLabel,
  onSave,
  validator,
  variant = "default",
  activateOnClick = true,
  containerClassName,
  triggerClassName,
  renderDisplay
}) {
  const t = useT();
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(value ?? "");
  const [error, setError] = React.useState(null);
  const [saving, setSaving] = React.useState(false);
  const [isMarkdownEnabled, setIsMarkdownEnabled] = React.useState(true);
  const textareaRef = React.useRef(null);
  const markdownEditorRef = React.useRef(null);
  const [markdownPlugins, setMarkdownPlugins] = React.useState([]);
  const fallbackError = React.useMemo(
    () => t("ui.detail.inline.error", "Failed to save value."),
    [t]
  );
  React.useEffect(() => {
    if (isTestEnv) return;
    let mounted = true;
    void loadMarkdownPlugins().then((plugins) => {
      if (!mounted) return;
      setMarkdownPlugins(plugins);
    });
    return () => {
      mounted = false;
    };
  }, []);
  const adjustTextareaSize = React.useCallback((element) => {
    if (!element) return;
    element.style.height = "auto";
    element.style.height = `${element.scrollHeight}px`;
  }, []);
  React.useEffect(() => {
    adjustTextareaSize(textareaRef.current);
  }, [adjustTextareaSize, draft, isMarkdownEnabled]);
  React.useEffect(() => {
    if (!editing) return;
    if (isMarkdownEnabled) {
      const element2 = markdownEditorRef.current?.querySelector("textarea");
      if (!element2) return;
      window.requestAnimationFrame(() => {
        element2.focus();
      });
      return;
    }
    const element = textareaRef.current;
    if (!element) return;
    window.requestAnimationFrame(() => {
      adjustTextareaSize(element);
      element.focus();
    });
  }, [adjustTextareaSize, editing, isMarkdownEnabled]);
  const handleMarkdownToggle = React.useCallback(() => {
    setIsMarkdownEnabled((prev) => !prev);
  }, []);
  React.useEffect(() => {
    if (!editing) {
      setDraft(value ?? "");
      setError(null);
    }
  }, [editing, value]);
  const handleActivate = React.useCallback(() => {
    if (!editing) setEditing(true);
  }, [editing]);
  const handleInteractiveClick = React.useCallback(
    (event) => {
      if (!activateOnClick || editing) return;
      const target = event.target;
      const interactiveElement = target.closest('button, input, select, textarea, a, [role="link"]');
      if (interactiveElement) {
        if (interactiveElement.tagName.toLowerCase() === "a") {
          if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
            return;
          }
          event.preventDefault();
        } else {
          return;
        }
      }
      handleActivate();
    },
    [activateOnClick, editing, handleActivate]
  );
  const handleContainerKeyDown = React.useCallback(
    (event) => {
      if (!activateOnClick || editing) return;
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        handleActivate();
      }
    },
    [activateOnClick, editing, handleActivate]
  );
  const adjustError = React.useCallback(
    (nextValue) => {
      if (!validator) return null;
      const trimmed = nextValue.trim();
      return validator(trimmed);
    },
    [validator]
  );
  const containerClasses = cn(
    "group rounded-lg border p-4",
    variant === "muted" ? "bg-muted/20" : null,
    activateOnClick && !editing ? "cursor-pointer" : null,
    containerClassName ?? null
  );
  const triggerClasses = cn(
    "transition-opacity duration-150",
    editing ? "opacity-100" : "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100",
    triggerClassName ?? null
  );
  const handleSave = React.useCallback(async () => {
    const trimmed = draft.trim();
    const validationError = adjustError(draft);
    if (validationError) {
      setError(validationError);
      return;
    }
    setSaving(true);
    try {
      await onSave(trimmed.length ? trimmed : null);
      setEditing(false);
    } catch (err) {
      setError(resolveInlineErrorMessage(err, fallbackError));
    } finally {
      setSaving(false);
    }
  }, [adjustError, draft, fallbackError, onSave]);
  return /* @__PURE__ */ jsx("div", { className: containerClasses, onClick: handleInteractiveClick, children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn("flex-1 min-w-0", activateOnClick && !editing ? "cursor-pointer" : null),
        ...activateOnClick && !editing ? { role: "button", tabIndex: 0, onKeyDown: handleContainerKeyDown } : {},
        children: [
          /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: label }),
          editing ? /* @__PURE__ */ jsxs(
            "form",
            {
              className: "mt-2 space-y-3",
              onSubmit: (event) => {
                event.preventDefault();
                if (!saving) void handleSave();
              },
              onKeyDown: (event) => {
                if (event.key === "Escape") {
                  event.preventDefault();
                  setEditing(false);
                  setError(null);
                  return;
                }
                if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
                  event.preventDefault();
                  if (!saving) void handleSave();
                }
              },
              children: [
                isMarkdownEnabled ? /* @__PURE__ */ jsx(
                  "div",
                  {
                    ref: markdownEditorRef,
                    className: cn(
                      "w-full rounded-md border border-muted-foreground/30 bg-background p-2",
                      saving ? "pointer-events-none opacity-75" : null
                    ),
                    children: /* @__PURE__ */ jsx("div", { "data-color-mode": "light", className: "w-full", children: /* @__PURE__ */ jsx(
                      MarkdownEditorComponent,
                      {
                        value: draft,
                        height: 220,
                        onChange: (nextValue) => {
                          if (error) setError(null);
                          setDraft(typeof nextValue === "string" ? nextValue : "");
                        },
                        previewOptions: { remarkPlugins: markdownPlugins }
                      }
                    ) })
                  }
                ) : /* @__PURE__ */ jsx(
                  Textarea,
                  {
                    ref: textareaRef,
                    rows: 3,
                    className: "w-full resize-none overflow-hidden rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",
                    placeholder,
                    value: draft,
                    onChange: (event) => {
                      if (error) setError(null);
                      setDraft(event.target.value);
                    },
                    onInput: (event) => adjustTextareaSize(event.currentTarget),
                    autoFocus: true,
                    disabled: saving
                  }
                ),
                error ? /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error }) : null,
                /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
                  /* @__PURE__ */ jsxs(Button, { type: "submit", size: "sm", disabled: saving, children: [
                    saving ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-3.5 w-3.5 animate-spin" }) : null,
                    t("ui.detail.inline.saveShortcut", "Save \u2318\u23CE / Ctrl+Enter")
                  ] }),
                  /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => setEditing(false), disabled: saving, children: t("ui.detail.inline.cancel", "Cancel") }),
                  /* @__PURE__ */ jsxs(
                    Button,
                    {
                      type: "button",
                      variant: "ghost",
                      size: "icon",
                      onClick: handleMarkdownToggle,
                      "aria-pressed": isMarkdownEnabled,
                      title: isMarkdownEnabled ? t("ui.detail.inline.markdownDisable", "Disable Markdown") : t("ui.detail.inline.markdownEnable", "Enable Markdown"),
                      "aria-label": isMarkdownEnabled ? t("ui.detail.inline.markdownDisable", "Disable Markdown") : t("ui.detail.inline.markdownEnable", "Enable Markdown"),
                      className: cn("h-8 w-8", isMarkdownEnabled ? "text-primary" : void 0),
                      disabled: saving,
                      children: [
                        /* @__PURE__ */ jsx(FileCode, { className: "h-4 w-4", "aria-hidden": true }),
                        /* @__PURE__ */ jsx("span", { className: "sr-only", children: isMarkdownEnabled ? t("ui.detail.inline.markdownDisable", "Disable Markdown") : t("ui.detail.inline.markdownEnable", "Enable Markdown") })
                      ]
                    }
                  )
                ] })
              ]
            }
          ) : /* @__PURE__ */ jsx(
            "div",
            {
              className: cn(
                "mt-1 text-sm break-words",
                renderDisplay ? null : "whitespace-pre-wrap",
                activateOnClick && !editing ? "cursor-pointer" : null
              ),
              children: renderDisplay ? renderDisplay({ value, emptyLabel }) : value && value.length ? /* @__PURE__ */ jsx(
                MarkdownPreview,
                {
                  remarkPlugins: markdownPlugins,
                  className: "prose prose-sm max-w-none text-foreground [&>*]:my-2 [&>*:last-child]:mb-0 [&_pre]:rounded-md [&_pre]:bg-muted [&_pre]:p-3 [&_code]:rounded [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5",
                  children: value
                }
              ) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: emptyLabel })
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "ghost",
        size: "sm",
        className: triggerClasses,
        onClick: (event) => {
          event.stopPropagation();
          setEditing((state) => !state);
        },
        children: editing ? /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
      }
    )
  ] }) });
}
function InlineSelectEditor({
  label,
  value,
  emptyLabel,
  options,
  onSave,
  variant = "default",
  activateOnClick = false,
  containerClassName,
  triggerClassName,
  hideLabel = false,
  renderEditor,
  renderDisplay
}) {
  const t = useT();
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState(value ?? "");
  const [saving, setSaving] = React.useState(false);
  React.useEffect(() => {
    if (!editing) setDraft(value ?? "");
  }, [editing, value]);
  const containerClasses = cn(
    "group",
    variant === "muted" ? "relative rounded border bg-muted/30 p-3" : variant === "plain" ? "relative flex flex-col gap-1 rounded-none border-0 p-0" : "rounded-lg border bg-card p-4",
    activateOnClick && !editing ? "cursor-pointer" : null,
    containerClassName ?? null
  );
  const triggerClasses = cn(
    "shrink-0 transition-opacity duration-150",
    editing ? "opacity-100" : "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100",
    variant === "muted" ? "h-8 w-8" : null,
    triggerClassName ?? null
  );
  const handleSave = React.useCallback(async () => {
    setSaving(true);
    try {
      await onSave(draft.length ? draft : null);
      setEditing(false);
    } catch (err) {
      const message = err instanceof Error ? err.message : t("ui.detail.inline.error", "Failed to save value.");
      console.error(message, err);
    } finally {
      setSaving(false);
    }
  }, [draft, onSave, t]);
  const selected = options.find((option) => option.value === value);
  const interactiveProps = activateOnClick && !editing ? {
    role: "button",
    tabIndex: 0,
    onClick: () => setEditing(true),
    onKeyDown: (event) => {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        setEditing(true);
      }
    }
  } : {};
  return /* @__PURE__ */ jsx("div", { className: containerClasses, children: /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-2", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0", ...interactiveProps, children: [
      hideLabel ? null : /* @__PURE__ */ jsx("p", { className: "text-xs uppercase tracking-wide text-muted-foreground", children: label }),
      editing ? /* @__PURE__ */ jsxs("div", { className: variant === "plain" ? "space-y-2 pt-1" : "mt-2 space-y-2", children: [
        renderEditor ? renderEditor({ value: draft, onChange: setDraft }) : /* @__PURE__ */ jsxs(
          "select",
          {
            className: "w-full rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring",
            value: draft,
            onChange: (event) => setDraft(event.target.value),
            children: [
              /* @__PURE__ */ jsx("option", { value: "", children: t("ui.detail.inline.select.placeholder", "Not set") }),
              options.map((option) => /* @__PURE__ */ jsx("option", { value: option.value, children: option.label }, option.value))
            ]
          }
        ),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", onClick: () => void handleSave(), disabled: saving, children: [
            saving ? /* @__PURE__ */ jsx(Loader2, { className: "mr-2 h-3.5 w-3.5 animate-spin" }) : null,
            t("ui.detail.inline.saveShortcut", "Save \u2318\u23CE / Ctrl+Enter")
          ] }),
          /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => setEditing(false), disabled: saving, children: t("ui.detail.inline.cancel", "Cancel") })
        ] })
      ] }) : /* @__PURE__ */ jsx("div", { className: variant === "plain" ? "flex items-center gap-2" : "mt-1 text-sm", children: renderDisplay ? renderDisplay({ value, emptyLabel }) : selected ? /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
        /* @__PURE__ */ jsx("p", { className: "font-medium leading-tight", children: selected.label }),
        selected.description ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: selected.description }) : null
      ] }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: emptyLabel }) })
    ] }),
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        variant: "ghost",
        size: variant === "plain" ? "icon" : "sm",
        className: triggerClasses,
        onClick: (event) => {
          event.stopPropagation();
          setEditing((state) => !state);
        },
        children: editing ? /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Pencil, { className: "h-4 w-4" })
      }
    )
  ] }) });
}
export {
  InlineMultilineEditor,
  InlineSelectEditor,
  InlineTextEditor,
  resolveSafeInlineUrlHref
};
//# sourceMappingURL=InlineEditors.js.map
