import { jsxs, jsx, Fragment } from "react/jsx-runtime";
import { forwardRef, createElement, useMemo, useState, useReducer, useRef, useEffect } from "react";
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
const toCamelCase = (string) => string.replace(
  /^([A-Z])|[\s-_]+(\w)/g,
  (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()
);
const toPascalCase = (string) => {
  const camelCase = toCamelCase(string);
  return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
};
const mergeClasses = (...classes) => classes.filter((className, index, array) => {
  return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
}).join(" ").trim();
const hasA11yProp = (props) => {
  for (const prop in props) {
    if (prop.startsWith("aria-") || prop === "role" || prop === "title") {
      return true;
    }
  }
};
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
var defaultAttributes = {
  xmlns: "http://www.w3.org/2000/svg",
  width: 24,
  height: 24,
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 2,
  strokeLinecap: "round",
  strokeLinejoin: "round"
};
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const Icon = forwardRef(
  ({
    color = "currentColor",
    size = 24,
    strokeWidth = 2,
    absoluteStrokeWidth,
    className = "",
    children,
    iconNode,
    ...rest
  }, ref) => createElement(
    "svg",
    {
      ref,
      ...defaultAttributes,
      width: size,
      height: size,
      stroke: color,
      strokeWidth: absoluteStrokeWidth ? Number(strokeWidth) * 24 / Number(size) : strokeWidth,
      className: mergeClasses("lucide", className),
      ...!children && !hasA11yProp(rest) && { "aria-hidden": "true" },
      ...rest
    },
    [
      ...iconNode.map(([tag, attrs]) => createElement(tag, attrs)),
      ...Array.isArray(children) ? children : [children]
    ]
  )
);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const createLucideIcon = (iconName, iconNode) => {
  const Component = forwardRef(
    ({ className, ...props }, ref) => createElement(Icon, {
      ref,
      iconNode,
      className: mergeClasses(
        `lucide-${toKebabCase(toPascalCase(iconName))}`,
        `lucide-${iconName}`,
        className
      ),
      ...props
    })
  );
  Component.displayName = toPascalCase(iconName);
  return Component;
};
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$d = [
  ["path", { d: "M8 2v4", key: "1cmpym" }],
  ["path", { d: "M16 2v4", key: "4m81vk" }],
  ["rect", { width: "18", height: "18", x: "3", y: "4", rx: "2", key: "1hopcy" }],
  ["path", { d: "M3 10h18", key: "8toen8" }]
];
const Calendar = createLucideIcon("calendar", __iconNode$d);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$c = [["path", { d: "m6 9 6 6 6-6", key: "qrunsl" }]];
const ChevronDown = createLucideIcon("chevron-down", __iconNode$c);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$b = [["path", { d: "m9 18 6-6-6-6", key: "mthhwq" }]];
const ChevronRight = createLucideIcon("chevron-right", __iconNode$b);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$a = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "m9 12 2 2 4-4", key: "dzmm74" }]
];
const CircleCheck = createLucideIcon("circle-check", __iconNode$a);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$9 = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "m15 9-6 6", key: "1uzhvr" }],
  ["path", { d: "m9 9 6 6", key: "z0biqf" }]
];
const CircleX = createLucideIcon("circle-x", __iconNode$9);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$8 = [
  [
    "path",
    {
      d: "M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",
      key: "1jaruq"
    }
  ]
];
const Flag = createLucideIcon("flag", __iconNode$8);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$7 = [
  ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
  ["path", { d: "M12 16v-4", key: "1dtifu" }],
  ["path", { d: "M12 8h.01", key: "e9boi3" }]
];
const Info = createLucideIcon("info", __iconNode$7);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$6 = [
  ["rect", { width: "18", height: "11", x: "3", y: "11", rx: "2", ry: "2", key: "1w4ew1" }],
  ["path", { d: "M7 11V7a5 5 0 0 1 10 0v4", key: "fwvmzm" }]
];
const Lock = createLucideIcon("lock", __iconNode$6);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$5 = [
  ["path", { d: "M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8", key: "1357e3" }],
  ["path", { d: "M3 3v5h5", key: "1xhq8a" }]
];
const RotateCcw = createLucideIcon("rotate-ccw", __iconNode$5);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$4 = [
  [
    "path",
    {
      d: "M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",
      key: "1c8476"
    }
  ],
  ["path", { d: "M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7", key: "1ydtos" }],
  ["path", { d: "M7 3v4a1 1 0 0 0 1 1h7", key: "t51u73" }]
];
const Save = createLucideIcon("save", __iconNode$4);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$3 = [
  [
    "path",
    {
      d: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
      key: "oel41y"
    }
  ],
  ["path", { d: "M12 8v4", key: "1got3b" }],
  ["path", { d: "M12 16h.01", key: "1drbdi" }]
];
const ShieldAlert = createLucideIcon("shield-alert", __iconNode$3);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$2 = [
  [
    "path",
    {
      d: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
      key: "oel41y"
    }
  ],
  ["path", { d: "m9 12 2 2 4-4", key: "dzmm74" }]
];
const ShieldCheck = createLucideIcon("shield-check", __iconNode$2);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode$1 = [
  [
    "path",
    {
      d: "m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",
      key: "wmoenq"
    }
  ],
  ["path", { d: "M12 9v4", key: "juzpu7" }],
  ["path", { d: "M12 17h.01", key: "p32p05" }]
];
const TriangleAlert = createLucideIcon("triangle-alert", __iconNode$1);
/**
 * @license lucide-react v0.556.0 - ISC
 *
 * This source code is licensed under the ISC license.
 * See the LICENSE file in the root directory of this source tree.
 */
const __iconNode = [
  ["path", { d: "M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2", key: "975kel" }],
  ["circle", { cx: "12", cy: "7", r: "4", key: "17ys0d" }]
];
const User = createLucideIcon("user", __iconNode);
function getNestedValue(obj, path) {
  return path.split(".").reduce(
    (current, key) => current !== void 0 && current !== null ? current[key] : void 0,
    obj
  );
}
function setNestedValue(obj, path, value) {
  const keys = path.split(".");
  const result = { ...obj };
  let current = result;
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    current[key] = { ...current[key] };
    current = current[key];
  }
  current[keys[keys.length - 1]] = value;
  return result;
}
const useValidation = (formData, rules) => {
  return useMemo(() => {
    const errors = {};
    rules.forEach((rule) => {
      const value = getNestedValue(formData, rule.field);
      if (rule.type === "required" && (value === void 0 || value === "" || value === null)) {
        errors[rule.field] = rule.message;
      }
      if (value !== void 0 && value !== null && value !== "") {
        if (rule.type === "regex" && rule.value instanceof RegExp && !rule.value.test(String(value))) {
          errors[rule.field] = rule.message;
        }
        if (rule.type === "min" && Number(value) < rule.value) {
          errors[rule.field] = rule.message;
        }
        if (rule.type === "max" && Number(value) > rule.value) {
          errors[rule.field] = rule.message;
        }
      }
    });
    return errors;
  }, [formData, rules]);
};
const FieldWrapper = ({
  label,
  error,
  isOverridden,
  onToggleOverride,
  readOnly,
  hint,
  children,
  showIcon = true,
  warningMode = false
}) => {
  const showAsWarning = warningMode || isOverridden;
  return /* @__PURE__ */ jsxs("div", { className: "mb-6 group", children: [
    /* @__PURE__ */ jsx("label", { className: "block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5", children: label }),
    /* @__PURE__ */ jsxs("div", { className: "relative", children: [
      children,
      showIcon && error && !showAsWarning && /* @__PURE__ */ jsx(TriangleAlert, { className: `absolute right-3 top-2.5 h-5 w-5 ${readOnly ? "text-red-400" : "text-red-500"}` }),
      showIcon && error && showAsWarning && (warningMode && !isOverridden ? /* @__PURE__ */ jsx(Info, { className: `absolute right-3 top-2.5 h-5 w-5 ${readOnly ? "text-amber-500" : "text-amber-600"}` }) : /* @__PURE__ */ jsx(ShieldAlert, { className: `absolute right-3 top-2.5 h-5 w-5 ${readOnly ? "text-amber-500" : "text-amber-600"}` }))
    ] }),
    error && /* @__PURE__ */ jsxs("div", { className: "mt-2 flex items-start justify-between", children: [
      /* @__PURE__ */ jsxs("div", { className: `text-sm flex items-center ${showAsWarning ? "text-amber-700" : "text-red-600"}`, children: [
        /* @__PURE__ */ jsx("span", { className: "mr-1.5", children: warningMode && !isOverridden ? "Value may be invalid:" : isOverridden ? "Manually Overridden:" : "●" }),
        error
      ] }),
      !readOnly && !warningMode && onToggleOverride && /* @__PURE__ */ jsx(
        "button",
        {
          onClick: onToggleOverride,
          className: `text-xs font-medium px-2 py-1 rounded-md transition-colors flex items-center space-x-1 border shadow-sm ${isOverridden ? "bg-white text-slate-600 border-slate-300 hover:bg-slate-50" : "bg-white text-red-600 border-red-200 hover:bg-red-50"}`,
          children: isOverridden ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(RotateCcw, { className: "w-3 h-3" }),
            /* @__PURE__ */ jsx("span", { children: "Undo" })
          ] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(ShieldCheck, { className: "w-3 h-3" }),
            /* @__PURE__ */ jsx("span", { children: "Accept Anyway" })
          ] })
        }
      )
    ] }),
    hint && !error && /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-slate-400", children: hint })
  ] });
};
const FieldGroup = ({
  field,
  children,
  hasErrors = false,
  hasOverrides = false
}) => {
  const [isCollapsed, setIsCollapsed] = useState(field.defaultCollapsed ?? false);
  const isCollapsible = field.collapsible !== false;
  const getBorderClass = () => {
    if (hasErrors && !hasOverrides) return "border-red-200 bg-red-50/30";
    if (hasErrors && hasOverrides) return "border-amber-200 bg-amber-50/30";
    return "border-slate-200 bg-slate-50/30";
  };
  const handleToggle = () => {
    if (isCollapsible) {
      setIsCollapsed(!isCollapsed);
    }
  };
  const handleKeyDown = (e) => {
    if (e.key === "Enter" || e.key === " ") {
      e.preventDefault();
      handleToggle();
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: `mb-4 rounded-lg border ${getBorderClass()}`, children: [
    /* @__PURE__ */ jsxs(
      "div",
      {
        className: `flex items-center justify-between px-4 py-3 ${isCollapsible ? "cursor-pointer hover:bg-slate-100/50" : ""} transition-colors rounded-t-lg border-b border-slate-200`,
        ...isCollapsible ? {
          role: "button",
          tabIndex: 0,
          "aria-expanded": !isCollapsed,
          onClick: handleToggle,
          onKeyDown: handleKeyDown
        } : {},
        children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center space-x-2", children: [
            isCollapsible && (isCollapsed ? /* @__PURE__ */ jsx(ChevronRight, { className: "w-4 h-4 text-slate-400" }) : /* @__PURE__ */ jsx(ChevronDown, { className: "w-4 h-4 text-slate-400" })),
            /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold text-slate-700 uppercase tracking-wide", children: field.label }),
            hasErrors && /* @__PURE__ */ jsx("span", { className: `text-xs px-2 py-0.5 rounded-full ${hasOverrides ? "bg-amber-100 text-amber-700" : "bg-red-100 text-red-700"}`, children: hasOverrides ? "Overridden" : "Has Errors" })
          ] }),
          field.hint && /* @__PURE__ */ jsx("span", { className: "text-xs text-slate-400", children: field.hint })
        ]
      }
    ),
    !isCollapsed && /* @__PURE__ */ jsx("div", { className: "p-4 pl-6", children })
  ] });
};
const getInputStyles = (readOnly, hasError, isOverridden) => {
  let borderColor = "border-slate-300";
  let bgColor = readOnly ? "bg-slate-100" : "bg-white";
  let focusStyles = "focus:border-teal-500 focus:ring-1 focus:ring-teal-500/20";
  let textColor = readOnly ? "text-slate-500" : "text-slate-900";
  if (hasError) {
    if (isOverridden) {
      borderColor = "border-amber-400";
      bgColor = readOnly ? "bg-amber-50/50" : "bg-amber-50";
      focusStyles = "focus:border-amber-500 focus:ring-1 focus:ring-amber-500/20";
    } else {
      borderColor = "border-red-300";
      bgColor = readOnly ? "bg-red-50/50" : "bg-red-50";
      focusStyles = "focus:border-red-500 focus:ring-1 focus:ring-red-500/20";
    }
  } else if (readOnly) {
    borderColor = "border-slate-200";
  }
  const baseStyles = "w-full px-3 py-2 border rounded-lg shadow-sm text-sm transition-all placeholder-slate-400";
  const stateStyles = readOnly ? "cursor-not-allowed" : `focus:outline-none ${focusStyles}`;
  return `${baseStyles} ${borderColor} ${bgColor} ${textColor} ${stateStyles}`;
};
const StringInput = ({
  value,
  onChange,
  readOnly,
  placeholder,
  hasError,
  isOverridden,
  type = "text"
}) => {
  return /* @__PURE__ */ jsx(
    "input",
    {
      type,
      value: value ?? "",
      onChange: (e) => onChange(e.target.value),
      disabled: readOnly,
      className: getInputStyles(readOnly, hasError, isOverridden),
      placeholder
    }
  );
};
const NumberInput = ({
  value,
  onChange,
  readOnly,
  placeholder,
  hasError,
  isOverridden
}) => {
  return /* @__PURE__ */ jsx(
    "input",
    {
      type: "number",
      value: value ?? "",
      onChange: (e) => onChange(Number(e.target.value)),
      disabled: readOnly,
      className: getInputStyles(readOnly, hasError, isOverridden),
      placeholder
    }
  );
};
const BooleanInput = ({
  value,
  onChange,
  readOnly
}) => {
  return /* @__PURE__ */ jsxs("div", { className: `flex items-center space-x-2 ${readOnly ? "opacity-70" : ""}`, children: [
    /* @__PURE__ */ jsx(
      "button",
      {
        onClick: () => !readOnly && onChange(!value),
        disabled: readOnly,
        className: `relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${value ? "bg-teal-600" : "bg-slate-200"} ${readOnly ? "cursor-not-allowed" : "cursor-pointer"}`,
        children: /* @__PURE__ */ jsx(
          "span",
          {
            className: `inline-block h-4 w-4 transform rounded-full bg-white transition-transform shadow-sm ${value ? "translate-x-6" : "translate-x-1"}`
          }
        )
      }
    ),
    /* @__PURE__ */ jsx("span", { className: "text-sm text-slate-600 font-medium", children: value ? "Yes" : "No" })
  ] });
};
const DateInput = ({
  value,
  onChange,
  readOnly,
  placeholder,
  hasError,
  isOverridden
}) => {
  return /* @__PURE__ */ jsx(
    "input",
    {
      type: "date",
      value: value ?? "",
      onChange: (e) => onChange(e.target.value),
      disabled: readOnly,
      className: getInputStyles(readOnly, hasError, isOverridden),
      placeholder
    }
  );
};
const SchemaFieldInput = ({
  field,
  value,
  onChange,
  readOnly,
  placeholder,
  hasError,
  isOverridden
}) => {
  const commonProps = { value, onChange, readOnly, placeholder, hasError, isOverridden };
  switch (field.type) {
    case "number":
      return /* @__PURE__ */ jsx(NumberInput, { ...commonProps });
    case "boolean":
      return /* @__PURE__ */ jsx(BooleanInput, { ...commonProps });
    case "date":
      return /* @__PURE__ */ jsx(DateInput, { ...commonProps });
    case "email":
      return /* @__PURE__ */ jsx(StringInput, { ...commonProps, type: "email" });
    case "string":
    default:
      return /* @__PURE__ */ jsx(StringInput, { ...commonProps });
  }
};
function getAllChildPaths(fields, parentPath) {
  const paths = [];
  for (const field of fields) {
    const fieldPath = `${parentPath}.${field.key}`;
    if (field.type === "object" && field.children) {
      paths.push(...getAllChildPaths(field.children, fieldPath));
    } else {
      paths.push(fieldPath);
    }
  }
  return paths;
}
const SchemaField = ({
  field,
  path,
  value,
  onChange,
  errors,
  overrides,
  onToggleOverride,
  readOnly,
  warningMode
}) => {
  if (field.type === "object" && field.children) {
    const childPaths = getAllChildPaths(field.children, path);
    const hasErrors = childPaths.some((p) => errors[p]);
    const hasOverrides = warningMode || childPaths.some((p) => overrides.has(p));
    return /* @__PURE__ */ jsx(
      FieldGroup,
      {
        field,
        hasErrors,
        hasOverrides,
        children: field.children.map((childField) => {
          const childPath = `${path}.${childField.key}`;
          const childValue = value == null ? void 0 : value[childField.key];
          return /* @__PURE__ */ jsx(
            SchemaField,
            {
              field: childField,
              path: childPath,
              value: childValue,
              onChange,
              errors,
              overrides,
              onToggleOverride,
              readOnly,
              warningMode
            },
            childField.key
          );
        })
      }
    );
  }
  const error = errors[path];
  const isOverridden = overrides.has(path);
  return /* @__PURE__ */ jsx(
    FieldWrapper,
    {
      label: field.label,
      error,
      isOverridden,
      onToggleOverride: () => onToggleOverride(path),
      readOnly,
      hint: field.hint,
      showIcon: field.type !== "boolean",
      warningMode,
      children: /* @__PURE__ */ jsx(
        SchemaFieldInput,
        {
          field,
          value,
          onChange: (val) => onChange(path, val),
          readOnly,
          placeholder: field.placeholder,
          hasError: !!error,
          isOverridden: warningMode || isOverridden
        }
      )
    }
  );
};
function editorReducer(state, action) {
  switch (action.type) {
    case "RESET":
      return {
        formData: action.payload,
        overrides: /* @__PURE__ */ new Set(),
        rejectReason: "",
        importComment: "",
        isRejectMode: false
      };
    case "UPDATE_FIELD":
      return { ...state, formData: setNestedValue(state.formData, action.path, action.value) };
    case "TOGGLE_OVERRIDE": {
      const next = new Set(state.overrides);
      if (next.has(action.key)) {
        next.delete(action.key);
      } else {
        next.add(action.key);
      }
      return { ...state, overrides: next };
    }
    case "SET_REJECT_REASON":
      return { ...state, rejectReason: action.payload };
    case "SET_IMPORT_COMMENT":
      return { ...state, importComment: action.payload };
    case "SET_REJECT_MODE":
      return { ...state, isRejectMode: action.payload };
    default:
      return state;
  }
}
function getFieldLeafPaths(field, parentPath = field.key) {
  var _a;
  if (field.type === "object" && ((_a = field.children) == null ? void 0 : _a.length)) {
    return field.children.flatMap((child) => getFieldLeafPaths(child, `${parentPath}.${child.key}`));
  }
  return [parentPath];
}
const ResolutionEditor = ({
  record,
  schema,
  rules,
  onSave,
  onReject,
  readOnly = false,
  displayName,
  hideFooter = false,
  mode = "resolve"
}) => {
  const isEditMode = mode === "edit";
  const [state, dispatch] = useReducer(editorReducer, {
    formData: record.data,
    overrides: /* @__PURE__ */ new Set(),
    rejectReason: "",
    importComment: "",
    isRejectMode: false
  });
  const { formData, overrides, rejectReason, importComment, isRejectMode } = state;
  const textareaRef = useRef(null);
  useEffect(() => {
    dispatch({ type: "RESET", payload: record.data });
  }, [record]);
  const clientErrors = useValidation(formData, rules);
  const validationErrors = useMemo(() => {
    var _a;
    const merged = { ...clientErrors };
    const serverFieldErrors = record.fieldErrors;
    if (serverFieldErrors) {
      for (const [field, message] of Object.entries(serverFieldErrors)) {
        if (!merged[field]) {
          const originalValue = ((_a = record.originalData) == null ? void 0 : _a[field]) ?? record.data[field];
          if (formData[field] === originalValue) {
            merged[field] = message;
          }
        }
      }
    }
    return merged;
  }, [clientErrors, record, formData]);
  const activeErrors = Object.keys(validationErrors).filter((key) => !overrides.has(key));
  const hasActiveErrors = activeErrors.length > 0;
  const errorCount = Object.keys(validationErrors).length;
  const groupedSchema = useMemo(() => {
    const invalidFields = [];
    const validFields = [];
    schema.forEach((field) => {
      const hasUnresolvedError = getFieldLeafPaths(field).some((path) => validationErrors[path] && !overrides.has(path));
      if (hasUnresolvedError) {
        invalidFields.push(field);
      } else {
        validFields.push(field);
      }
    });
    return { invalidFields, validFields };
  }, [schema, validationErrors, overrides]);
  const handleFieldChange = (path, value) => {
    if (readOnly) return;
    dispatch({ type: "UPDATE_FIELD", path, value });
  };
  const toggleOverride = (key) => {
    if (readOnly) return;
    dispatch({ type: "TOGGLE_OVERRIDE", key });
  };
  const handleSaveClick = () => {
    if (readOnly) return;
    onSave(record.id, formData, importComment);
  };
  const handleRejectClick = () => {
    if (readOnly) return;
    dispatch({ type: "SET_REJECT_MODE", payload: true });
    requestAnimationFrame(() => {
      var _a;
      return (_a = textareaRef.current) == null ? void 0 : _a.focus();
    });
  };
  const confirmReject = () => {
    if (!rejectReason.trim()) return;
    onReject == null ? void 0 : onReject(record.id, rejectReason);
  };
  const renderStatusBadge = () => {
    if (record.status === "imported") {
      return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-teal-50 text-teal-700 border border-teal-200", children: [
        /* @__PURE__ */ jsx(CircleCheck, { className: "w-3.5 h-3.5 mr-1.5" }),
        "Imported"
      ] });
    }
    if (record.status === "rejected") {
      return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-50 text-red-700 border border-red-200", children: [
        /* @__PURE__ */ jsx(CircleX, { className: "w-3.5 h-3.5 mr-1.5" }),
        "Rejected"
      ] });
    }
    if (isEditMode) {
      if (errorCount > 0) {
        return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-amber-50 text-amber-700 border border-amber-200", children: [
          /* @__PURE__ */ jsx(Info, { className: "w-3.5 h-3.5 mr-1.5" }),
          errorCount,
          " Warning",
          errorCount !== 1 ? "s" : ""
        ] });
      }
      return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-emerald-50 text-emerald-700 border border-emerald-200", children: [
        /* @__PURE__ */ jsx(CircleCheck, { className: "w-3.5 h-3.5 mr-1.5" }),
        "Valid"
      ] });
    }
    if (!readOnly && !hasActiveErrors) {
      return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-emerald-50 text-emerald-700 border border-emerald-200", children: [
        /* @__PURE__ */ jsx(CircleCheck, { className: "w-3.5 h-3.5 mr-1.5" }),
        "Ready to Import"
      ] });
    }
    if (!readOnly) {
      return /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-amber-50 text-amber-700 border border-amber-200", children: [
        /* @__PURE__ */ jsx(Flag, { className: "w-3.5 h-3.5 mr-1.5" }),
        "Needs Attention"
      ] });
    }
    return null;
  };
  const renderEditFooter = () => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
    /* @__PURE__ */ jsx("div", { className: "flex items-center text-sm", children: errorCount > 0 ? /* @__PURE__ */ jsxs("span", { className: "text-amber-700 font-medium flex items-center", children: [
      /* @__PURE__ */ jsx(Info, { className: "w-4 h-4 mr-2" }),
      errorCount,
      " field",
      errorCount !== 1 ? "s" : "",
      " may need attention"
    ] }) : /* @__PURE__ */ jsxs("span", { className: "text-emerald-700 font-medium flex items-center", children: [
      /* @__PURE__ */ jsx(CircleCheck, { className: "w-4 h-4 mr-2" }),
      "All fields valid"
    ] }) }),
    /* @__PURE__ */ jsxs(
      "button",
      {
        onClick: handleSaveClick,
        className: "flex items-center px-6 py-2 bg-teal-600 hover:bg-teal-700 text-white rounded-lg font-medium shadow-sm shadow-teal-600/20 transition-colors focus:ring-2 focus:ring-offset-2 focus:ring-teal-500 text-sm",
        children: [
          /* @__PURE__ */ jsx(Save, { className: "w-4 h-4 mr-2" }),
          "Save"
        ]
      }
    )
  ] });
  const renderResolveFooter = () => {
    if (readOnly) {
      return /* @__PURE__ */ jsxs("div", { className: "flex flex-col space-y-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-start", children: [
          /* @__PURE__ */ jsx("div", { className: `p-2 rounded-full mr-3 shrink-0 ${record.status === "imported" ? "bg-teal-100" : "bg-red-100"}`, children: record.status === "imported" ? /* @__PURE__ */ jsx(CircleCheck, { className: "w-5 h-5 text-teal-600" }) : /* @__PURE__ */ jsx(CircleX, { className: "w-5 h-5 text-red-600" }) }),
          /* @__PURE__ */ jsxs("div", { className: "flex-1", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-sm font-bold text-slate-900", children: record.status === "imported" ? "Record Imported" : "Record Rejected" }),
            /* @__PURE__ */ jsxs("div", { className: "text-xs text-slate-500 mt-1 flex items-center flex-wrap gap-1", children: [
              record.resolvedBy === "System" || !record.resolvedBy ? /* @__PURE__ */ jsx("span", { className: "bg-slate-200 px-1.5 py-0.5 rounded text-slate-700 font-medium text-[10px] uppercase tracking-wide", children: "Auto-processed" }) : /* @__PURE__ */ jsxs("span", { className: "flex items-center", children: [
                /* @__PURE__ */ jsx(User, { className: "w-3 h-3 mr-1" }),
                "Action by ",
                /* @__PURE__ */ jsx("span", { className: "font-medium text-slate-700 ml-1", children: record.resolvedBy })
              ] }),
              record.resolutionDate && /* @__PURE__ */ jsxs("span", { className: "flex items-center text-slate-400 ml-2 border-l border-slate-300 pl-2", children: [
                /* @__PURE__ */ jsx(Calendar, { className: "w-3 h-3 mr-1" }),
                /* @__PURE__ */ jsx("span", { className: "font-mono", children: new Date(record.resolutionDate).toLocaleString() })
              ] })
            ] })
          ] })
        ] }),
        record.resolutionNote ? /* @__PURE__ */ jsxs("div", { className: "ml-12 bg-white border border-slate-200 rounded-lg p-3 text-sm text-slate-600 shadow-sm relative", children: [
          /* @__PURE__ */ jsx("div", { className: "absolute top-0 left-4 -mt-1.5 w-3 h-3 bg-white border-t border-l border-slate-200 transform rotate-45" }),
          /* @__PURE__ */ jsx("span", { className: "font-bold text-[10px] text-slate-400 uppercase tracking-wider block mb-1", children: record.status === "imported" ? "Import Note" : "Rejection Reason" }),
          record.resolutionNote
        ] }) : record.status === "imported" && (record.resolvedBy === "System" || !record.resolvedBy) ? /* @__PURE__ */ jsx("div", { className: "ml-12 text-xs text-slate-400 italic", children: "This record passed all validation checks and was automatically imported." }) : null
      ] });
    }
    if (hasActiveErrors) {
      return /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs("div", { className: "flex items-center text-red-700 font-medium text-sm", children: [
          /* @__PURE__ */ jsx(CircleX, { className: "w-5 h-5 mr-2" }),
          activeErrors.length,
          " Unresolved Issue",
          activeErrors.length !== 1 && "s"
        ] }),
        /* @__PURE__ */ jsx(
          "button",
          {
            onClick: handleRejectClick,
            className: "px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg font-medium shadow-sm transition-colors focus:ring-2 focus:ring-offset-2 focus:ring-red-500 text-sm",
            children: "Reject Record"
          }
        )
      ] });
    }
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsx("label", { htmlFor: "import-comment", className: "block text-xs font-bold text-slate-500 uppercase tracking-wider mb-1.5", children: "Audit Note / Import Comment" }),
        /* @__PURE__ */ jsx(
          "input",
          {
            id: "import-comment",
            type: "text",
            value: importComment,
            onChange: (e) => dispatch({ type: "SET_IMPORT_COMMENT", payload: e.target.value }),
            placeholder: "Optional comment for the audit log...",
            className: "w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-1 focus:ring-teal-500 focus:border-teal-500 bg-white text-sm"
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
        /* @__PURE__ */ jsxs("span", { className: "text-emerald-700 font-medium text-sm flex items-center", children: [
          /* @__PURE__ */ jsx(CircleCheck, { className: "w-4 h-4 mr-2" }),
          "All validations passed ",
          overrides.size > 0 && `(${overrides.size} overridden)`
        ] }),
        /* @__PURE__ */ jsxs(
          "button",
          {
            onClick: handleSaveClick,
            className: "flex items-center px-6 py-2 bg-teal-600 hover:bg-teal-700 text-white rounded-lg font-medium shadow-sm shadow-teal-600/20 transition-colors focus:ring-2 focus:ring-offset-2 focus:ring-teal-500 text-sm",
            children: [
              /* @__PURE__ */ jsx(Save, { className: "w-4 h-4 mr-2" }),
              "Save & Import"
            ]
          }
        )
      ] })
    ] });
  };
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col h-full bg-white rounded-xl shadow-sm border border-slate-200 overflow-hidden", children: [
    /* @__PURE__ */ jsxs("div", { className: "px-6 py-4 border-b border-slate-100 flex justify-between items-center bg-slate-50/50", children: [
      /* @__PURE__ */ jsxs("div", { children: [
        /* @__PURE__ */ jsxs("h2", { className: "text-lg font-bold text-slate-800 flex items-center gap-2", children: [
          displayName || "Record",
          " ",
          /* @__PURE__ */ jsxs("span", { className: "font-mono text-slate-500 text-sm", children: [
            "#",
            record.id
          ] }),
          readOnly && /* @__PURE__ */ jsx(Lock, { className: "w-4 h-4 text-slate-400" })
        ] }),
        /* @__PURE__ */ jsxs("p", { className: "text-xs text-slate-400 mt-1 font-mono", children: [
          "Imported on ",
          record.importDate
        ] })
      ] }),
      /* @__PURE__ */ jsx("div", { children: renderStatusBadge() })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "flex-1 overflow-y-auto p-6 relative bg-white", children: [
      readOnly && /* @__PURE__ */ jsx("div", { className: "absolute top-0 left-0 right-0 z-10 pointer-events-none h-4 bg-gradient-to-b from-white to-transparent" }),
      /* @__PURE__ */ jsxs("div", { className: "max-w-2xl mx-auto", children: [
        groupedSchema.invalidFields.length > 0 && /* @__PURE__ */ jsxs("div", { className: "mb-8", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-xs font-bold uppercase tracking-wider text-red-700", children: "Invalid fields" }),
            /* @__PURE__ */ jsx("span", { className: "text-[11px] font-medium text-red-600 bg-red-50 border border-red-100 rounded-full px-2 py-0.5", children: groupedSchema.invalidFields.length })
          ] }),
          groupedSchema.invalidFields.map((field) => /* @__PURE__ */ jsx(
            SchemaField,
            {
              field,
              path: field.key,
              value: formData[field.key],
              onChange: handleFieldChange,
              errors: validationErrors,
              overrides,
              onToggleOverride: toggleOverride,
              readOnly,
              warningMode: isEditMode
            },
            field.key
          ))
        ] }),
        groupedSchema.validFields.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
          groupedSchema.invalidFields.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mb-3", children: [
            /* @__PURE__ */ jsx("h3", { className: "text-xs font-bold uppercase tracking-wider text-slate-500", children: "Valid fields" }),
            /* @__PURE__ */ jsx("span", { className: "text-[11px] font-medium text-slate-500 bg-slate-50 border border-slate-200 rounded-full px-2 py-0.5", children: groupedSchema.validFields.length })
          ] }),
          groupedSchema.validFields.map((field) => /* @__PURE__ */ jsx(
            SchemaField,
            {
              field,
              path: field.key,
              value: formData[field.key],
              onChange: handleFieldChange,
              errors: validationErrors,
              overrides,
              onToggleOverride: toggleOverride,
              readOnly,
              warningMode: isEditMode
            },
            field.key
          ))
        ] })
      ] })
    ] }),
    !hideFooter && /* @__PURE__ */ jsx("div", { className: `px-6 py-4 border-t transition-colors duration-300 ${readOnly ? "bg-slate-50 border-slate-200" : isEditMode ? "bg-slate-50 border-slate-200" : hasActiveErrors ? "bg-red-50/30 border-red-100" : "bg-slate-50 border-slate-200"}`, children: isEditMode ? renderEditFooter() : renderResolveFooter() }),
    !isEditMode && isRejectMode && /* @__PURE__ */ jsx("div", { className: "absolute inset-0 z-50 bg-slate-900/50 backdrop-blur-sm flex items-center justify-center p-4", children: /* @__PURE__ */ jsxs("div", { className: "bg-white rounded-xl shadow-2xl max-w-md w-full p-6 animate-in fade-in zoom-in-95 duration-200 border border-slate-200", children: [
      /* @__PURE__ */ jsxs("h3", { className: "text-lg font-bold text-slate-900 mb-2", children: [
        "Reject Record ",
        /* @__PURE__ */ jsxs("span", { className: "font-mono text-base font-normal text-slate-500", children: [
          "#",
          record.id
        ] })
      ] }),
      /* @__PURE__ */ jsx("p", { className: "text-sm text-slate-500 mb-4", children: "Please provide a reason for rejecting this record. This will be logged in the system." }),
      /* @__PURE__ */ jsx(
        "textarea",
        {
          ref: textareaRef,
          className: "w-full h-32 px-3 py-2 border border-slate-300 rounded-lg mb-4 focus:ring-1 focus:ring-red-500 focus:border-red-500 resize-none text-sm placeholder-slate-400",
          placeholder: "Reason for rejection...",
          value: rejectReason,
          onChange: (e) => dispatch({ type: "SET_REJECT_REASON", payload: e.target.value })
        }
      ),
      /* @__PURE__ */ jsxs("div", { className: "flex justify-end space-x-3", children: [
        /* @__PURE__ */ jsx(
          "button",
          {
            onClick: () => dispatch({ type: "SET_REJECT_MODE", payload: false }),
            className: "px-4 py-2 text-slate-600 hover:bg-slate-100 hover:text-slate-900 rounded-lg font-medium text-sm transition-colors",
            children: "Cancel"
          }
        ),
        /* @__PURE__ */ jsx(
          "button",
          {
            onClick: confirmReject,
            disabled: !rejectReason.trim(),
            className: "px-4 py-2 bg-red-600 hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed text-white rounded-lg font-medium text-sm shadow-sm transition-colors",
            children: "Confirm Rejection"
          }
        )
      ] })
    ] }) })
  ] });
};
const DataQualityEditorWrapper = (props) => {
  return /* @__PURE__ */ jsx(ResolutionEditor, { ...props });
};
export {
  DataQualityEditorWrapper,
  ResolutionEditor,
  DataQualityEditorWrapper as default
};
//# sourceMappingURL=index.js.map
