'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useId, useState, useRef } from 'react';
import * as Dialog from '@radix-ui/react-dialog';
import { X, Upload, Search, ImageIcon, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../lib/api.js';
import { adminPortalContainer } from '../lib/portal-container.js';
import { useApiData } from '../lib/useApiData.js';
export function MediaPickerModal({ open, onClose, onSelect, onSelectItem, accept, libraryOnly = false, }) {
    const [tab, setTab] = useState('library');
    const [search, setSearch] = useState('');
    const [uploading, setUploading] = useState(false);
    const fileInputRef = useRef(null);
    const searchId = useId();
    const { data, loading, refetch } = useApiData(open ? `/media?pageSize=50${search ? `&search=${encodeURIComponent(search)}` : ''}` : null);
    const items = data?.data?.items ?? data?.items ?? [];
    const imageItems = items.filter((item) => item.mimeType.startsWith('image/'));
    async function handleUpload(files) {
        if (!files || files.length === 0)
            return;
        setUploading(true);
        const file = files[0];
        const formData = new FormData();
        formData.append('file', file);
        const res = await cmsApi('/media/upload', {
            method: 'POST',
            body: formData,
        });
        if (res.error) {
            toast.error(res.error);
        }
        else if (res.data) {
            const mediaItem = res.data;
            const url = mediaItem.url || mediaItem.storageKey || '';
            toast.success(`Uploaded ${file.name}`);
            onSelectItem?.({
                id: mediaItem.id,
                storageKey: mediaItem.storageKey,
                url,
                filename: mediaItem.filename ?? file.name,
                mimeType: mediaItem.mimeType ?? file.type,
                width: mediaItem.width,
                height: mediaItem.height,
            });
            onSelect(url, file.name);
            onClose();
        }
        setUploading(false);
        if (fileInputRef.current)
            fileInputRef.current.value = '';
    }
    function handleSelectItem(item) {
        const url = item.url || item.storageKey || '';
        onSelectItem?.({
            id: item.id,
            storageKey: item.storageKey,
            url,
            filename: item.filename,
            mimeType: item.mimeType,
            width: item.width,
            height: item.height,
        });
        // Prefer the asset's curated alt text from the library so inserted images
        // carry meaningful alt instead of a filename. Callers can still override.
        onSelect(url, item.altTag?.trim() || item.filename);
        onClose();
    }
    return (_jsx(Dialog.Root, { open: open, onOpenChange: (next) => !next && onClose(), children: _jsxs(Dialog.Portal, { container: adminPortalContainer(), children: [_jsx(Dialog.Overlay, { className: "fixed inset-0 z-70 bg-black/40" }), _jsxs(Dialog.Content, { "aria-describedby": undefined, className: "bg-card text-card-foreground border-border fixed top-1/2 left-1/2 z-70 mx-4 flex max-h-[80vh] w-[calc(100%-2rem)] max-w-2xl -translate-x-1/2 -translate-y-1/2 flex-col rounded-xl border shadow-2xl focus:outline-none", children: [_jsxs("div", { className: "border-border flex items-center justify-between border-b px-6 py-4", children: [_jsx(Dialog.Title, { className: "text-foreground text-lg font-medium", children: "Insert Image" }), _jsx(Dialog.Close, { asChild: true, children: _jsx("button", { type: "button", "aria-label": "Close media picker", className: "text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring rounded-lg p-1.5 transition-colors focus-visible:ring-2 focus-visible:outline-none", children: _jsx(X, { className: "h-5 w-5", "aria-hidden": true }) }) })] }), !libraryOnly && (_jsxs("div", { className: "border-border flex border-b", role: "tablist", "aria-label": "Image source", children: [_jsx("button", { type: "button", role: "tab", "aria-selected": tab === 'library', onClick: () => setTab('library'), className: `flex-1 px-4 py-2.5 text-sm font-medium transition-colors ${tab === 'library'
                                        ? 'border-primary text-primary border-b-2'
                                        : 'text-muted-foreground hover:text-foreground'}`, children: "Media Library" }), _jsx("button", { type: "button", role: "tab", "aria-selected": tab === 'upload', onClick: () => setTab('upload'), className: `flex-1 px-4 py-2.5 text-sm font-medium transition-colors ${tab === 'upload'
                                        ? 'border-primary text-primary border-b-2'
                                        : 'text-muted-foreground hover:text-foreground'}`, children: "Upload New" })] })), _jsx("div", { className: "flex-1 overflow-y-auto p-4", children: libraryOnly || tab === 'library' ? (_jsxs(_Fragment, { children: [_jsxs("div", { className: "relative mb-4", children: [_jsx(Search, { className: "text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2", "aria-hidden": true }), _jsx("input", { id: searchId, type: "text", value: search, onChange: (e) => setSearch(e.target.value), placeholder: "Search images...", "aria-label": "Search images", className: "border-input bg-background text-foreground focus:ring-ring w-full rounded-lg border py-2 pr-3 pl-9 text-sm focus:ring-2 focus:outline-none" })] }), loading ? (_jsx("div", { className: "flex items-center justify-center py-12", children: _jsx(Loader2, { className: "text-muted-foreground h-6 w-6 animate-spin", "aria-hidden": true }) })) : imageItems.length === 0 ? (_jsx("div", { className: "text-muted-foreground py-12 text-center text-sm", children: "No images found. Try uploading one." })) : (_jsx("div", { className: "grid grid-cols-3 gap-3 sm:grid-cols-4", children: imageItems.map((item) => {
                                            const src = item.url || item.storageKey;
                                            return (_jsxs("button", { type: "button", onClick: () => handleSelectItem(item), title: item.filename, className: "group border-border bg-muted hover:border-primary relative aspect-square overflow-hidden rounded-lg border-2 transition-colors", children: [src ? (_jsx("img", { src: src, alt: item.filename, loading: "lazy", className: "h-full w-full object-contain" })) : (_jsx("div", { className: "flex h-full w-full items-center justify-center", children: _jsx(ImageIcon, { className: "text-muted-foreground h-8 w-8", "aria-hidden": true }) })), _jsx("div", { className: "absolute inset-x-0 bottom-0 bg-black/60 p-1.5 opacity-0 transition-opacity group-hover:opacity-100", children: _jsx("p", { className: "truncate text-xs text-white", children: item.filename }) })] }, item.id));
                                        }) }))] })) : (_jsxs("div", { className: "flex flex-col items-center justify-center py-12", children: [_jsx("input", { ref: fileInputRef, type: "file", accept: accept ?? 'image/*', className: "hidden", onChange: (e) => handleUpload(e.target.files) }), _jsx("div", { className: "bg-primary/10 mb-4 flex h-16 w-16 items-center justify-center rounded-full", children: uploading ? (_jsx(Loader2, { className: "text-primary h-8 w-8 animate-spin", "aria-hidden": true })) : (_jsx(Upload, { className: "text-primary h-8 w-8", "aria-hidden": true })) }), _jsx("p", { className: "text-muted-foreground mb-4 text-sm", children: uploading ? 'Uploading...' : 'Select an image file to upload' }), !uploading && (_jsx("button", { type: "button", onClick: () => fileInputRef.current?.click(), className: "bg-primary text-primary-foreground rounded-lg px-4 py-2 text-sm transition-opacity hover:opacity-90", children: "Choose File" }))] })) })] })] }) }));
}
//# sourceMappingURL=MediaPickerModal.js.map