import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useEffect, useRef, useCallback, useMemo, forwardRef, useImperativeHandle, } from "react";
import { Dialog, DialogContent } from "../../components/ui/dialog";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Button } from "../../components/ui/button";
import { Textarea } from "../../components/ui/textarea";
import DialogButtons from "../ui/DialogButtons";
import { Popover, PopoverContent, PopoverTrigger, } from "../../components/ui/popover";
import { X, Upload, Loader2, Wand2, Image as ImageIcon, FolderOpen, Sparkles, Search, } from "lucide-react";
import { useEditContext } from "../client/editContext";
import { closeAgent, startSuggestionAgent, awaitAgentResponse, } from "../services/agentService";
import { startImageJob } from "../services/editService";
import ContentTree from "../ContentTree";
import { getComponentById } from "../componentTreeHelper";
import { Lightbulb } from "lucide-react";
/**
 * Extracts the suggestion content from a fenced code block with the 'suggestion' language tag.
 * Handles both complete fences and partial/streaming content where the closing fence hasn't arrived yet.
 * If no fenced block is found, returns an empty string to avoid showing raw fence markers.
 */
function extractSuggestionFromFence(content) {
    // First try to match a complete fence
    const completeFenceRegex = /```suggestion\s*\n([\s\S]*?)```/;
    const completeMatch = content.match(completeFenceRegex);
    if (completeMatch && completeMatch[1]) {
        return completeMatch[1].trim();
    }
    // During streaming: match an opening fence without closing backticks
    const partialFenceRegex = /```suggestion\s*\n([\s\S]*?)$/;
    const partialMatch = content.match(partialFenceRegex);
    if (partialMatch && partialMatch[1]) {
        return partialMatch[1].trim();
    }
    // No fence found at all - return empty to avoid showing preamble text
    return "";
}
export const AiImageEditorDialog = forwardRef(({ open, onClose, onComplete, fieldDescriptor, initialPrompt = "", originalRawValue, variantName, currentImageSrc, currentMediaItemId, }, ref) => {
    const editContext = useEditContext();
    // Agent state - created lazily on first image
    // Image state
    const [images, setImages] = useState([]);
    const [uploading, setUploading] = useState(false);
    const [browsingMedia, setBrowsingMedia] = useState(false);
    const initialImageLoadedRef = useRef(false);
    // Prompt state
    const [modifyPrompt, setModifyPrompt] = useState(initialPrompt);
    const [generatePrompt, setGeneratePrompt] = useState("");
    // Suggestion state
    const [suggesting, setSuggesting] = useState(false);
    // Submission state
    const [submitting, setSubmitting] = useState(false);
    const [error, setError] = useState(null);
    // Target folder state (required)
    const [targetFolderId, setTargetFolderId] = useState(null);
    const [targetFolderName, setTargetFolderName] = useState("");
    const [targetFolderPath, setTargetFolderPath] = useState("");
    const [targetFolderExpandIdPath, setTargetFolderExpandIdPath] = useState(undefined);
    const [targetFolderPickerOpen, setTargetFolderPickerOpen] = useState(false);
    const folderPickerRootItemIds = useMemo(() => ["3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1"], []);
    const folderPickerTemplateIds = useMemo(() => ["FE5DD826-48C6-436D-B87A-7C4210C7413B"], []);
    const folderPickerSelectedItemIds = useMemo(() => (targetFolderId ? [targetFolderId] : []), [targetFolderId]);
    // Refs
    const fileInputRef = useRef(null);
    const dropZoneRef = useRef(null);
    const [isDragOver, setIsDragOver] = useState(false);
    // Expose agentId to parent via ref (no longer used for image jobs)
    useImperativeHandle(ref, () => ({
        getAgentId: () => null,
    }));
    // Add image files to local dialog state (no backend upload here)
    const handleFileUpload = useCallback((files) => {
        if (!files || files.length === 0)
            return;
        setError(null);
        const fileList = Array.from(files);
        const maxSizeMB = 10;
        const maxSizeBytes = maxSizeMB * 1024 * 1024;
        for (const file of fileList) {
            if (!file.type.startsWith("image/")) {
                setError(`File "${file.name}" is not an image`);
                continue;
            }
            if (file.size > maxSizeBytes) {
                setError(`File "${file.name}" exceeds maximum allowed size of ${maxSizeMB} MB`);
                continue;
            }
            const id = crypto.randomUUID();
            const thumbnailUrl = URL.createObjectURL(file);
            setImages((prev) => [
                ...prev,
                { id, fileName: file.name, thumbnailUrl, loading: false, file },
            ]);
        }
    }, []);
    // Browse media library
    const handleBrowseMedia = useCallback(async () => {
        if (!editContext?.selectMedia)
            return;
        setBrowsingMedia(true);
        setError(null);
        try {
            // Open media selector
            const mediaId = await editContext.selectMedia({
                selectedIdPath: "",
                mode: "images",
            });
            if (!mediaId) {
                setBrowsingMedia(false);
                return;
            }
            // Fetch media URL from server
            const urlResponse = await fetch(`/parhelia/agent/GetMediaUrl?itemId=${encodeURIComponent(mediaId)}`);
            if (!urlResponse.ok)
                throw new Error("Failed to get media URL");
            const { url } = await urlResponse.json();
            // Fetch the actual image blob
            const imageResponse = await fetch(url);
            if (!imageResponse.ok)
                throw new Error("Failed to fetch image");
            const blob = await imageResponse.blob();
            // Create a File object
            const pathParts = mediaId.split("/");
            const rawName = pathParts[pathParts.length - 1] || "media-image";
            const cleanName = rawName.replace(/[^a-zA-Z0-9_-]/g, "_");
            const extension = blob.type.split("/")[1] || "jpg";
            const file = new File([blob], `${cleanName}.${extension}`, {
                type: blob.type,
            });
            handleFileUpload([file]);
        }
        catch (err) {
            console.error("Failed to add media library image", err);
            setError("Failed to add image from media library");
        }
        finally {
            setBrowsingMedia(false);
        }
    }, [editContext, handleFileUpload]);
    // Search media library with generated description
    const handleSearchMedia = useCallback(async () => {
        if (!editContext?.selectMedia || !generatePrompt.trim())
            return;
        setBrowsingMedia(true);
        setError(null);
        try {
            // Open media selector with search term
            const mediaId = await editContext.selectMedia({
                selectedIdPath: "",
                mode: "images",
                initialSearchTerm: generatePrompt.trim(),
            });
            if (!mediaId) {
                setBrowsingMedia(false);
                return;
            }
            // Fetch media URL from server
            const urlResponse = await fetch(`/parhelia/agent/GetMediaUrl?itemId=${encodeURIComponent(mediaId)}`);
            if (!urlResponse.ok)
                throw new Error("Failed to get media URL");
            const { url } = await urlResponse.json();
            // Fetch the actual image blob
            const imageResponse = await fetch(url);
            if (!imageResponse.ok)
                throw new Error("Failed to fetch image");
            const blob = await imageResponse.blob();
            // Create a File object
            const pathParts = mediaId.split("/");
            const rawName = pathParts[pathParts.length - 1] || "media-image";
            const cleanName = rawName.replace(/[^a-zA-Z0-9_-]/g, "_");
            const extension = blob.type.split("/")[1] || "jpg";
            const file = new File([blob], `${cleanName}.${extension}`, {
                type: blob.type,
            });
            handleFileUpload([file]);
        }
        catch (err) {
            console.error("Failed to add media library image", err);
            setError("Failed to add image from media library");
        }
        finally {
            setBrowsingMedia(false);
        }
    }, [editContext, handleFileUpload, generatePrompt]);
    // Delete an uploaded image
    const handleDeleteImage = useCallback(async (imageId) => {
        setImages((prev) => {
            const img = prev.find((i) => i.id === imageId);
            if (img?.thumbnailUrl)
                URL.revokeObjectURL(img.thumbnailUrl);
            return prev.filter((i) => i.id !== imageId);
        });
    }, []);
    // Handle paste
    const handlePaste = useCallback((e) => {
        const items = e.clipboardData?.items;
        if (!items)
            return;
        const files = [];
        for (let i = 0; i < items.length; i++) {
            const item = items[i];
            if (!item)
                continue;
            if (item.type.indexOf("image") !== -1) {
                const file = item.getAsFile();
                if (file) {
                    const timestamp = new Date().toISOString().replace(/[:.]/g, "-");
                    const extension = item.type.split("/")[1] || "png";
                    const newFile = new File([file], `pasted-image-${timestamp}.${extension}`, { type: file.type });
                    files.push(newFile);
                }
            }
        }
        if (files.length > 0) {
            e.preventDefault();
            handleFileUpload(files);
        }
    }, [handleFileUpload]);
    // Drag and drop handlers
    const handleDragOver = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(true);
    }, []);
    const handleDragLeave = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
    }, []);
    const handleDrop = useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            // Filter to only image files
            const imageFiles = Array.from(e.dataTransfer.files).filter((f) => f.type.startsWith("image/"));
            if (imageFiles.length > 0) {
                handleFileUpload(imageFiles);
            }
        }
    }, [handleFileUpload]);
    const fileToBase64 = useCallback((file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => {
                const result = reader.result;
                if (typeof result !== "string")
                    return resolve("");
                const commaIdx = result.indexOf(",");
                resolve(commaIdx >= 0 ? result.slice(commaIdx + 1) : result);
            };
            reader.onerror = () => reject(reader.error || new Error("Failed to read file"));
            reader.readAsDataURL(file);
        });
    }, []);
    // Submit the prompt to start the backend image job (no agent)
    const handleSubmit = useCallback(async () => {
        const isModifyMode = images.length > 0;
        const activePrompt = isModifyMode ? modifyPrompt : generatePrompt;
        if (!activePrompt.trim())
            return;
        if (!fieldDescriptor) {
            setError("No field selected");
            return;
        }
        if (!editContext?.sessionId) {
            setError("Missing session");
            return;
        }
        if (!targetFolderId) {
            setError("Select a target folder first");
            return;
        }
        setSubmitting(true);
        setError(null);
        try {
            const sourceImages = isModifyMode
                ? await Promise.all(images.map(async (img) => {
                    if (!img.file)
                        throw new Error(`Missing image file: ${img.fileName}`);
                    return {
                        base64: await fileToBase64(img.file),
                        contentType: img.file.type,
                    };
                }))
                : undefined;
            const response = await startImageJob({
                prompt: activePrompt,
                itemId: fieldDescriptor.item.id,
                fieldId: fieldDescriptor.fieldId,
                language: fieldDescriptor.item.language,
                version: fieldDescriptor.item.version,
                variantName,
                pageItemId: editContext.page?.item?.id,
                targetFolderId,
                sourceImages,
            }, editContext.sessionId);
            if (response.type !== "success") {
                setError(response.summary || "Failed to start image job");
                setSubmitting(false);
                return;
            }
            onComplete({ success: true });
            onClose();
        }
        catch (err) {
            console.error("Failed to submit AI image job", err);
            setError(err?.message || "Failed to submit request");
            setSubmitting(false);
        }
    }, [
        images,
        modifyPrompt,
        generatePrompt,
        fieldDescriptor,
        variantName,
        editContext,
        fileToBase64,
        onComplete,
        onClose,
        targetFolderId,
    ]);
    // Handle suggesting a description based on context
    const handleSuggestDescription = useCallback(async () => {
        if (!fieldDescriptor || !editContext?.addSocketMessageListener)
            return;
        setSuggesting(true);
        setError(null);
        const newAgentId = crypto.randomUUID();
        try {
            // Find the component if possible to get more context
            const component = editContext.page
                ? getComponentById(fieldDescriptor.item.id, editContext.page)
                : undefined;
            // Build context payload
            const context = {
                field: {
                    fieldId: fieldDescriptor.fieldId,
                    fieldName: undefined,
                    item: fieldDescriptor.item,
                },
                additionalData: {
                    suggestDescription: true,
                    componentName: component?.name,
                    componentType: component?.type,
                    pageName: editContext.page?.item?.name,
                    pageId: editContext.page?.item?.id,
                },
            };
            // Start the suggestion agent
            await startSuggestionAgent({
                agentId: newAgentId,
                sessionId: editContext.sessionId,
                context,
            });
            // Await the response via WebSocket
            const result = await awaitAgentResponse({
                agentId: newAgentId,
                addSocketMessageListener: editContext.addSocketMessageListener,
                timeout: 60000,
                onContentUpdate: (content) => {
                    setGeneratePrompt(extractSuggestionFromFence(content));
                },
            });
            if (result.success) {
                setGeneratePrompt(extractSuggestionFromFence(result.content));
            }
            else {
                setError(result.error || "Failed to get suggestion");
            }
        }
        catch (err) {
            console.error("Failed to get AI suggestion", err);
            setError(err.message || "Failed to start suggestion agent");
        }
        finally {
            setSuggesting(false);
            // Close the suggestion agent
            try {
                await closeAgent(newAgentId);
            }
            catch (err) {
                console.error("Failed to close suggestion agent", err);
            }
        }
    }, [fieldDescriptor, editContext]);
    const handleCancel = useCallback(() => {
        // Clean up thumbnail URLs
        images.forEach((img) => {
            if (img.thumbnailUrl)
                URL.revokeObjectURL(img.thumbnailUrl);
        });
        onClose();
    }, [images, onClose]);
    // Clean up on unmount / images change
    useEffect(() => {
        return () => {
            images.forEach((img) => {
                if (img.thumbnailUrl)
                    URL.revokeObjectURL(img.thumbnailUrl);
            });
        };
    }, [images]);
    // Reset state when dialog closes
    useEffect(() => {
        if (!open) {
            initialImageLoadedRef.current = false;
            setBrowsingMedia(false);
        }
    }, [open]);
    // Initialize / default target folder when dialog opens
    useEffect(() => {
        if (!open)
            return;
        if (!editContext?.itemsRepository)
            return;
        let cancelled = false;
        (async () => {
            // 1) Edit mode: if we have a current media item id, default to its parent folder
            if (currentMediaItemId) {
                try {
                    const mediaItem = await editContext.itemsRepository.getItem({
                        id: currentMediaItemId,
                        language: fieldDescriptor?.item.language ?? "en",
                        version: 0,
                    });
                    const parentId = mediaItem?.parentId;
                    if (parentId && !cancelled) {
                        const folderItem = await editContext.itemsRepository.getItem({
                            id: parentId,
                            language: fieldDescriptor?.item.language ?? "en",
                            version: 0,
                        });
                        if (!cancelled) {
                            setTargetFolderId(parentId);
                            setTargetFolderName(folderItem?.name ?? "");
                            setTargetFolderPath(folderItem?.path ?? "");
                            setTargetFolderExpandIdPath(folderItem?.idPath);
                        }
                        return;
                    }
                }
                catch {
                    // ignore, fall through to preferences
                }
            }
            // 2) Otherwise: last saved folder from user preferences
            const prefId = editContext.userInfo?.preferences?.aiImageTargetFolderId;
            if (prefId && !cancelled) {
                try {
                    const folderItem = await editContext.itemsRepository.getItem({
                        id: prefId,
                        language: fieldDescriptor?.item.language ?? "en",
                        version: 0,
                    });
                    if (!cancelled) {
                        setTargetFolderId(prefId);
                        setTargetFolderName(folderItem?.name ?? "");
                        setTargetFolderPath(folderItem?.path ?? "");
                        setTargetFolderExpandIdPath(folderItem?.idPath);
                    }
                }
                catch {
                    // ignore
                }
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [open, editContext, currentMediaItemId, fieldDescriptor]);
    // Auto-load the current image from the field when dialog opens
    useEffect(() => {
        if (!open || initialImageLoadedRef.current)
            return;
        if (!currentImageSrc && !currentMediaItemId)
            return;
        // Mark as loaded immediately (sync) to prevent double execution
        initialImageLoadedRef.current = true;
        const loadCurrentImage = async () => {
            setUploading(true);
            setError(null);
            try {
                let imageBlob = null;
                let fileName = "current-image";
                if (currentMediaItemId) {
                    // Fetch via media item ID
                    const urlResponse = await fetch(`/parhelia/agent/GetMediaUrl?itemId=${encodeURIComponent(currentMediaItemId)}`);
                    if (urlResponse.ok) {
                        const { url, alt } = await urlResponse.json();
                        const imageResponse = await fetch(url);
                        if (imageResponse.ok) {
                            imageBlob = await imageResponse.blob();
                            // Extract name from media item ID path
                            const pathParts = currentMediaItemId.split("/");
                            fileName = pathParts[pathParts.length - 1] || "current-image";
                        }
                    }
                }
                else if (currentImageSrc) {
                    // Fetch directly from src URL
                    const imageResponse = await fetch(currentImageSrc);
                    if (imageResponse.ok) {
                        imageBlob = await imageResponse.blob();
                        // Extract filename from URL
                        const urlParts = currentImageSrc.split("/");
                        const lastPart = urlParts[urlParts.length - 1]?.split("?")[0];
                        fileName = lastPart || "current-image";
                    }
                }
                if (imageBlob) {
                    // Clean up filename
                    const cleanName = fileName.replace(/[^a-zA-Z0-9_.-]/g, "_");
                    const extension = imageBlob.type.split("/")[1] || "jpg";
                    const fullFileName = cleanName.includes(".")
                        ? cleanName
                        : `${cleanName}.${extension}`;
                    const file = new File([imageBlob], fullFileName, {
                        type: imageBlob.type,
                    });
                    handleFileUpload([file]);
                }
            }
            catch (err) {
                console.error("Failed to load current image", err);
                // Don't show error - the user can still add images manually
            }
            finally {
                setUploading(false);
            }
        };
        loadCurrentImage();
    }, [open, currentImageSrc, currentMediaItemId, handleFileUpload]);
    // Preset prompts for common operations
    const presetPrompts = [
        {
            label: "Enhance",
            prompt: "Enhance this image to improve quality and clarity",
        },
        {
            label: "Remove Background",
            prompt: "Remove the background from this image",
        },
        { label: "Upscale", prompt: "Upscale this image to higher resolution" },
        {
            label: "Fix Lighting",
            prompt: "Improve the lighting and color balance of this image",
        },
    ];
    const canSubmit = (images.length > 0 ? modifyPrompt.trim() : generatePrompt.trim()) &&
        !!targetFolderId &&
        !submitting &&
        !uploading;
    return (_jsx(Dialog, { open: open, onOpenChange: (isOpen) => !isOpen && handleCancel(), children: _jsxs(DialogContent, { className: "flex max-w-2xl flex-col overflow-hidden border-none p-0 shadow-2xl", style: { height: "auto", maxHeight: "90vh" }, onPaste: handlePaste, children: [_jsx(StyledDialogTitle, { icon: _jsx(Sparkles, { strokeWidth: 1.5 }), title: "AI Image Editor", subtitle: "Describe what you want to create, or upload images to modify" }), _jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-y-auto px-6 pb-4", children: _jsxs("div", { className: "flex flex-col gap-4 pt-6", children: [error && (_jsx("div", { className: "border-feedback-red bg-feedback-red-light text-feedback-red rounded border p-3 text-sm", children: error })), images.length === 0 && (_jsxs("div", { className: "border-highlight-100/50 bg-highlight-100/5 ring-highlight-100/20 space-y-3 rounded-xl border p-4 shadow-sm ring-1", children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Wand2, { className: "text-highlight-100 h-4 w-4" }), _jsx("span", { className: "text-highlight-100 text-sm font-semibold", children: "Generate New Image" })] }), fieldDescriptor && (_jsxs(Button, { variant: "ghost", size: "sm", className: "text-highlight-100 hover:bg-highlight-10 hover:text-highlight-100 h-7 gap-1.5 px-2 text-xs", onClick: (e) => {
                                                    e.stopPropagation();
                                                    handleSuggestDescription();
                                                }, disabled: suggesting || submitting, children: [suggesting ? (_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" })) : (_jsx(Lightbulb, { className: "h-3.5 w-3.5" })), suggesting ? "Suggesting..." : "Suggest"] }))] }), _jsx(Textarea, { value: generatePrompt, onChange: (e) => setGeneratePrompt(e.target.value), placeholder: "Describe the image you want to create...", className: "min-h-[80px] resize-none border-none bg-transparent p-0 focus-visible:ring-0", disabled: submitting })] })), _jsxs("div", { ref: dropZoneRef, onDragOver: handleDragOver, onDragEnter: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, className: `relative rounded-lg border-2 border-dashed p-4 transition-colors ${isDragOver
                                    ? "border-highlight-100 bg-highlight-10"
                                    : "border-border-default bg-neutral-grey-5/50"}`, children: [images.length > 0 && (_jsx("div", { className: "mb-4 flex flex-wrap gap-3", children: images.map((img) => (_jsxs("div", { className: "group border-border-default relative h-20 w-20 overflow-hidden rounded-lg border bg-white", children: [img.loading ? (_jsx("div", { className: "flex h-full w-full items-center justify-center", children: _jsx(Loader2, { className: "text-neutral-grey-50 h-6 w-6 animate-spin", strokeWidth: 1 }) })) : img.thumbnailUrl ? (_jsx("img", { src: img.thumbnailUrl, alt: img.fileName, className: "h-full w-full object-cover" })) : (_jsx("div", { className: "flex h-full w-full items-center justify-center", children: _jsx(ImageIcon, { className: "text-neutral-grey-50 h-8 w-8", strokeWidth: 1 }) })), _jsx("button", { onClick: () => handleDeleteImage(img.id), className: "bg-neutral-grey-100/50 absolute top-1 right-1 rounded-full p-1 opacity-0 transition-opacity group-hover:opacity-100", title: "Remove image", children: _jsx(X, { className: "h-3 w-3 text-white", strokeWidth: 2 }) }), _jsx("div", { className: "bg-neutral-grey-100/50 absolute inset-x-0 bottom-0 truncate px-1 py-0.5 text-[10px] text-white", children: img.fileName })] }, img.id))) })), _jsxs("div", { className: "flex items-center justify-between gap-4", children: [_jsx("div", { className: "text-neutral-grey-50 text-sm", children: isDragOver
                                                    ? "Drop images here"
                                                    : images.length === 0
                                                        ? "Or, drag & drop images here to modify:"
                                                        : "Modify these images, or add more:" }), _jsxs("div", { className: "flex gap-2", children: [_jsxs(Button, { variant: "outline", size: "sm", className: "h-8 px-3 text-xs", onClick: () => fileInputRef.current?.click(), disabled: uploading, children: [uploading ? (_jsx(Loader2, { className: "mr-1 h-3.5 w-3.5 animate-spin", strokeWidth: 1 })) : (_jsx(Upload, { className: "mr-1 h-3.5 w-3.5", strokeWidth: 1 })), "Browse"] }), editContext?.selectMedia && (_jsxs(_Fragment, { children: [_jsxs(Button, { variant: "outline", size: "sm", className: "h-8 px-3 text-xs", onClick: handleBrowseMedia, disabled: browsingMedia, children: [_jsx(FolderOpen, { className: "mr-1 h-3.5 w-3.5", strokeWidth: 1 }), "Media"] }), images.length === 0 && generatePrompt.trim() && (_jsxs(Button, { variant: "outline", size: "sm", className: "h-8 px-3 text-xs", onClick: handleSearchMedia, disabled: browsingMedia, children: [_jsx(Search, { className: "mr-1 h-3.5 w-3.5", strokeWidth: 1 }), "Search"] }))] }))] }), _jsx("input", { ref: fileInputRef, type: "file", className: "hidden", accept: "image/*", multiple: true, onChange: (e) => {
                                                    const files = e.target.files
                                                        ? Array.from(e.target.files)
                                                        : null;
                                                    e.target.value = "";
                                                    handleFileUpload(files);
                                                } })] })] }), images.length > 0 && (_jsxs("div", { className: "border-highlight-100/50 bg-highlight-100/5 ring-highlight-100/20 space-y-3 rounded-xl border p-4 shadow-sm ring-1", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Sparkles, { className: "text-highlight-100 h-4 w-4" }), _jsx("span", { className: "text-highlight-100 text-sm font-semibold", children: "Enhance & Modify" })] }), _jsx(Textarea, { value: modifyPrompt, onChange: (e) => setModifyPrompt(e.target.value), placeholder: "E.g., Remove the background, improve lighting, upscale...", className: "min-h-[80px] resize-none border-none bg-transparent p-0 focus-visible:ring-0", disabled: submitting }), _jsx("div", { className: "mt-2 flex flex-wrap gap-1", children: presetPrompts.map((preset) => (_jsx("button", { onClick: (e) => {
                                                e.stopPropagation();
                                                setModifyPrompt(preset.prompt);
                                            }, className: `rounded-badge badge-pad-sm text-2xs border transition-colors ${modifyPrompt === preset.prompt
                                                ? "border-highlight-100 bg-highlight-100 text-white"
                                                : "border-border-default text-neutral-grey-50 hover:border-highlight-100 hover:text-highlight-100 bg-white"}`, disabled: submitting, children: preset.label }, preset.label))) })] })), _jsxs("div", { className: "border-border-default rounded-xl border bg-white p-4 shadow-sm", children: [_jsxs("div", { className: "flex items-start justify-between gap-3", children: [_jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("div", { className: "text-neutral-grey-100 text-sm font-semibold", children: "Target folder" }), targetFolderPath ? (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 truncate text-xs", title: targetFolderPath, children: targetFolderPath })) : (_jsx("div", { className: "text-neutral-grey-50 mt-0.5 text-xs", children: "Select where the generated image will be saved" }))] }), _jsxs(Popover, { open: targetFolderPickerOpen, onOpenChange: setTargetFolderPickerOpen, enableIframeClickDetection: false, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { variant: "outline", size: "sm", className: "h-8 shrink-0 gap-2 px-3 text-xs", children: [_jsx(FolderOpen, { className: "h-3.5 w-3.5", strokeWidth: 1 }), targetFolderId ? "Change" : "Select"] }) }), _jsx(PopoverContent, { className: "pointer-events-auto z-[110] w-[520px] p-2", align: "end", children: _jsx("div", { className: "h-[360px] overflow-hidden rounded border", children: _jsx(ContentTree, { rootItemIds: folderPickerRootItemIds, selectionMode: "single", selectedItemIds: folderPickerSelectedItemIds, templateIds: folderPickerTemplateIds, hideRootNodes: true, expandIdPath: targetFolderExpandIdPath ??
                                                                    "3D6658D8-A0BF-4E75-B3E2-D050FABCF4E1", onSelectionChange: (selection) => {
                                                                    const node = selection[0];
                                                                    if (!node?.id)
                                                                        return;
                                                                    setTargetFolderId(node.id);
                                                                    setTargetFolderName(node.displayName || node.name || "");
                                                                    setTargetFolderPath(node.path || "");
                                                                    setTargetFolderExpandIdPath(node.idPath);
                                                                    editContext?.setUserPreferences?.({
                                                                        aiImageTargetFolderId: node.id,
                                                                    });
                                                                    setTargetFolderPickerOpen(false);
                                                                }, language: fieldDescriptor?.item.language ?? "en", includeItemPath: false, database: "master" }) }) })] })] }), !targetFolderId && (_jsx("div", { className: "text-feedback-orange mt-2 text-xs", children: "Select a target folder to enable generation." }))] })] }) }), _jsxs(DialogButtons, { className: "bg-neutral-grey-5/50", children: [_jsx(Button, { variant: "ghost", onClick: handleCancel, disabled: submitting, children: "Cancel" }), _jsx(Button, { onClick: handleSubmit, disabled: !canSubmit, className: "min-w-[100px] gap-1", children: submitting ? (_jsxs(_Fragment, { children: [_jsx(Loader2, { className: "h-4 w-4 animate-spin", strokeWidth: 1 }), "Generating..."] })) : (_jsxs(_Fragment, { children: [_jsx(Wand2, { className: "h-4 w-4", strokeWidth: 1 }), "Generate"] })) })] })] }) }));
});
AiImageEditorDialog.displayName = "AiImageEditorDialog";
export default AiImageEditorDialog;
//# sourceMappingURL=AiImageEditorDialog.js.map