"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { ChevronDown, ChevronRight, Plus, Trash2 } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { createLocalId } from "./productForm.js";
const toEntries = (value) => {
  if (!value || typeof value !== "object") return [];
  return Object.entries(value).map(([key, entry]) => ({
    id: `${key}-${createLocalId()}`,
    key,
    value: serializeMetadataValue(entry)
  }));
};
const serializeMetadataValue = (value) => {
  if (value == null) return "";
  if (typeof value === "string") return value;
  if (typeof value === "number" || typeof value === "boolean") return String(value);
  try {
    return JSON.stringify(value);
  } catch {
    return String(value);
  }
};
const parseMetadataValue = (raw) => {
  const trimmed = raw.trim();
  if (!trimmed.length) return "";
  if (trimmed === "true") return true;
  if (trimmed === "false") return false;
  const numeric = Number(trimmed);
  if (!Number.isNaN(numeric) && trimmed === `${numeric}`) return numeric;
  if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) {
    try {
      return JSON.parse(trimmed);
    } catch {
      return trimmed;
    }
  }
  return trimmed;
};
function MetadataEditor({
  value,
  onChange,
  defaultCollapsed = true,
  title,
  description,
  embedded = false
}) {
  const t = useT();
  const [collapsed, setCollapsed] = React.useState(defaultCollapsed);
  const [entries, setEntries] = React.useState(() => toEntries(value));
  const skipSyncRef = React.useRef(false);
  React.useEffect(() => {
    if (skipSyncRef.current) {
      skipSyncRef.current = false;
      return;
    }
    setEntries(toEntries(value));
  }, [value]);
  const emitChange = React.useCallback(
    (nextEntries) => {
      skipSyncRef.current = true;
      setEntries(nextEntries);
      const next = {};
      nextEntries.forEach(({ key, value: value2 }) => {
        const normalizedKey = key.trim();
        if (!normalizedKey.length) return;
        next[normalizedKey] = parseMetadataValue(value2);
      });
      onChange(next);
    },
    [onChange]
  );
  const updateEntry = React.useCallback(
    (id, field, nextValue) => {
      const next = entries.map((entry) => entry.id === id ? { ...entry, [field]: nextValue } : entry);
      emitChange(next);
    },
    [emitChange, entries]
  );
  const addEntry = React.useCallback(() => {
    const next = [...entries, { id: createLocalId(), key: "", value: "" }];
    emitChange(next);
    setCollapsed(false);
  }, [emitChange, entries]);
  const removeEntry = React.useCallback(
    (id) => {
      emitChange(entries.filter((entry) => entry.id !== id));
    },
    [emitChange, entries]
  );
  const resolvedTitle = title ?? t("catalog.products.edit.metadata.title", "Metadata");
  const resolvedDescription = description ?? t("catalog.products.edit.metadata.hint", "Attach structured key/value pairs for integrations.");
  const hasTitle = typeof resolvedTitle === "string" && resolvedTitle.trim().length > 0;
  const hasDescription = typeof resolvedDescription === "string" && resolvedDescription.trim().length > 0;
  const content = /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
        hasTitle ? /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: resolvedTitle }) : null,
        hasDescription ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: resolvedDescription }) : null
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            onClick: () => setCollapsed((prev) => !prev),
            className: "gap-2 text-xs",
            children: [
              collapsed ? /* @__PURE__ */ jsx(ChevronRight, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "h-4 w-4" }),
              collapsed ? t("catalog.products.edit.metadata.expand", "Show metadata") : t("catalog.products.edit.metadata.collapse", "Hide metadata")
            ]
          }
        ),
        /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", variant: "outline", onClick: addEntry, children: [
          /* @__PURE__ */ jsx(Plus, { className: "mr-1 h-4 w-4" }),
          t("catalog.products.edit.metadata.add", "Add entry")
        ] })
      ] })
    ] }),
    !collapsed ? /* @__PURE__ */ jsxs("div", { className: "mt-3 space-y-3", children: [
      entries.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("catalog.products.edit.metadata.empty", "No metadata. Add your first entry.") }) : null,
      entries.map((entry) => /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-2 rounded-md bg-muted/50 p-3 sm:flex-row sm:items-center", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col gap-2 sm:flex-row", children: [
          /* @__PURE__ */ jsx(
            Input,
            {
              value: entry.key,
              placeholder: t("catalog.products.edit.metadata.keyPlaceholder", "Key"),
              onChange: (event) => updateEntry(entry.id, "key", event.target.value),
              className: "sm:flex-1"
            }
          ),
          /* @__PURE__ */ jsx(
            Input,
            {
              value: entry.value,
              placeholder: t("catalog.products.edit.metadata.valuePlaceholder", "Value"),
              onChange: (event) => updateEntry(entry.id, "value", event.target.value),
              className: "sm:flex-1"
            }
          )
        ] }),
        /* @__PURE__ */ jsxs(Button, { type: "button", variant: "ghost", size: "icon", onClick: () => removeEntry(entry.id), children: [
          /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4 text-muted-foreground hover:text-destructive" }),
          /* @__PURE__ */ jsx("span", { className: "sr-only", children: t("catalog.products.edit.metadata.remove", "Remove entry") })
        ] })
      ] }, entry.id))
    ] }) : null
  ] });
  if (embedded) {
    return /* @__PURE__ */ jsx("div", { className: "space-y-3", children: content });
  }
  return /* @__PURE__ */ jsx("div", { className: "rounded-lg border p-4", children: content });
}
export {
  MetadataEditor
};
//# sourceMappingURL=MetadataEditor.js.map
