"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState } from "react";
import { AutoEmbedOption, INSERT_EMBED_COMMAND, LexicalAutoEmbedPlugin } from "@lexical/react/LexicalAutoEmbedPlugin";
import { ReactExtension } from "@lexical/react/ReactExtension";
import { configExtension, declarePeerDependency, defineExtension } from "lexical";
import { useToolbarActiveEditor } from "../../plugins/toolbar-plugin/toolbar-active-editor.js";
import { DropDownItem } from "../../ui/dropdown.js";
import { BylineToolbarExtension } from "../byline-toolbar/byline-toolbar-extension.js";
import { INSERT_VIMEO_COMMAND } from "../vimeo/vimeo-extension.js";
import { INSERT_YOUTUBE_COMMAND } from "../youtube/youtube-extension.js";
import { AutoEmbedModal } from "./auto-embed-modal.js";
import * as __rspack_external_react_dom_7136dc57 from "react-dom";
const YoutubeEmbedConfig = {
    contentName: 'Youtube Video',
    exampleUrl: 'https://www.youtube.com/watch?v=jNQXAC9IVRw',
    icon: /*#__PURE__*/ jsx("i", {
        className: "icon youtube"
    }),
    insertNode: (editor, result)=>{
        editor.dispatchCommand(INSERT_YOUTUBE_COMMAND, result.id);
    },
    keywords: [
        'youtube',
        'video'
    ],
    parseUrl: async (url)=>{
        const match = /^.*(youtu\.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/.exec(url);
        const id = null != match ? match?.[2].length === 11 ? match[2] : null : null;
        if (null != id) return {
            id,
            url
        };
        return null;
    },
    type: 'youtube-video'
};
const VimeoEmbedConfig = {
    contentName: 'Vimeo Video',
    exampleUrl: 'https://vimeo.com/584985260',
    icon: /*#__PURE__*/ jsx("i", {
        className: "icon vimeo"
    }),
    insertNode: (editor, result)=>{
        editor.dispatchCommand(INSERT_VIMEO_COMMAND, result.id);
    },
    keywords: [
        'vimeo',
        'video'
    ],
    parseUrl: async (url)=>{
        const match = /https:\/\/vimeo\.com\/(\d{5,10})/.exec(url);
        const id = null != match ? match[1] : null;
        if (null != id) return {
            id,
            url
        };
        return null;
    },
    type: 'vimeo-video'
};
const EmbedConfigs = [
    YoutubeEmbedConfig,
    VimeoEmbedConfig
];
function AutoEmbedMenuItem({ index, isSelected, onClick, onMouseEnter, option }) {
    let className = 'item';
    if (isSelected) className += ' selected';
    const handleKeyDown = (event)=>{
        if ('Enter' === event.key || ' ' === event.key) {
            event.preventDefault();
            onClick();
        }
    };
    return /*#__PURE__*/ jsx("li", {
        className: className,
        ref: option.setRefElement,
        id: `typeahead-item-${index}`,
        onMouseEnter: onMouseEnter,
        onClick: onClick,
        onKeyDown: handleKeyDown,
        children: /*#__PURE__*/ jsx("span", {
            className: "text",
            children: option.title
        })
    }, option.key);
}
function AutoEmbedMenu({ options, selectedItemIndex, onOptionClick, onOptionMouseEnter }) {
    return /*#__PURE__*/ jsx("div", {
        className: "typeahead-popover",
        children: /*#__PURE__*/ jsx("ul", {
            children: options.map((option, i)=>/*#__PURE__*/ jsx(AutoEmbedMenuItem, {
                    index: i,
                    isSelected: selectedItemIndex === i,
                    onClick: ()=>{
                        onOptionClick(option, i);
                    },
                    onMouseEnter: ()=>{
                        onOptionMouseEnter(i);
                    },
                    option: option
                }, option.key))
        })
    });
}
function AutoEmbedPlugin() {
    const [open, setOpen] = useState(false);
    const [embedConfig, setEmbedConfig] = useState(null);
    const handleOnOpenEmbedModalForConfig = (config)=>{
        setEmbedConfig(config);
        setOpen(true);
    };
    const getMenuOptions = (activeEmbedConfig, embedFn, dismissFn)=>[
            new AutoEmbedOption('Dismiss', {
                onSelect: dismissFn
            }),
            new AutoEmbedOption(`Embed ${activeEmbedConfig.contentName}`, {
                onSelect: embedFn
            })
        ];
    return /*#__PURE__*/ jsxs(Fragment, {
        children: [
            /*#__PURE__*/ jsx(LexicalAutoEmbedPlugin, {
                embedConfigs: EmbedConfigs,
                onOpenEmbedModalForConfig: handleOnOpenEmbedModalForConfig,
                getMenuOptions: getMenuOptions,
                menuRenderFn: (anchorElementRef, { selectedIndex, options, selectOptionAndCleanUp, setHighlightedIndex })=>null != anchorElementRef.current ? /*#__PURE__*/ __rspack_external_react_dom_7136dc57.createPortal(/*#__PURE__*/ jsx("div", {
                        className: "typeahead-popover auto-embed-menu",
                        style: {
                            marginLeft: anchorElementRef.current.style.width,
                            width: 200
                        },
                        children: /*#__PURE__*/ jsx(AutoEmbedMenu, {
                            options: options,
                            selectedItemIndex: selectedIndex,
                            onOptionClick: (option, index)=>{
                                setHighlightedIndex(index);
                                selectOptionAndCleanUp(option);
                            },
                            onOptionMouseEnter: (index)=>{
                                setHighlightedIndex(index);
                            }
                        })
                    }), anchorElementRef.current) : null
            }),
            /*#__PURE__*/ jsx(AutoEmbedModal, {
                open: open,
                embedConfig: embedConfig,
                onClose: ()=>{
                    setOpen(false);
                    setEmbedConfig(null);
                }
            })
        ]
    });
}
function EmbedInsertItem({ embedConfig }) {
    const editor = useToolbarActiveEditor();
    return /*#__PURE__*/ jsxs(DropDownItem, {
        onClick: ()=>{
            editor.dispatchCommand(INSERT_EMBED_COMMAND, embedConfig.type);
        },
        className: "item",
        children: [
            embedConfig.icon,
            /*#__PURE__*/ jsx("span", {
                className: "text",
                children: embedConfig.contentName
            })
        ]
    });
}
const AutoEmbedExtension = defineExtension({
    name: '@byline/richtext-lexical/AutoEmbed',
    dependencies: [
        configExtension(ReactExtension, {
            decorators: [
                /*#__PURE__*/ jsx(AutoEmbedPlugin, {}, "d")
            ]
        })
    ],
    peerDependencies: [
        declarePeerDependency(BylineToolbarExtension.name, {
            items: EmbedConfigs.map((embedConfig, idx)=>({
                    id: `@byline/richtext-lexical/AutoEmbed/${embedConfig.type}`,
                    placement: 'insert-menu',
                    order: 60 + idx,
                    node: /*#__PURE__*/ jsx(EmbedInsertItem, {
                        embedConfig: embedConfig
                    })
                }))
        })
    ]
});
export { AutoEmbedExtension, AutoEmbedPlugin, EmbedConfigs, VimeoEmbedConfig, YoutubeEmbedConfig };
