import { jsx } from "react/jsx-runtime";
import { useContext, useMemo } from "react";
import { RecursionField, Schema } from "@tachybase/schema";
import { SchemaComponentContext } from "../context.mjs";
import { SchemaComponentOptions } from "./SchemaComponentOptions.mjs";
function toSchema(schema) {
    if (Schema.isSchemaInstance(schema)) return schema;
    if (null == schema ? void 0 : schema.name) return new Schema({
        type: 'object',
        properties: {
            [schema.name]: schema
        }
    });
    return new Schema(schema);
}
const useMemoizedSchema = (schema)=>useMemo(()=>toSchema(schema), []);
const RecursionSchemaComponent = (props)=>{
    const { components, scope, schema, ...others } = props;
    const ctx = useContext(SchemaComponentContext);
    const s = useMemo(()=>toSchema(schema), [
        schema
    ]);
    return /*#__PURE__*/ jsx(SchemaComponentContext.Provider, {
        value: {
            ...ctx,
            refresh: ()=>{
                var _ctx_refresh, _props_onChange;
                null == (_ctx_refresh = ctx.refresh) || _ctx_refresh.call(ctx);
                null == (_props_onChange = props.onChange) || _props_onChange.call(props, s);
            }
        },
        children: /*#__PURE__*/ jsx(SchemaComponentOptions, {
            inherit: true,
            components: components,
            scope: scope,
            children: /*#__PURE__*/ jsx(RecursionField, {
                ...others,
                schema: s
            })
        })
    });
};
const MemoizedSchemaComponent = (props)=>{
    const { schema, ...others } = props;
    const s = useMemoizedSchema(schema);
    return /*#__PURE__*/ jsx(RecursionSchemaComponent, {
        ...others,
        schema: s
    });
};
const SchemaComponent = (props)=>{
    const { memoized, ...others } = props;
    if (memoized) return /*#__PURE__*/ jsx(MemoizedSchemaComponent, {
        ...others
    });
    return /*#__PURE__*/ jsx(RecursionSchemaComponent, {
        ...others
    });
};
export { SchemaComponent };
