import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useRef, useState, useCallback, } from "react";
import { Check, RotateCcw, Wand2 } from "lucide-react";
import { Button } from "../../components/ui/button";
import { useEditContext } from "../client/editContext";
/**
 * Overlay component that appears on an image after AI edit completes.
 * Provides options to accept, revert, or refine the edit.
 */
export function AiImageResultOverlay({ fieldDescriptor, originalRawValue, agentId, onAccept, onRevert, onRefine, autoDismissMs = 0, }) {
    const editContext = useEditContext();
    const [isVisible, setIsVisible] = useState(true);
    const [indicatorRect, setIndicatorRect] = useState(null);
    const rafRef = useRef(null);
    const dismissTimerRef = useRef(null);
    // Find the field element in the iframe
    const pageViewContext = editContext?.getActiveSlotContext()?.primaryPageViewContext;
    const fieldElements = useMemo(() => {
        if (!pageViewContext?.editorIframe?.contentWindow?.document)
            return [];
        const elements = pageViewContext.editorIframe.contentWindow.document.querySelectorAll(`[data-fieldid="${fieldDescriptor.fieldId}"][data-itemid="${fieldDescriptor.item.id}"][data-language="${fieldDescriptor.item.language}"][data-version="${fieldDescriptor.item.version}"]`);
        return Array.from(elements);
    }, [
        pageViewContext?.editorIframe,
        fieldDescriptor.fieldId,
        fieldDescriptor.item.id,
        fieldDescriptor.item.language,
        fieldDescriptor.item.version,
    ]);
    const element = fieldElements[0] ?? null;
    // Track bounds so the overlay follows the field while the iframe scrolls
    useEffect(() => {
        if (!element)
            return;
        const ownerDoc = element.ownerDocument;
        const ownerWin = ownerDoc.defaultView ?? null;
        const scrollContainer = ownerDoc.scrollingElement ?? ownerDoc.documentElement ?? ownerDoc.body;
        const update = () => {
            try {
                setIndicatorRect(element.getBoundingClientRect());
            }
            catch {
                setIndicatorRect(null);
            }
        };
        const scheduleUpdate = () => {
            if (rafRef.current != null)
                window.cancelAnimationFrame(rafRef.current);
            rafRef.current = window.requestAnimationFrame(() => {
                rafRef.current = null;
                update();
            });
        };
        update();
        scrollContainer?.addEventListener("scroll", scheduleUpdate, {
            passive: true,
        });
        ownerWin?.addEventListener("scroll", scheduleUpdate, { passive: true });
        ownerWin?.addEventListener("resize", scheduleUpdate);
        let ro = null;
        try {
            ro = new ResizeObserver(scheduleUpdate);
            ro.observe(element);
        }
        catch {
            ro = null;
        }
        return () => {
            if (rafRef.current != null) {
                window.cancelAnimationFrame(rafRef.current);
                rafRef.current = null;
            }
            scrollContainer?.removeEventListener("scroll", scheduleUpdate);
            ownerWin?.removeEventListener("scroll", scheduleUpdate);
            ownerWin?.removeEventListener("resize", scheduleUpdate);
            try {
                ro?.disconnect();
            }
            catch { }
        };
    }, [element]);
    // Auto-dismiss timer
    useEffect(() => {
        if (autoDismissMs > 0) {
            dismissTimerRef.current = setTimeout(() => {
                setIsVisible(false);
                onAccept();
            }, autoDismissMs);
        }
        return () => {
            if (dismissTimerRef.current) {
                clearTimeout(dismissTimerRef.current);
            }
        };
    }, [autoDismissMs, onAccept]);
    // Handle accept (keep the edit)
    const handleAccept = useCallback(() => {
        setIsVisible(false);
        onAccept();
    }, [onAccept]);
    // Handle revert (restore original value)
    const handleRevert = useCallback(() => {
        if (editContext) {
            editContext.operations.editField({
                field: fieldDescriptor,
                rawValue: originalRawValue,
                refresh: "immediate",
            });
        }
        setIsVisible(false);
        onRevert();
    }, [editContext, fieldDescriptor, originalRawValue, onRevert]);
    // Handle refine (re-open editor)
    const handleRefine = useCallback(() => {
        if (dismissTimerRef.current) {
            clearTimeout(dismissTimerRef.current);
        }
        setIsVisible(false);
        onRefine?.();
    }, [onRefine]);
    if (!isVisible || !indicatorRect || !element)
        return null;
    return (_jsxs("div", { className: "pointer-events-none absolute", style: {
            left: indicatorRect.x,
            top: indicatorRect.y,
            width: indicatorRect.width,
            height: indicatorRect.height,
            zIndex: 850,
        }, children: [_jsx("div", { className: "border-feedback-green bg-feedback-green/10 absolute inset-0 rounded border-2" }), _jsxs("div", { className: "ring-neutral-grey-100/10 pointer-events-auto absolute top-2 right-2 flex items-center gap-1 rounded-lg bg-white/95 p-1 shadow-lg ring-1 backdrop-blur-sm", children: [_jsxs(Button, { size: "sm", variant: "ghost", onClick: handleAccept, className: "text-feedback-green hover:bg-feedback-green-light hover:text-feedback-green h-7 gap-1 px-2 text-xs", title: "Accept edit", children: [_jsx(Check, { className: "h-3.5 w-3.5", strokeWidth: 2 }), "Accept"] }), _jsxs(Button, { size: "sm", variant: "ghost", onClick: handleRevert, className: "text-feedback-orange hover:bg-feedback-orange-light hover:text-feedback-orange h-7 gap-1 px-2 text-xs", title: "Revert to original", children: [_jsx(RotateCcw, { className: "h-3.5 w-3.5", strokeWidth: 2 }), "Revert"] }), onRefine && (_jsxs(Button, { size: "sm", variant: "ghost", onClick: handleRefine, className: "text-highlight-100 hover:bg-highlight-10 h-7 gap-1 px-2 text-xs", title: "Refine edit", children: [_jsx(Wand2, { className: "h-3.5 w-3.5", strokeWidth: 2 }), "Refine"] }))] }), _jsxs("div", { className: "rounded-badge bg-feedback-green badge-pad-sm text-2xs pointer-events-none absolute bottom-2 left-2 flex items-center gap-1 font-medium text-white shadow-sm", children: [_jsx(Check, { className: "h-3 w-3", strokeWidth: 2 }), "AI Edited"] })] }));
}
export default AiImageResultOverlay;
//# sourceMappingURL=AiImageResultOverlay.js.map