"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Button } from "../primitives/button.js";
import { IconButton } from "../primitives/icon-button.js";
import { Input } from "../primitives/input.js";
import { InlineInput } from "../primitives/inline-input.js";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "../primitives/select.js";
import { Plus, Trash2, ChevronRight, ChevronDown, Code, LayoutList } from "lucide-react";
function cn(...classes) {
  return classes.filter(Boolean).join(" ");
}
function getJsonType(value) {
  if (value === null) return "null";
  if (Array.isArray(value)) return "array";
  return typeof value;
}
function JsonBuilder({
  value,
  onChange,
  disabled,
  error
}) {
  const [mode, setMode] = React.useState("raw");
  const [rawString, setRawString] = React.useState(() => {
    if (value === null) return "{}";
    return typeof value === "object" ? JSON.stringify(value, null, 2) : String(value || "{}");
  });
  const [parseError, setParseError] = React.useState(null);
  React.useEffect(() => {
    if (value === null) {
      if (!disabled) {
        onChange({});
      }
      setRawString("{}");
      setParseError(null);
      return;
    }
    if (typeof value === "object") {
      setRawString(JSON.stringify(value, null, 2));
      setParseError(null);
    }
  }, [value, disabled, onChange]);
  const handleRawChange = (str) => {
    setRawString(str);
    try {
      if (str.trim() === "") {
        onChange({});
        setParseError(null);
      } else {
        const parsed = JSON.parse(str);
        onChange(parsed);
        setParseError(null);
      }
    } catch (e) {
      onChange(str);
      setParseError("Invalid JSON");
    }
  };
  const switchToBuilder = () => {
    try {
      if (typeof value === "string") {
        JSON.parse(value);
      }
      setMode("builder");
    } catch (e) {
      alert("Cannot switch to Builder mode: Invalid JSON");
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4 border rounded-md p-4 bg-card", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2 border-b pb-2 mb-2", children: [
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: cn(mode === "raw" && "bg-muted text-foreground"),
          onClick: () => setMode("raw"),
          children: [
            /* @__PURE__ */ jsx(Code, { className: "w-4 h-4" }),
            "Raw JSON"
          ]
        }
      ),
      /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "ghost",
          size: "sm",
          className: cn(mode === "builder" && "bg-muted text-foreground"),
          onClick: switchToBuilder,
          children: [
            /* @__PURE__ */ jsx(LayoutList, { className: "w-4 h-4" }),
            "Builder"
          ]
        }
      )
    ] }),
    mode === "raw" ? /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(
        "textarea",
        {
          value: rawString,
          onChange: (e) => handleRawChange(e.target.value),
          onBlur: () => {
            try {
              const parsed = JSON.parse(rawString);
              setRawString(JSON.stringify(parsed, null, 2));
            } catch {
            }
          },
          placeholder: '{"key": "value"}',
          className: "w-full rounded border px-3 py-2 min-h-[300px] text-sm font-mono focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
          disabled
        }
      ),
      parseError && /* @__PURE__ */ jsx("div", { className: "text-xs text-red-600", children: "Invalid JSON format" })
    ] }) : /* @__PURE__ */ jsx("div", { className: "min-h-[300px] text-sm overflow-x-auto", children: typeof value === "object" && value !== null ? /* @__PURE__ */ jsx(
      JsonNode,
      {
        data: value,
        onChange,
        readOnly: disabled,
        isRoot: true
      }
    ) : /* @__PURE__ */ jsx("div", { className: "text-muted-foreground italic p-4 text-center", children: "Value is not an object or array. Switch to Raw to edit." }) }),
    error && /* @__PURE__ */ jsx("div", { className: "text-xs text-red-600", children: error })
  ] });
}
function JsonNode({ data, onChange, onDelete, readOnly, label, isRoot }) {
  const type = getJsonType(data);
  const isContainer = type === "object" || type === "array";
  const [collapsed, setCollapsed] = React.useState(false);
  const handleTypeChange = (newType) => {
    let newVal = "";
    switch (newType) {
      case "string":
        newVal = "";
        break;
      case "number":
        newVal = 0;
        break;
      case "boolean":
        newVal = false;
        break;
      case "object":
        newVal = {};
        break;
      case "array":
        newVal = [];
        break;
      case "null":
        newVal = null;
        break;
    }
    onChange(newVal);
  };
  const handleAddKey = () => {
    if (type === "object") {
      const newKey = `newKey_${Object.keys(data).length}`;
      onChange({ ...data, [newKey]: "" });
    } else if (type === "array") {
      onChange([...data, ""]);
    }
  };
  const handleChildChange = (key, newVal) => {
    if (type === "object") {
      onChange({ ...data, [key]: newVal });
    } else if (type === "array") {
      const arr = [...data];
      arr[Number(key)] = newVal;
      onChange(arr);
    }
  };
  const handleKeyRename = (oldKey, newKey) => {
    if (oldKey === newKey) return;
    const keys = Object.keys(data);
    const newData = {};
    keys.forEach((k) => {
      if (k === oldKey) {
        newData[newKey] = data[k];
      } else {
        newData[k] = data[k];
      }
    });
    onChange(newData);
  };
  const handleChildDelete = (key) => {
    if (type === "object") {
      const newData = { ...data };
      delete newData[key];
      onChange(newData);
    } else if (type === "array") {
      onChange(data.filter((_, i) => i !== key));
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: cn("pl-0", !isRoot && "pl-4 border-l border-border ml-1"), children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-2 py-1 group", children: [
      isContainer && /* @__PURE__ */ jsx(IconButton, { type: "button", variant: "ghost", size: "xs", className: "mt-1 text-muted-foreground hover:text-foreground", onClick: () => setCollapsed(!collapsed), children: collapsed ? /* @__PURE__ */ jsx(ChevronRight, { className: "w-3 h-3" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "w-3 h-3" }) }),
      !isContainer && !isRoot && /* @__PURE__ */ jsx("div", { className: "w-3" }),
      " ",
      label !== void 0 && !isRoot && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1", children: [
        /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground font-mono", children: label }),
        /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs", children: ":" })
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex-1 flex gap-2 items-center flex-wrap", children: [
        !readOnly && /* @__PURE__ */ jsxs(
          Select,
          {
            value: type,
            onValueChange: (next) => handleTypeChange(next),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { size: "sm", className: "w-auto min-w-[6rem]", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "string", children: "String" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "number", children: "Number" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "boolean", children: "Boolean" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "object", children: "Object" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "array", children: "Array" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "null", children: "Null" })
              ] })
            ]
          }
        ),
        type === "string" && /* @__PURE__ */ jsx(
          Input,
          {
            size: "sm",
            className: "flex-1 min-w-0 sm:min-w-[120px]",
            value: data,
            onChange: (e) => onChange(e.target.value),
            disabled: readOnly
          }
        ),
        type === "number" && /* @__PURE__ */ jsx(
          Input,
          {
            type: "number",
            size: "sm",
            className: "flex-1 w-full sm:w-[100px]",
            value: data,
            onChange: (e) => onChange(parseFloat(e.target.value) || 0),
            disabled: readOnly
          }
        ),
        type === "boolean" && /* @__PURE__ */ jsxs(
          Select,
          {
            value: String(data),
            onValueChange: (next) => onChange(next === "true"),
            disabled: readOnly,
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { size: "sm", className: "flex-1 w-full sm:w-[100px]", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
              /* @__PURE__ */ jsxs(SelectContent, { children: [
                /* @__PURE__ */ jsx(SelectItem, { value: "true", children: "true" }),
                /* @__PURE__ */ jsx(SelectItem, { value: "false", children: "false" })
              ] })
            ]
          }
        ),
        type === "null" && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "null" }),
        isContainer && /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: type === "object" ? `{ ${Object.keys(data).length} items }` : `[ ${data.length} items ]` }),
        onDelete && !readOnly && /* @__PURE__ */ jsx(
          IconButton,
          {
            type: "button",
            variant: "ghost",
            size: "xs",
            className: "text-muted-foreground hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity",
            title: "Remove item",
            onClick: onDelete,
            children: /* @__PURE__ */ jsx(Trash2, { className: "w-3.5 h-3.5" })
          }
        )
      ] })
    ] }),
    isContainer && !collapsed && /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 w-full pl-2", children: [
      type === "object" && Object.entries(data).map(([key, val], idx) => /* @__PURE__ */ jsxs("div", { className: "flex", children: [
        /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsx(
          InlineInput,
          {
            className: "w-full sm:w-[100px]",
            inputClassName: "text-right text-xs font-mono pr-1",
            value: key,
            onChange: (e) => handleKeyRename(key, e.target.value),
            disabled: readOnly
          }
        ) }),
        /* @__PURE__ */ jsx("div", { className: "flex-1", children: /* @__PURE__ */ jsx(
          JsonNode,
          {
            data: val,
            onChange: (v) => handleChildChange(key, v),
            onDelete: () => handleChildDelete(key),
            readOnly
          }
        ) })
      ] }, idx)),
      type === "array" && data.map((val, idx) => /* @__PURE__ */ jsx(
        JsonNode,
        {
          label: String(idx),
          data: val,
          onChange: (v) => handleChildChange(idx, v),
          onDelete: () => handleChildDelete(idx),
          readOnly
        },
        idx
      )),
      !readOnly && /* @__PURE__ */ jsx("div", { className: "pl-4 mt-1", children: /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: handleAddKey,
          className: "h-6 text-xs",
          children: [
            /* @__PURE__ */ jsx(Plus, { className: "w-3 h-3 mr-1" }),
            "Add ",
            type === "object" ? "Property" : "Item"
          ]
        }
      ) })
    ] })
  ] });
}
export {
  JsonBuilder
};
//# sourceMappingURL=JsonBuilder.js.map
