import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import CharacterCount from "@tiptap/extension-character-count";
import Placeholder from "@tiptap/extension-placeholder";
import { Extension } from "@tiptap/core";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import styles from "./CampaignMessage.module.scss";
// Custom extension for template variable highlighting
const TemplateVariableHighlight = Extension.create({
    name: 'templateVariableHighlight',
    addProseMirrorPlugins() {
        const getDecorations = (doc) => {
            const decorations = [];
            const templateVarRegex = /{{\.(?:Last_Name|Full_Name|School_Name|Job_Title|My_Name|My_First_Name|My_Full_Name|User_Name|Current_Company|Current_Title|Hiring_Company)}}/g;
            doc.descendants((node, pos) => {
                if (node.isText) {
                    const text = node.text;
                    let match;
                    templateVarRegex.lastIndex = 0; // Reset regex
                    while ((match = templateVarRegex.exec(text)) !== null) {
                        const start = pos + match.index;
                        const end = start + match[0].length;
                        decorations.push(Decoration.inline(start, end, {
                            class: 'highlighted-template-var'
                        }));
                    }
                }
            });
            return DecorationSet.create(doc, decorations);
        };
        const pluginKey = new PluginKey('templateVariableHighlight');
        return [
            new Plugin({
                key: pluginKey,
                state: {
                    init: (_, { doc }) => {
                        return getDecorations(doc);
                    },
                    apply: (tr) => {
                        return getDecorations(tr.doc);
                    }
                },
                props: {
                    decorations: (state) => {
                        return pluginKey.getState(state);
                    }
                }
            })
        ];
    }
});
const CampaignMessage = ({ value = "", handleChange = () => false, placeholder = "Type your message...", maxLength = 369 }) => {
    const editor = useEditor({
        extensions: [
            StarterKit.configure({
                heading: false,
                bold: false,
                italic: false,
                strike: false,
                code: false,
                codeBlock: false,
                blockquote: false,
                horizontalRule: false,
                listItem: false,
                orderedList: false,
                bulletList: false,
                history: {
                    depth: 50,
                },
            }),
            CharacterCount.configure({
                limit: maxLength,
            }),
            Placeholder.configure({
                placeholder,
            }),
            TemplateVariableHighlight,
        ],
        content: value,
        onUpdate: ({ editor }) => {
            const text = editor.getText();
            handleChange(text);
        },
        editorProps: {
            handlePaste: (view, event) => {
                const text = event.clipboardData?.getData('text/plain') || '';
                const currentLength = view.state.doc.textContent.length;
                const remainingChars = maxLength - currentLength;
                if (remainingChars <= 0) {
                    return true; // Block the paste
                }
                if (text.length > remainingChars) {
                    const truncatedText = text.slice(0, remainingChars);
                    const { from, to } = view.state.selection;
                    view.dispatch(view.state.tr.insertText(truncatedText, from, to));
                    return true; // Block the original paste
                }
                return false; // Allow the paste
            },
            handleTextInput: (view, from, to, text) => {
                const currentLength = view.state.doc.textContent.length;
                const textLength = text.length;
                const selectionLength = to - from;
                const newLength = currentLength - selectionLength + textLength;
                if (newLength > maxLength) {
                    return true; // Block the input
                }
                return false; // Allow the input
            },
            attributes: {
                class: styles.editorContent,
            },
        },
    });
    // Update editor content when value prop changes
    useEffect(() => {
        if (editor && value !== editor.getText()) {
            editor.commands.setContent(value);
        }
    }, [value, editor]);
    const charactersLeft = maxLength - (editor?.storage.characterCount?.characters() || 0);
    return (_jsxs("div", { className: styles.campaignMessageWrapper, children: [_jsx("p", { className: styles.campaignMessageHeading, children: "Your Message" }), _jsx("div", { className: styles.campaignMessageContainer, children: _jsx(EditorContent, { editor: editor, className: styles.editorContent }) }), _jsxs("p", { className: styles.campaignMessageCharactersLeft, children: [charactersLeft, " characters left"] })] }));
};
export default CampaignMessage;
