import { c as Kind } from "./parser-CkF6Qt8V.js";
import { r as typeDefsDoc } from "./documents-D4ek7Ubv.js";
import { f as makeStateSchemaNameForScope, l as makeInitialSchemaDoc, m as validateStateObject, n as ensureValidStateSchemaName, r as StateValidationError, u as makeMinimalObjectForStateType } from "./linting-Dn6pXRkK.js";
import { C as twMerge, i as Trigger, n as List, r as Root2, t as Content } from "./dist-D8H48e8N.js";
import { n as safeParseSdl, r as useSchemaContext } from "./schema-context-DY-GEGnY.js";
import * as React$1 from "react";
import { Suspense, forwardRef, lazy, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
//#region editors/document-model-editor/components/button.tsx
const Button = forwardRef((props, ref) => {
	const { className, ...rest } = props;
	return /* @__PURE__ */ jsx("button", {
		ref,
		...rest,
		className: twMerge("h-10 rounded-md border border-gray-200 bg-gray-50 px-4 py-2 text-sm font-medium whitespace-nowrap text-gray-900 transition-colors hover:bg-gray-100 hover:text-gray-900 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50 dark:border-slate-500 dark:bg-slate-600 dark:text-slate-100 dark:hover:bg-slate-700 dark:hover:text-slate-50", className)
	});
});
//#endregion
//#region editors/document-model-editor/components/state-error.tsx
function StateValidationErrorMessage({ error }) {
	const { payload } = error;
	switch (payload.kind) {
		case "MISSING": return /* @__PURE__ */ jsxs("span", { children: [
			"Field ",
			/* @__PURE__ */ jsx("strong", { children: payload.field }),
			" is missing."
		] });
		case "MISSING_OPTIONAL": return /* @__PURE__ */ jsxs("span", { children: [
			"Optional field ",
			/* @__PURE__ */ jsx("strong", { children: payload.field }),
			" is not defined."
		] });
		case "UNKNOWN_FIELD": return /* @__PURE__ */ jsxs("span", { children: [
			"Field ",
			/* @__PURE__ */ jsx("strong", { children: payload.field }),
			" is not a known field."
		] });
		case "NON_NULL": return /* @__PURE__ */ jsxs("span", { children: [
			"Field ",
			/* @__PURE__ */ jsx("strong", { children: payload.field }),
			" cannot be null."
		] });
		case "TYPE": return /* @__PURE__ */ jsxs("span", { children: [
			"Field ",
			/* @__PURE__ */ jsx("strong", { children: payload.field }),
			payload.expectedType ? /* @__PURE__ */ jsxs(Fragment$1, { children: [
				" ",
				"must be a",
				" ",
				/* @__PURE__ */ jsx("strong", { children: payload.expectedType.replace(/!/g, "") }),
				"."
			] }) : /* @__PURE__ */ jsx(Fragment$1, { children: " has an invalid value." })
		] });
		case "RECURSIVE_TYPE": return /* @__PURE__ */ jsxs("span", { children: [
			"Field ",
			/* @__PURE__ */ jsx("strong", { children: payload.typeName }),
			" has a recursive type. It must be optional."
		] });
		default: return /* @__PURE__ */ jsx("span", { children: "Invalid value." });
	}
}
//#endregion
//#region editors/document-model-editor/components/tabs.tsx
const Tabs = Root2;
const TabsList = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(List, {
	ref,
	className: twMerge("flex items-center justify-center rounded-xl bg-gray-50 p-1 shadow-inner dark:bg-slate-800", className),
	...props
}));
TabsList.displayName = List.displayName;
const TabsTrigger = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Trigger, {
	ref,
	className: twMerge("flex w-full items-center justify-center rounded-lg p-1 text-sm whitespace-nowrap text-gray-500 transition-all disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-gray-50 data-[state=active]:text-gray-800 data-[state=active]:shadow-tab dark:text-slate-400", className),
	...props
}));
TabsTrigger.displayName = Trigger.displayName;
const TabsContent = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Content, {
	ref,
	className,
	...props
}));
TabsContent.displayName = Content.displayName;
//#endregion
//#region editors/document-model-editor/components/state-schemas.tsx
const GraphqlEditor = lazy(() => import("./graphql-editor-8bWqxqUN.js"));
const JSONEditor = lazy(() => import("./json-editor-DlvyzQQO.js"));
function StateEditor({ modelName, stateSchema, initialValue, setStateSchema, setInitialState, scope }) {
	const { sharedSchema: sharedSchemaSdl, error: sharedSchemaError } = useSchemaContext();
	const [showStandardLib, setShowStandardLib] = useState(false);
	const [syncWithSchema, setSyncWithSchema] = useState(true);
	const customLinter = useCallback((doc) => ensureValidStateSchemaName(doc, modelName, scope), [modelName, scope]);
	const schemaErrors = useMemo(() => {
		const errors = ensureValidStateSchemaName(stateSchema, modelName, scope);
		if (sharedSchemaError) return [...errors, sharedSchemaError];
		return errors;
	}, [
		stateSchema,
		modelName,
		scope,
		sharedSchemaError
	]);
	const handleToggleStandardLib = useCallback(() => {
		setShowStandardLib((prev) => !prev);
	}, []);
	const handleSchemaUpdate = useCallback((newDoc) => setStateSchema(newDoc, scope), [setStateSchema, scope]);
	const handleInitialStateUpdate = useCallback((newDoc) => setInitialState(newDoc, scope), [setInitialState, scope]);
	const hasSyncedRef = useRef(false);
	const { initialValueErrors, fixedState } = useMemo(() => {
		const existingValue = initialValue || "{}";
		const sharedSchemaDocumentNode = safeParseSdl(sharedSchemaSdl);
		if (!sharedSchemaDocumentNode) return {
			initialValueErrors: [],
			fixedState: null
		};
		const stateTypeName = makeStateSchemaNameForScope(modelName, scope);
		if (!stateTypeName) return {
			initialValueErrors: [],
			fixedState: null
		};
		const stateTypeDefinitionNode = sharedSchemaDocumentNode.definitions.find((def) => def.kind === Kind.OBJECT_TYPE_DEFINITION && def.name.value === stateTypeName);
		if (!stateTypeDefinitionNode || stateTypeDefinitionNode.kind !== Kind.OBJECT_TYPE_DEFINITION) return {
			initialValueErrors: [],
			fixedState: null
		};
		const errors = validateStateObject(sharedSchemaDocumentNode, stateTypeDefinitionNode, existingValue);
		if (errors.length && syncWithSchema) {
			const computedFixedState = makeMinimalObjectForStateType({
				sharedSchemaDocumentNode,
				stateTypeDefinitionNode,
				existingValue
			});
			if (initialValue !== computedFixedState) return {
				initialValueErrors: [],
				fixedState: computedFixedState
			};
		}
		return {
			initialValueErrors: errors,
			fixedState: null
		};
	}, [
		sharedSchemaSdl,
		initialValue,
		syncWithSchema,
		scope,
		modelName
	]);
	useEffect(() => {
		if (fixedState && !hasSyncedRef.current) {
			hasSyncedRef.current = true;
			setInitialState(fixedState, scope);
		} else if (!fixedState) hasSyncedRef.current = false;
	}, [
		fixedState,
		setInitialState,
		scope
	]);
	return /* @__PURE__ */ jsxs("div", {
		className: "grid grid-cols-2 gap-4",
		children: [/* @__PURE__ */ jsxs("div", { children: [
			/* @__PURE__ */ jsxs("h3", {
				className: "mb-2 text-lg text-gray-900 capitalize dark:text-slate-100",
				children: [scope, " state schema *"]
			}),
			/* @__PURE__ */ jsxs(Button, {
				onClick: handleToggleStandardLib,
				className: "mb-2 flex w-fit items-center gap-2",
				children: [
					showStandardLib ? "Hide" : "Show",
					" standard library",
					/* @__PURE__ */ jsx("svg", {
						className: twMerge("inline-block transition-transform", showStandardLib ? "rotate-180" : "rotate-0"),
						xmlns: "http://www.w3.org/2000/svg",
						width: "24",
						height: "24",
						viewBox: "0 0 24 24",
						fill: "currentColor",
						children: /* @__PURE__ */ jsx("path", {
							d: "M11.9883 6.01172C11.4363 6.01172 10.9883 6.45972 10.9883 7.01172V13.0117H6.98828L11.9883 18.0117L16.9883 13.0117H12.9883V7.01172C12.9883 6.45972 12.5403 6.01172 11.9883 6.01172Z",
							fill: "currentColor"
						})
					})
				]
			}),
			/* @__PURE__ */ jsxs(Suspense, { children: [
				showStandardLib && /* @__PURE__ */ jsx(GraphqlEditor, {
					doc: typeDefsDoc,
					readonly: true
				}),
				/* @__PURE__ */ jsx(GraphqlEditor, {
					doc: stateSchema,
					updateDocumentInModel: handleSchemaUpdate,
					customLinter
				}),
				schemaErrors.length > 0 && /* @__PURE__ */ jsx("p", {
					className: "mt-2 text-sm text-red-600 dark:text-red-100",
					children: schemaErrors[0].message
				})
			] })
		] }), /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
			className: "flex flex-col items-end",
			children: [/* @__PURE__ */ jsxs("h3", {
				className: "mb-2 text-right text-lg text-gray-900 capitalize dark:text-slate-100",
				children: [scope, " state initial value *"]
			}), /* @__PURE__ */ jsxs("label", {
				className: "mb-2 flex w-fit items-center gap-2 rounded-md border border-gray-200 bg-gray-50 p-2 text-sm font-medium whitespace-nowrap text-gray-900 transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none dark:border-slate-500 dark:bg-slate-600 dark:text-slate-100 dark:hover:bg-slate-500 dark:hover:text-slate-50",
				children: [
					/* @__PURE__ */ jsx("input", {
						type: "checkbox",
						className: "",
						value: syncWithSchema.toString(),
						onChange: (e) => {
							setSyncWithSchema(e.currentTarget.value === "true" ? true : false);
						}
					}),
					"Sync with schema",
					" ",
					/* @__PURE__ */ jsx("svg", {
						className: "inline-block",
						xmlns: "http://www.w3.org/2000/svg",
						width: "16",
						height: "16",
						viewBox: "0 0 16 16",
						fill: "none",
						children: /* @__PURE__ */ jsx("path", {
							d: "M8.00521 1.99219C6.63588 1.99219 5.32788 2.45152 4.27588 3.28419C3.98721 3.51219 3.94321 3.93285 4.17188 4.22151C4.40054 4.51018 4.82055 4.55418 5.10921 4.32552C5.92721 3.67819 6.93921 3.32552 8.00521 3.32552C10.5825 3.32552 12.6719 5.41485 12.6719 7.99218H11.3385L13.3385 10.6588L15.3385 7.99218H14.0052C14.0052 4.67818 11.3192 1.99219 8.00521 1.99219ZM2.67188 5.32552L0.671875 7.99218H2.00521C2.00521 11.3062 4.69121 13.9922 8.00521 13.9922C9.37521 13.9922 10.6825 13.5335 11.7345 12.7002C12.0232 12.4722 12.0672 12.0515 11.8385 11.7628C11.6099 11.4742 11.1899 11.4302 10.9012 11.6588C10.0825 12.3068 9.07188 12.6588 8.00521 12.6588C5.42788 12.6588 3.33854 10.5695 3.33854 7.99218H4.67188L2.67188 5.32552Z",
							fill: "currentColor"
						})
					})
				]
			})]
		}), /* @__PURE__ */ jsxs(Suspense, { children: [/* @__PURE__ */ jsx(JSONEditor, {
			doc: initialValue,
			updateDocumentInModel: handleInitialStateUpdate
		}), initialValueErrors.map((error, index) => /* @__PURE__ */ jsx("p", {
			className: "mt-2 text-sm text-red-600 dark:text-red-100",
			children: error instanceof StateValidationError ? /* @__PURE__ */ jsx(StateValidationErrorMessage, { error }) : error.message
		}, index))] })] })]
	});
}
function StateSchemas({ modelName, globalStateSchema, localStateSchema, globalStateInitialValue, localStateInitialValue, setStateSchema, setInitialState, currentScope, onScopeChange }) {
	const handleAddLocalState = useCallback(() => {
		setStateSchema(makeInitialSchemaDoc(modelName, "local"), "local");
		setInitialState("", "local");
	}, [
		modelName,
		setStateSchema,
		setInitialState
	]);
	return /* @__PURE__ */ jsxs(Tabs, {
		className: "pb-8",
		activationMode: "manual",
		value: currentScope,
		onValueChange: (value) => onScopeChange(value),
		children: [
			/* @__PURE__ */ jsx("div", {
				className: "my-6",
				children: /* @__PURE__ */ jsxs(TabsList, {
					className: "mx-auto flex max-w-sm",
					children: [/* @__PURE__ */ jsx(TabsTrigger, {
						value: "global",
						children: "Global"
					}), /* @__PURE__ */ jsx(TabsTrigger, {
						value: "local",
						children: "Local"
					})]
				})
			}),
			/* @__PURE__ */ jsx(TabsContent, {
				value: "global",
				tabIndex: -1,
				children: /* @__PURE__ */ jsx(StateEditor, {
					modelName,
					stateSchema: globalStateSchema,
					initialValue: globalStateInitialValue,
					setStateSchema,
					setInitialState,
					scope: "global"
				})
			}),
			/* @__PURE__ */ jsx(TabsContent, {
				value: "local",
				tabIndex: -1,
				children: !localStateSchema ? /* @__PURE__ */ jsxs("div", {
					className: "",
					children: [/* @__PURE__ */ jsx("h3", {
						className: "mb-2 text-lg text-gray-900 capitalize dark:text-slate-100",
						children: "local state schema *"
					}), /* @__PURE__ */ jsx(Button, {
						onClick: handleAddLocalState,
						children: "Add local state"
					})]
				}) : /* @__PURE__ */ jsx(StateEditor, {
					modelName,
					stateSchema: localStateSchema,
					initialValue: localStateInitialValue,
					setStateSchema,
					setInitialState,
					scope: "local"
				})
			})
		]
	});
}
//#endregion
export { StateSchemas as default };

//# sourceMappingURL=state-schemas-CVQyYhpH.js.map