/// <reference types="@dhwaniapp/plugin-sdk" />

(function() {
    const React = window.React;
    const { Node, ReactNodeViewRenderer, NodeViewWrapper, mergeAttributes } = window.DhwaniEditorSDK;
    const { useState, useEffect } = React;
    let sdk; // Populated upon registration

    // 1. Define the React Component for the Search UI
    function SearchLinkComponent(props) {
        const [query, setQuery] = useState("");
        const [results, setResults] = useState([]);
        const [loading, setLoading] = useState(false);
        const [selectedIndex, setSelectedIndex] = useState(0);

        // Perform search when query changes with a small debounce
        useEffect(() => {
            if (!query.trim()) {
                setResults([]);
                setSelectedIndex(0);
                return;
            }

            let active = true;
            setLoading(true);

            const delayDebounce = setTimeout(() => {
                if (!sdk) {
                    setLoading(false);
                    return;
                }

                sdk.api.searchContentGlobally(query)
                    .then(res => {
                        if (active) {
                            setResults(res || []);
                            setSelectedIndex(0);
                            setLoading(false);
                        }
                    })
                    .catch(err => {
                        console.error("[SearchLinkPlugin] Search error:", err);
                        if (active) {
                            setLoading(false);
                        }
                    });
            }, 150);

            return () => {
                active = false;
                clearTimeout(delayDebounce);
            };
        }, [query]);

        // Handle inserting the selected page as a link and deleting the search block
        const handleSelect = (item) => {
            if (!item || !sdk) return;

            // Generate the specialized dhwani:// link HTML
            const linkHtml = sdk.api.getHTMLLinkForNoteIdContentId(item.title, item.noteId, item.id);

            // Insert the HTML link at the cursor position
            props.editor.chain().focus().insertContent(linkHtml).run();

            // Remove the search card from the editor
            props.deleteNode();
        };

        // Keyboard navigation handlers
        const handleKeyDown = (e) => {
            if (e.key === "ArrowDown") {
                e.preventDefault();
                setSelectedIndex(prev => (results.length > 0 ? (prev + 1) % results.length : 0));
            } else if (e.key === "ArrowUp") {
                e.preventDefault();
                setSelectedIndex(prev => (results.length > 0 ? (prev - 1 + results.length) % results.length : 0));
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (results.length > 0 && selectedIndex >= 0 && selectedIndex < results.length) {
                    handleSelect(results[selectedIndex]);
                }
            } else if (e.key === "Escape") {
                e.preventDefault();
                props.deleteNode();
            }
        };

        // Render the search card using React.createElement
        return React.createElement(
            NodeViewWrapper,
            {
                className: "card bg-base-100 shadow-lg border border-base-300 rounded-xl p-4 my-4 max-w-md w-full relative select-none text-base-content",
                style: {
                    fontFamily: "var(--editor-font-family, inherit)"
                }
            },
            // Header
            React.createElement(
                "div",
                { className: "flex items-center justify-between mb-3" },
                React.createElement(
                    "h3",
                    { className: "font-semibold text-xs flex items-center gap-2 uppercase tracking-wider opacity-80" },
                    React.createElement(
                        "svg",
                        {
                            xmlns: "http://www.w3.org/2000/svg",
                            fill: "none",
                            viewBox: "0 0 24 24",
                            strokeWidth: "2",
                            stroke: "currentColor",
                            className: "w-4 h-4 text-primary"
                        },
                        React.createElement("path", {
                            strokeLinecap: "round",
                            strokeLinejoin: "round",
                            d: "M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244"
                        })
                    ),
                    "Search & Link Page"
                ),
                React.createElement(
                    "button",
                    {
                        className: "btn btn-ghost btn-xs btn-circle text-base-content/50 hover:text-base-content",
                        onClick: () => props.deleteNode()
                    },
                    "✕"
                )
            ),
            // Search Input Field
            React.createElement(
                "div",
                { className: "relative flex items-center" },
                React.createElement("input", {
                    type: "text",
                    placeholder: "Type page title to search...",
                    className: "input input-bordered input-sm w-full pr-8 focus:outline-none focus:border-primary",
                    value: query,
                    onChange: (e) => setQuery(e.target.value),
                    onKeyDown: handleKeyDown,
                    autoFocus: true
                }),
                query && React.createElement(
                    "button",
                    {
                        className: "absolute right-2.5 text-base-content/40 hover:text-base-content/70 text-xs",
                        onClick: () => setQuery("")
                    },
                    "✕"
                )
            ),
            // Results Container
            React.createElement(
                "div",
                { className: "mt-3 max-h-48 overflow-y-auto space-y-1" },
                loading && React.createElement(
                    "div",
                    { className: "flex items-center justify-center py-4 text-xs opacity-60 gap-2" },
                    React.createElement("span", { className: "loading loading-spinner loading-xs text-primary" }),
                    "Searching notes..."
                ),
                !loading && query && results.length === 0 && React.createElement(
                    "div",
                    { className: "text-center py-4 text-xs opacity-50" },
                    "No pages found matching \"" + query + "\""
                ),
                !loading && !query && React.createElement(
                    "div",
                    { className: "text-center py-4 text-xs opacity-40" },
                    "Start typing to search all notebooks..."
                ),
                !loading && results.length > 0 && results.map((item, index) => {
                    const isSelected = index === selectedIndex;
                    return React.createElement(
                        "div",
                        {
                            key: item.id,
                            className: "flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors text-xs " + 
                                (isSelected ? "bg-primary text-primary-content font-medium" : "hover:bg-base-200"),
                            onClick: () => handleSelect(item)
                        },
                        React.createElement(
                            "div",
                            { className: "flex flex-col text-left truncate max-w-[75%]" },
                            React.createElement("span", { className: "font-medium truncate" }, item.title),
                            React.createElement(
                                "span",
                                { className: "text-[10px] opacity-75 truncate mt-0.5" },
                                "In: " + (item.noteTitle || "Notebook")
                            )
                        ),
                        React.createElement(
                            "div",
                            { className: "flex items-center gap-1.5 shrink-0" },
                            React.createElement(
                                "span",
                                { className: "badge badge-xs badge-outline capitalize font-mono text-[9px]" },
                                item.type
                            ),
                            React.createElement(
                                "span",
                                { className: "text-[9px] font-bold uppercase tracking-wider opacity-80" },
                                "Link"
                            )
                        )
                    );
                })
            )
        );
    }

    // 2. Define the Custom Tiptap Node
    const SearchLinkNode = Node.create({
        name: "searchLink",
        group: "block",
        atom: true, // Leaf node, renders its own interface and does not have editable text inside

        parseHTML() {
            return [{ tag: "div[data-type=\"search-link\"]" }];
        },

        renderHTML({ HTMLAttributes }) {
            return ["div", mergeAttributes(HTMLAttributes, { "data-type": "search-link" })];
        },

        addNodeView() {
            return ReactNodeViewRenderer(SearchLinkComponent);
        }
    });

    // 3. Register the extension and Slash Command
    sdk = window.Dhwani.registerPageExtension({
        name: "searchLink",
        tiptapExtension: SearchLinkNode,
        slashCommand: {
            title: "Search & Link Page",
            description: "Search note pages by title and insert a link",
            icon: `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 text-primary">
              <path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244" />
            </svg>`,
            command: (editor) => {
                editor
                    .chain()
                    .focus()
                    .insertContent({ type: "searchLink" })
                    .run();
            }
        }
    });

    console.log("[SearchLinkPlugin] Plugin registered successfully!");
})();
