"use client";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { lazy, Suspense, useCallback, useEffect, useState } from "react";
import { getRichTextProfile } from "../services/contentService";
import { useRichTextProfileParsed } from "./richtext/hooks/useRichTextProfile";
const RichTextEditorComponent = lazy(() => import("./RichTextEditorComponent").then((module) => ({
    default: module.RichTextEditorComponent,
})));
export function RichTextEditor({ field, readOnly, updateFieldValue, isFocusedField, }) {
    const [isMounted, setIsMounted] = useState(false);
    const profilePath = field.customProperties?.profile;
    const itemId = field.descriptor.item.id;
    const itemLanguage = field.descriptor.item.language;
    const itemVersion = field.descriptor.item.version;
    const fieldProfileKey = [
        itemId,
        itemLanguage,
        itemVersion,
        field.id,
        profilePath ?? "",
    ].join(":");
    const [requestedProfileKeys, setRequestedProfileKeys] = useState(() => new Set());
    const profileLoadRequested = isFocusedField || requestedProfileKeys.has(fieldProfileKey);
    const profileServiceCall = useCallback((path) => getRichTextProfile(path, itemId), [itemId]);
    useEffect(() => {
        setIsMounted(true);
    }, []);
    useEffect(() => {
        if (isFocusedField) {
            setRequestedProfileKeys((previousKeys) => {
                if (previousKeys.has(fieldProfileKey)) {
                    return previousKeys;
                }
                const nextKeys = new Set(previousKeys);
                nextKeys.add(fieldProfileKey);
                return nextKeys;
            });
        }
    }, [fieldProfileKey, isFocusedField]);
    const { profile, error } = useRichTextProfileParsed(profilePath, profileServiceCall, { enabled: profileLoadRequested });
    // Show error state if profile failed to load
    if (error) {
        return (_jsxs("div", { style: { padding: "8px", color: "var(--color-feedback-red)" }, children: ["Error loading RTE profile from ", profilePath, ": ", error.message] }));
    }
    if (!isMounted) {
        return (_jsx("div", { style: { padding: "8px", color: "var(--color-neutral-grey-50)" }, children: "Loading editor..." }));
    }
    return (_jsx(Suspense, { fallback: _jsx("div", { style: { padding: "8px", color: "var(--color-neutral-grey-50)" }, children: "Loading editor..." }), children: _jsx(RichTextEditorComponent, { field: field, readOnly: readOnly, profile: profile, updateFieldValue: updateFieldValue, showControls: isFocusedField }) }));
}
//# sourceMappingURL=RichTextEditor.js.map