"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const button = require('../../button.cjs');
const input = require('../../input.cjs');
const label = require('../../label.cjs');
const select = require('../../select.cjs');
const card = require('../../card.cjs');
const LucideIcons = require('lucide-react');
const layerStore = require('../../../lib/ui-builder/store/layer-store.cjs');
const utils = require('../../../lib/utils.cjs');
const editorStore = require('../../../lib/ui-builder/store/editor-store.cjs');

const EMPTY_OBJECT = {};
const VariablesPanel = ({
  className
}) => {
  const { variables, addVariable, updateVariable, removeVariable } = layerStore.useLayerStore();
  const [isAdding, setIsAdding] = React.useState(false);
  const [editingId, setEditingId] = React.useState(null);
  const incrementRevision = editorStore.useEditorStore((state) => state.incrementRevision);
  const allowVariableEditing = editorStore.useEditorStore((state) => state.allowVariableEditing);
  const functionRegistry = editorStore.useEditorStore((state) => state.functionRegistry);
  const handleAddVariable = React.useCallback(
    (name, type, defaultValue) => {
      addVariable(name, type, defaultValue);
      incrementRevision();
    },
    [addVariable, incrementRevision]
  );
  const handleSetIsAdding = React.useCallback(() => {
    setIsAdding(true);
  }, []);
  const handleSetIsNotAdding = React.useCallback(() => {
    setIsAdding(false);
  }, []);
  const handleOnSave = React.useCallback(
    (id, updates) => {
      updateVariable(id, updates);
      setEditingId(null);
    },
    [updateVariable]
  );
  const handleOnCancel = React.useCallback(() => {
    setEditingId(null);
  }, []);
  const handleOnDelete = React.useCallback(
    (id) => {
      removeVariable(id);
      incrementRevision();
    },
    [removeVariable, incrementRevision]
  );
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: utils.cn("flex flex-col gap-4 p-4", className), children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
      /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-lg font-semibold", children: "Variables" }),
      allowVariableEditing && /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { size: "sm", onClick: handleSetIsAdding, disabled: isAdding, children: [
        /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Plus, { className: "h-4 w-4 mr-2" }),
        "Add Variable"
      ] })
    ] }),
    isAdding && allowVariableEditing && /* @__PURE__ */ jsxRuntime.jsx(
      AddVariableForm,
      {
        onSave: handleAddVariable,
        onCancel: handleSetIsNotAdding,
        functionRegistry
      }
    ),
    /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: variables.map((variable) => /* @__PURE__ */ jsxRuntime.jsx(
      VariableCard,
      {
        variable,
        isEditing: editingId === variable.id,
        onEdit: setEditingId,
        onSave: handleOnSave,
        onCancel: handleOnCancel,
        onDelete: handleOnDelete,
        editVariables: allowVariableEditing,
        functionRegistry
      },
      variable.id
    )) }),
    variables.length === 0 && !isAdding && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-center text-muted-foreground py-8", children: allowVariableEditing ? 'No variables defined. Click "Add Variable" to create one.' : "No variables defined." })
  ] });
};
const AddVariableForm = ({
  onSave,
  onCancel,
  functionRegistry
}) => {
  const [name, setName] = React.useState("");
  const [type, setType] = React.useState("string");
  const [defaultValue, setDefaultValue] = React.useState("");
  const [errors, setErrors] = React.useState(EMPTY_OBJECT);
  const functionOptions = React.useMemo(() => {
    if (!functionRegistry) return [];
    return Object.entries(functionRegistry).map(([id, def]) => ({
      id,
      name: def.name,
      description: def.description
    }));
  }, [functionRegistry]);
  const hasFunctions = functionOptions.length > 0;
  const validateForm = React.useCallback(() => {
    const newErrors = {};
    if (!name.trim()) {
      newErrors.name = "Name is required";
    }
    if (type === "function") {
      if (!defaultValue) {
        newErrors.defaultValue = "Please select a function";
      }
    } else if (!defaultValue.trim()) {
      newErrors.defaultValue = "Preview value is required";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [name, defaultValue, type]);
  const handleSave = React.useCallback(() => {
    if (!validateForm()) return;
    let parsedValue = defaultValue;
    try {
      if (type === "number") {
        parsedValue = parseFloat(defaultValue) || 0;
      } else if (type === "boolean") {
        parsedValue = defaultValue.toLowerCase() === "true";
      }
    } catch (e) {
      console.warn("Error parsing variable value, keeping as string", e);
    }
    onSave(name, type, parsedValue);
  }, [name, type, defaultValue, onSave, validateForm]);
  const handleNameChange = React.useCallback(
    (e) => {
      setName(e.target.value);
      if (errors.name) setErrors((prev) => ({ ...prev, name: void 0 }));
    },
    [errors.name]
  );
  const handleTypeChange = React.useCallback(
    (value) => {
      setType(value);
      setDefaultValue("");
    },
    []
  );
  const handleDefaultValueChange = React.useCallback(
    (e) => {
      setDefaultValue(e.target.value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  const handleFunctionSelect = React.useCallback(
    (value) => {
      setDefaultValue(value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  return /* @__PURE__ */ jsxRuntime.jsxs(card.Card, { children: [
    /* @__PURE__ */ jsxRuntime.jsx(card.CardHeader, { className: "pb-3", children: /* @__PURE__ */ jsxRuntime.jsx(card.CardTitle, { className: "text-sm", children: "Add New Variable" }) }),
    /* @__PURE__ */ jsxRuntime.jsxs(card.CardContent, { className: "space-y-3", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { htmlFor: "var-name", children: [
          "Name ",
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: "var-name",
            value: name,
            onChange: handleNameChange,
            placeholder: "variableName",
            className: errors.name ? "border-red-500" : ""
          }
        ),
        errors.name && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.name })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "var-type", children: "Type" }),
        /* @__PURE__ */ jsxRuntime.jsxs(select.Select, { value: type, onValueChange: handleTypeChange, children: [
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, {}) }),
          /* @__PURE__ */ jsxRuntime.jsxs(select.SelectContent, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "string", children: "String" }),
            /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "number", children: "Number" }),
            /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "boolean", children: "Boolean" }),
            hasFunctions && /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "function", children: "Function" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { children: type === "function" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { htmlFor: "var-function", children: [
          "Function ",
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs(select.Select, { value: defaultValue, onValueChange: handleFunctionSelect, children: [
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { className: errors.defaultValue ? "border-red-500" : "", children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, { placeholder: "Select a function..." }) }),
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectContent, { children: functionOptions.map((fn) => /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: fn.id, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col", children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { children: fn.name }),
            fn.description && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: fn.description })
          ] }) }, fn.id)) })
        ] }),
        errors.defaultValue && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { htmlFor: "var-default", children: [
          "Preview Value ",
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: "var-default",
            value: defaultValue,
            onChange: handleDefaultValueChange,
            placeholder: getPlaceholderForType(type),
            className: errors.defaultValue ? "border-red-500" : ""
          }
        ),
        errors.defaultValue && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { size: "sm", onClick: handleSave, children: [
          /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Check, { className: "h-4 w-4 mr-2" }),
          "Save"
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { size: "sm", variant: "outline", onClick: onCancel, children: [
          /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.X, { className: "h-4 w-4 mr-2" }),
          "Cancel"
        ] })
      ] })
    ] })
  ] });
};
const VariableCard = ({
  variable,
  isEditing,
  onEdit,
  onSave,
  onCancel,
  onDelete,
  editVariables,
  functionRegistry
}) => {
  const [name, setName] = React.useState(variable.name);
  const [type, setType] = React.useState(variable.type);
  const [defaultValue, setDefaultValue] = React.useState(
    String(variable.defaultValue)
  );
  const [errors, setErrors] = React.useState(EMPTY_OBJECT);
  const functionOptions = React.useMemo(() => {
    if (!functionRegistry) return [];
    return Object.entries(functionRegistry).map(([id, def]) => ({
      id,
      name: def.name,
      description: def.description
    }));
  }, [functionRegistry]);
  const hasFunctions = functionOptions.length > 0;
  const getFunctionDisplayName = React.useCallback((funcId) => {
    if (!functionRegistry) return funcId;
    const fn = functionRegistry[funcId];
    return fn ? fn.name : funcId;
  }, [functionRegistry]);
  const validateForm = React.useCallback(() => {
    const newErrors = {};
    if (!name.trim()) {
      newErrors.name = "Name is required";
    }
    if (type === "function") {
      if (!defaultValue) {
        newErrors.defaultValue = "Please select a function";
      }
    } else if (!defaultValue.trim()) {
      newErrors.defaultValue = "Preview value is required";
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  }, [name, defaultValue, type]);
  const handleSave = React.useCallback(() => {
    if (!validateForm()) return;
    let parsedValue = defaultValue;
    try {
      if (type === "number") {
        parsedValue = parseFloat(defaultValue) || 0;
      } else if (type === "boolean") {
        parsedValue = defaultValue.toLowerCase() === "true";
      }
    } catch (e) {
      console.warn("Error parsing variable value, keeping as string", e);
    }
    onSave(variable.id, { name, type, defaultValue: parsedValue });
  }, [name, type, defaultValue, onSave, validateForm, variable.id]);
  const handleNameChange = React.useCallback(
    (e) => {
      setName(e.target.value);
      if (errors.name) setErrors((prev) => ({ ...prev, name: void 0 }));
    },
    [errors.name]
  );
  const handleTypeChange = React.useCallback(
    (value) => {
      setType(value);
      setDefaultValue("");
    },
    []
  );
  const handleDefaultValueChange = React.useCallback(
    (e) => {
      setDefaultValue(e.target.value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  const handleFunctionSelect = React.useCallback(
    (value) => {
      setDefaultValue(value);
      if (errors.defaultValue)
        setErrors((prev) => ({ ...prev, defaultValue: void 0 }));
    },
    [errors.defaultValue]
  );
  const handleOnEdit = React.useCallback(() => {
    onEdit(variable.id);
  }, [onEdit, variable.id]);
  const handleOnDelete = React.useCallback(() => {
    onDelete(variable.id);
  }, [onDelete, variable.id]);
  if (isEditing) {
    return /* @__PURE__ */ jsxRuntime.jsx(card.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(card.CardContent, { className: "pt-4 space-y-3", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { htmlFor: `edit-name-${variable.id}`, children: [
          "Name ",
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: `edit-name-${variable.id}`,
            value: name,
            onChange: handleNameChange,
            className: errors.name ? "border-red-500" : ""
          }
        ),
        errors.name && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.name })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: `edit-type-${variable.id}`, children: "Type" }),
        /* @__PURE__ */ jsxRuntime.jsxs(select.Select, { value: type, onValueChange: handleTypeChange, children: [
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, {}) }),
          /* @__PURE__ */ jsxRuntime.jsxs(select.SelectContent, { children: [
            /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "string", children: "String" }),
            /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "number", children: "Number" }),
            /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "boolean", children: "Boolean" }),
            hasFunctions && /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: "function", children: "Function" })
          ] })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { children: type === "function" ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { htmlFor: `edit-function-${variable.id}`, children: [
          "Function ",
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs(select.Select, { value: defaultValue, onValueChange: handleFunctionSelect, children: [
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { className: errors.defaultValue ? "border-red-500" : "", children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, { placeholder: "Select a function..." }) }),
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectContent, { children: functionOptions.map((fn) => /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: fn.id, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col", children: [
            /* @__PURE__ */ jsxRuntime.jsx("span", { children: fn.name }),
            fn.description && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: fn.description })
          ] }) }, fn.id)) })
        ] }),
        errors.defaultValue && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
        /* @__PURE__ */ jsxRuntime.jsxs(label.Label, { htmlFor: `edit-default-${variable.id}`, children: [
          "Preview Value ",
          /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-red-500", children: "*" })
        ] }),
        /* @__PURE__ */ jsxRuntime.jsx(
          input.Input,
          {
            id: `edit-default-${variable.id}`,
            value: defaultValue,
            onChange: handleDefaultValueChange,
            placeholder: getPlaceholderForType(type),
            className: errors.defaultValue ? "border-red-500" : ""
          }
        ),
        errors.defaultValue && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-red-500 mt-1", children: errors.defaultValue })
      ] }) }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { size: "sm", onClick: handleSave, children: [
          /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Check, { className: "h-4 w-4 mr-2" }),
          "Save"
        ] }),
        /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { size: "sm", variant: "outline", onClick: onCancel, children: [
          /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.X, { className: "h-4 w-4 mr-2" }),
          "Cancel"
        ] })
      ] })
    ] }) });
  }
  return /* @__PURE__ */ jsxRuntime.jsx(card.Card, { children: /* @__PURE__ */ jsxRuntime.jsx(card.CardContent, { className: "pt-4", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: variable.name }),
        /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs bg-muted px-2 py-1 rounded", children: variable.type })
      ] }),
      /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-sm text-muted-foreground mt-1", children: variable.type === "function" ? getFunctionDisplayName(String(variable.defaultValue)) : String(variable.defaultValue) })
    ] }),
    editVariables && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1", children: [
      /* @__PURE__ */ jsxRuntime.jsx(button.Button, { size: "sm", variant: "ghost", onClick: handleOnEdit, children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Edit2, { className: "h-4 w-4" }) }),
      /* @__PURE__ */ jsxRuntime.jsx(button.Button, { size: "sm", variant: "ghost", onClick: handleOnDelete, children: /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Trash2, { className: "h-4 w-4" }) })
    ] })
  ] }) }) });
};
function getPlaceholderForType(type) {
  switch (type) {
    case "string":
      return "Enter text...";
    case "number":
      return "0";
    case "boolean":
      return "true";
    case "function":
      return "Select a function...";
    default:
      return "";
  }
}

exports.VariablesPanel = VariablesPanel;
