import { Extension } from '@tiptap/core';
import { Plugin, PluginKey } from 'prosemirror-state';
import { Decoration, DecorationSet } from 'prosemirror-view';

export interface WikiAutoLinkOptions {
    wikiMap: Map<string, string>;
    onSuggest?: (match: { title: string, id: string, from: number, to: number }) => void;
}

export const WikiAutoLink = Extension.create<WikiAutoLinkOptions>({
    name: 'wikiAutoLink',

    addOptions() {
        return {
            wikiMap: new Map(),
            onSuggest: undefined,
        };
    },

    addProseMirrorPlugins() {
        const { wikiMap, onSuggest } = this.options;
        const pluginKey = new PluginKey('wikiAutoLink');

        return [
            new Plugin({
                key: pluginKey,
                state: {
                    init() {
                        return DecorationSet.empty;
                    },
                    apply(tr, oldState) {
                        // For simplicity and performance in Phase 1, 
                        // we'll recalculate decorations on every change for the visible content.
                        // In a larger doc, we'd optimize to only scan changed nodes.

                        if (!tr.docChanged) return oldState;

                        const decorations: Decoration[] = [];
                        const textContent = tr.doc.textBetween(0, tr.doc.content.size, ' ');

                        // Skip scanning if wikiMap is empty
                        if (wikiMap.size === 0) return DecorationSet.empty;

                        // Scan for each title in the map
                        // Note: This is a basic O(n*m) scanner. 
                        // For Phase 1 this is fine. For Phase 3, we'd use Aho-Corasick.
                        wikiMap.forEach((id, title) => {
                            if (title.length < 2) return; // Skip very short titles

                            // [Fix 3] \b(word boundary)는 한글에서 동작 안 함 → lookahead/lookbehind로 교체
                            const escaped = title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                            const regex = new RegExp(`(?<![\\w가-힣ㄱ-ㅎ])${escaped}(?![\\w가-힣ㄱ-ㅎ])`, 'gi');
                            let match;
                            while ((match = regex.exec(textContent)) !== null) {
                                // Check if this match is already inside an existing link or wikiLink node
                                // (Implementation simplified for now: just add decoration)
                                decorations.push(
                                    Decoration.inline(match.index, match.index + title.length, {
                                        class: 'potential-wiki-link',
                                        'data-id': id,
                                        'data-title': title,
                                    })
                                );
                            }
                        });

                        return DecorationSet.create(tr.doc, decorations);
                    },
                },
                props: {
                    decorations(state) {
                        return this.getState(state);
                    },
                },
            }),
        ];
    },
});
