'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useCallback, useState } from 'react';
import { BubbleMenu } from '@tiptap/react';
import { Loader2, Maximize2, Minimize2, Sparkles, SpellCheck, Wand2 } from 'lucide-react';
import { toast } from 'sonner';
import { COAUTHOR_ACTIONS, coauthorActionLabel, coauthorText, } from '../lib/coauthor-client.js';
import { CoauthorResultPopover } from './CoauthorResultPopover.js';
const ACTION_ICONS = {
    rewrite: Wand2,
    expand: Maximize2,
    compress: Minimize2,
    proofread: SpellCheck,
};
const INITIAL = {
    open: false,
    loading: false,
    action: 'rewrite',
    before: '',
    after: '',
    from: 0,
    to: 0,
};
/**
 * Floating menu that appears above the current text selection inside the
 * TipTap editor. Renders four AI co-author actions
 * (rewrite / expand / compress / proofread) and hands the selected text to
 * `/ai/coauthor`. When the server returns, opens the shared
 * `CoauthorResultPopover` with a before/after diff and Apply / Copy /
 * Discard actions.
 *
 * The popover, not the bubble itself, holds the result — by design — so
 * the user can scroll the editor, see the source of truth, and explicitly
 * choose what to do with the AI output.
 */
export function AICoauthorBubbleMenu({ editor }) {
    const [state, setState] = useState(INITIAL);
    const [pendingAction, setPendingAction] = useState(null);
    const runAction = useCallback(async (action) => {
        if (!editor)
            return;
        const { from, to, empty } = editor.state.selection;
        if (empty)
            return;
        const before = editor.state.doc.textBetween(from, to, '\n', '\n');
        if (!before.trim()) {
            toast.error('Select text to use the AI co-author.');
            return;
        }
        setPendingAction(action);
        setState({
            open: true,
            loading: true,
            action,
            before,
            after: '',
            from,
            to,
        });
        const outcome = await coauthorText(action, before);
        if (!outcome.ok) {
            setState((prev) => ({ ...prev, loading: false, error: outcome.error }));
            toast.error(outcome.error);
            setPendingAction(null);
            return;
        }
        setState((prev) => ({
            ...prev,
            loading: false,
            after: outcome.result.text,
            changes: outcome.result.changes,
            error: undefined,
        }));
        setPendingAction(null);
    }, [editor]);
    const handleApply = useCallback(() => {
        if (!editor)
            return;
        editor.chain().focus().insertContentAt({ from: state.from, to: state.to }, state.after).run();
        toast.success(`${coauthorActionLabel(state.action)} applied.`);
        setState(INITIAL);
    }, [editor, state.action, state.from, state.to, state.after]);
    const handleCopy = useCallback(async () => {
        try {
            await navigator.clipboard.writeText(state.after);
            toast.success('Copied to clipboard.');
        }
        catch {
            toast.error('Clipboard unavailable — copy the text manually.');
        }
    }, [state.after]);
    const handleDiscard = useCallback(() => {
        setState(INITIAL);
        setPendingAction(null);
    }, []);
    if (!editor)
        return null;
    return (_jsxs(_Fragment, { children: [_jsxs(BubbleMenu, { editor: editor, shouldShow: ({ editor: ed, from, to }) => {
                    if (state.open)
                        return false;
                    if (from === to)
                        return false;
                    if (!ed.isEditable)
                        return false;
                    return true;
                }, tippyOptions: { duration: 100, placement: 'top' }, className: "border-border bg-card flex items-center gap-0.5 rounded-md border p-1 shadow-md", children: [_jsxs("span", { className: "text-muted-foreground flex items-center gap-1 px-1.5 text-xs font-medium", children: [_jsx(Sparkles, { className: "h-3 w-3", "aria-hidden": true }), "AI"] }), _jsx("span", { className: "bg-muted mx-0.5 h-4 w-px" }), COAUTHOR_ACTIONS.map((id) => {
                        const Icon = ACTION_ICONS[id];
                        const isPending = pendingAction === id;
                        const anyPending = pendingAction !== null;
                        return (_jsxs("button", { type: "button", onClick: () => runAction(id), disabled: anyPending, className: "text-foreground hover:bg-accent flex items-center gap-1 rounded px-2 py-1 text-xs disabled:cursor-not-allowed disabled:opacity-50", title: `AI ${coauthorActionLabel(id)}`, children: [isPending ? (_jsx(Loader2, { className: "h-3 w-3 animate-spin", "aria-hidden": true })) : (_jsx(Icon, { className: "h-3 w-3", "aria-hidden": true })), coauthorActionLabel(id)] }, id));
                    })] }), _jsx(CoauthorResultPopover, { open: state.open, loading: state.loading, action: state.action, before: state.before, after: state.after, error: state.error, changes: state.changes, applyLabel: "Replace selection", onApply: handleApply, onCopy: handleCopy, onDiscard: handleDiscard })] }));
}
//# sourceMappingURL=AICoauthorBubbleMenu.js.map