"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import { memo, useCallback, useMemo, useRef } from "react";
import { HelpText, Label } from "@byline/ui/react";
import { ErrorBoundary } from "react-error-boundary";
import { richTextValidate } from "../validate/validate.js";
import { ApplyValuePlugin } from "./apply-value-plugin.js";
import { EditorContext } from "./editor-context.js";
import { hashSerializedState } from "./utils/hashSerializedState.js";
import "./editor-component.css";
import "./themes/lexical-editor-theme.css";
const baseClass = 'lexicalRichTextEditor';
const editor_component_EditorComponent = /*#__PURE__*/ memo(function({ name, id, label, description, required, readonly, editorConfig, defaultValue, value, onChange, minHeight, maxHeight, validate = richTextValidate, onError: _onError, lexicalEditorProps: _lexicalEditorProps, featureBeforeEditor, featureAfterEditor, featureChildren }) {
    const disabled = readonly ?? false;
    const dispatchFieldUpdateTask = useRef(void 0);
    const valueRef = useRef(value);
    valueRef.current = value;
    const initialValueRef = useRef(defaultValue);
    initialValueRef.current = defaultValue;
    const lastEmittedHashRef = useRef(void 0);
    const normalizedIncomingHashRef = useRef(void 0);
    const hasNormalizedBaselineRef = useRef(false);
    useCallback((val)=>{
        if ('function' == typeof validate) return validate(val, {
            required
        });
        return true;
    }, [
        validate,
        required
    ]);
    const handleChange = useCallback((editorState, _editor, _tags)=>{
        const updateFieldValue = (editorState)=>{
            const newState = editorState.toJSON();
            const nextHash = hashSerializedState(newState);
            if ((valueRef.current ?? initialValueRef.current) != null && true !== hasNormalizedBaselineRef.current) return;
            if (null != normalizedIncomingHashRef.current && nextHash === normalizedIncomingHashRef.current) return;
            if (null != lastEmittedHashRef.current && nextHash === lastEmittedHashRef.current) return;
            lastEmittedHashRef.current = nextHash;
            if ('function' == typeof onChange) onChange(newState);
        };
        if ('function' == typeof window.requestIdleCallback) {
            if ('function' == typeof window.cancelIdleCallback && dispatchFieldUpdateTask.current) cancelIdleCallback(dispatchFieldUpdateTask.current);
            dispatchFieldUpdateTask.current = requestIdleCallback(()=>updateFieldValue(editorState), {
                timeout: 500
            });
        } else updateFieldValue(editorState);
    }, [
        onChange
    ]);
    const incomingValue = value ?? defaultValue ?? void 0;
    const incomingHash = useMemo(()=>null != incomingValue ? hashSerializedState(incomingValue) : void 0, [
        incomingValue
    ]);
    return /*#__PURE__*/ jsx("div", {
        className: baseClass,
        children: /*#__PURE__*/ jsxs("div", {
            className: `${baseClass}__wrap`,
            children: [
                null != label && ('string' == typeof label ? /*#__PURE__*/ jsx(Label, {
                    id: `${id}-label`,
                    label: label,
                    htmlFor: id,
                    required: required
                }) : label),
                /*#__PURE__*/ jsx(ErrorBoundary, {
                    fallbackRender: fallbackRender,
                    onReset: ()=>{},
                    children: /*#__PURE__*/ jsxs(EditorContext, {
                        composerKey: id,
                        editorConfig: editorConfig,
                        onChange: handleChange,
                        readOnly: disabled,
                        value: incomingValue,
                        minHeight: minHeight,
                        maxHeight: maxHeight,
                        beforeEditor: featureBeforeEditor,
                        afterEditor: featureAfterEditor,
                        children: [
                            /*#__PURE__*/ jsx(ApplyValuePlugin, {
                                value: incomingValue,
                                incomingHash: incomingHash,
                                lastEmittedHashRef: lastEmittedHashRef,
                                normalizedIncomingHashRef: normalizedIncomingHashRef,
                                hasNormalizedBaselineRef: hasNormalizedBaselineRef
                            }),
                            featureChildren
                        ]
                    }, id)
                }),
                description && /*#__PURE__*/ jsx(HelpText, {
                    text: description
                })
            ]
        })
    });
});
function fallbackRender({ error }) {
    return /*#__PURE__*/ jsxs("div", {
        className: "errorBoundary",
        role: "alert",
        children: [
            /*#__PURE__*/ jsx("p", {
                children: "Something went wrong:"
            }),
            /*#__PURE__*/ jsx("pre", {
                style: {
                    color: 'red'
                },
                children: error.message
            })
        ]
    });
}
export { editor_component_EditorComponent as EditorComponent };
