"use client";
import { jsx as _jsx } from "react/jsx-runtime";
import * as React from "react";
import { createPortal } from "react-dom";
import dynamic from "next/dynamic";
import { useEdenContext } from "eden/context";
const EditableMap = dynamic(() => import("./editable-map"), { ssr: false });
const CONTAINER_SELECTOR = ".editable-map";
const EDITOR_SELECTOR = "[data-eden-editor]";
const DIALOG_SELECTOR = "dialog, [role='dialog']";
const OVERRIDE_SELECTOR = "[data-map-presets-override]";
const MOUNT_DELAY = 200;
export default function EdenEditableMap() {
    const { lang, path } = useEdenContext();
    const [formats, setFormats] = React.useState([]);
    const [refreshKey, setRefreshKey] = React.useState(0);
    const refresh = React.useCallback(() => setRefreshKey((key) => key + 1), []);
    React.useEffect(() => {
        setFormats([]);
        const timeout = setTimeout(() => setFormats(collectFormats()), MOUNT_DELAY);
        return () => clearTimeout(timeout);
    }, [lang, path, refreshKey]);
    React.useEffect(() => {
        const editors = Array.from(document.querySelectorAll(EDITOR_SELECTOR));
        window.addEventListener("eden-content-saved", refresh);
        editors.forEach((editor) => {
            editor.addEventListener("eden-block-created", refresh);
            editor.addEventListener("eden-block-pasted", refresh);
        });
        return () => {
            window.removeEventListener("eden-content-saved", refresh);
            editors.forEach((editor) => {
                editor.removeEventListener("eden-block-created", refresh);
                editor.removeEventListener("eden-block-pasted", refresh);
            });
        };
    }, [refresh]);
    return formats.map((format, index) => createPortal(_jsx(EditableMap, { format: format }), format.element, String(index)));
}
function collectFormats() {
    const elements = document.querySelectorAll(CONTAINER_SELECTOR);
    return Array.from(elements).map((element) => ({
        element,
        isInDialog: Boolean(element.closest(DIALOG_SELECTOR)),
        isInEditor: Boolean(element.closest(EDITOR_SELECTOR)),
        presets: {
            ...parsePresets(element.dataset.presets),
            ...parsePresets(element.closest(OVERRIDE_SELECTOR)?.dataset
                .mapPresetsOverride),
        },
    }));
}
function parsePresets(value) {
    if (!value) {
        return {};
    }
    try {
        return JSON.parse(value);
    }
    catch (error) {
        console.error("[eden-editable-map] Invalid map presets", error);
        return {};
    }
}
