'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Upload, Grid3x3, List, Search, Trash2, Download, ArrowUpDown, ArrowUp, ArrowDown, X, Bot, Sparkles, Link2, AlertTriangle, Copy, ExternalLink, ImageIcon, FileImage, Loader2, FolderInput, GripVertical, } from 'lucide-react';
import { useState, useMemo, useRef, useCallback } from 'react';
import { toast } from 'sonner';
import { sortByRelevance, toggleSort } from '../lib/search.js';
import { useApiData } from '../lib/useApiData.js';
import { cmsApi } from '../lib/api.js';
import { FolderTree } from '../components/FolderTree.js';
function isImageMedia(item) {
    return (Boolean(item.url) &&
        (item.type?.startsWith('image/') || /\.(avif|gif|jpe?g|png|webp|svg)$/i.test(item.url)));
}
function matchesMediaType(item, filterType) {
    if (filterType === 'all')
        return true;
    if (filterType === 'image')
        return item.type?.startsWith('image/') || isImageMedia(item);
    if (filterType === 'video')
        return item.type?.startsWith('video/');
    if (filterType === 'document')
        return !item.type?.startsWith('image/') && !item.type?.startsWith('video/');
    return item.type === filterType;
}
function MediaPreview({ item }) {
    if (isImageMedia(item)) {
        return (_jsx("img", { src: item.url, alt: item.altTag || item.title || item.name || 'Media preview', className: "h-full w-full object-cover", loading: "lazy" }));
    }
    return _jsx(FileImage, { className: "text-muted-foreground h-6 w-6 sm:h-8 sm:w-8" });
}
function buildMediaApiUrl(folderSel) {
    const base = '/media?pageSize=100';
    if (folderSel.type === 'smart') {
        if (folderSel.smart === 'recent')
            return `${base}&sort=updatedAt&order=desc&pageSize=20`;
        if (folderSel.smart === 'uncategorized')
            return `${base}&folderId=none`;
        return base;
    }
    return `${base}&folderId=${folderSel.folderId}`;
}
export function MediaBrowser({ onNavigate }) {
    const [folderSel, setFolderSel] = useState({ type: 'smart', smart: 'all' });
    const [sidebarOpen, setSidebarOpen] = useState(true);
    const apiUrl = useMemo(() => buildMediaApiUrl(folderSel), [folderSel]);
    const { data, loading, error, refetch } = useApiData(apiUrl);
    const allData = useApiData('/media?pageSize=1');
    const uncatData = useApiData('/media?pageSize=1&folderId=none');
    const [viewMode, setViewMode] = useState('grid');
    const [searchQuery, setSearchQuery] = useState('');
    const [filterType, setFilterType] = useState('all');
    const [selectedMedia, setSelectedMedia] = useState([]);
    const [sortConfig, setSortConfig] = useState(null);
    const [activeItem, setActiveItem] = useState(null);
    const [editAlt, setEditAlt] = useState('');
    const [editTitle, setEditTitle] = useState('');
    const [editFilename, setEditFilename] = useState('');
    const [saving, setSaving] = useState(false);
    const [aiGenerating, setAiGenerating] = useState(null);
    const [uploading, setUploading] = useState(false);
    const fileInputRef = useRef(null);
    const mediaItems = data?.data ?? data?.items ?? [];
    const filteredAndSorted = useMemo(() => {
        let results = mediaItems.filter((item) => {
            const matchesSearch = (item.name ?? '').toLowerCase().includes(searchQuery.toLowerCase());
            const matchesType = matchesMediaType(item, filterType);
            return matchesSearch && matchesType;
        });
        if (searchQuery.trim()) {
            results = sortByRelevance(results, searchQuery, (m) => [m.name]);
        }
        else if (sortConfig) {
            results = [...results].sort((a, b) => {
                let cmp;
                if (sortConfig.key === 'size') {
                    cmp = a.sizeBytes - b.sizeBytes;
                }
                else {
                    cmp = String(a[sortConfig.key]).localeCompare(String(b[sortConfig.key]));
                }
                return sortConfig.direction === 'asc' ? cmp : -cmp;
            });
        }
        return results;
    }, [mediaItems, searchQuery, filterType, sortConfig]);
    const openDetail = (item) => {
        setActiveItem(item);
        setEditAlt(item.altTag ?? '');
        setEditTitle(item.title ?? '');
        setEditFilename(item.name);
    };
    const closeDetail = () => {
        setActiveItem(null);
    };
    const handleCheckbox = (e, id) => {
        e.stopPropagation();
        setSelectedMedia((prev) => prev.includes(id) ? prev.filter((item) => item !== id) : [...prev, id]);
    };
    const handleSelectAll = () => {
        setSelectedMedia((prev) => prev.length === filteredAndSorted.length ? [] : filteredAndSorted.map((item) => item.id));
    };
    const handleSaveDetails = async () => {
        if (!activeItem)
            return;
        setSaving(true);
        const res = await cmsApi(`/media/${activeItem.id}`, {
            method: 'PUT',
            body: JSON.stringify({
                alt: editAlt,
                title: editTitle,
                filename: editFilename,
            }),
        });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Media details saved');
            refetch();
        }
    };
    const deleteMedia = async (id) => {
        const res = await cmsApi(`/media/${id}`, { method: 'DELETE' });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success('Media deleted');
            if (activeItem?.id === id)
                closeDetail();
            refetch();
        }
    };
    const handleAiGenerate = async (field) => {
        setAiGenerating(field);
        if (field === 'optimize' && activeItem) {
            const res = await cmsApi(`/media/${activeItem.id}/optimize`, { method: 'POST' });
            if (res.error) {
                toast.error(res.error);
            }
            else if (res.data?.optimization?.alreadyOptimized) {
                toast.info('Image is already in WebP format — no further optimization needed');
            }
            else if (res.data?.optimization) {
                const opt = res.data.optimization;
                toast.success(`Optimized: ${opt.originalSizeFormatted} → ${opt.optimizedSizeFormatted} (${opt.savings}% smaller)`);
                refetch();
            }
            setAiGenerating(null);
            return;
        }
        if (!activeItem) {
            setAiGenerating(null);
            return;
        }
        const res = await cmsApi('/ai/media-metadata', { method: 'POST', body: JSON.stringify({ mediaId: activeItem.id }) });
        if (res.error) {
            // AI plugin/provider not configured (e.g. local dev): fall back to a
            // basic filename-derived suggestion so the action still helps.
            const base = (activeItem.name ?? '')
                .replace(/\.\w+$/, '')
                .replace(/[-_]/g, ' ')
                .trim();
            if (field === 'alt') {
                setEditAlt(base ? `Image of ${base}` : '');
            }
            else {
                setEditTitle(base.replace(/\b\w/g, (c) => c.toUpperCase()));
            }
            toast.info('AI unavailable — generated a basic suggestion from the filename');
            setAiGenerating(null);
            return;
        }
        if (field === 'alt') {
            setEditAlt(res.data?.alt ?? '');
            toast.success('Alt tag generated by AI');
        }
        else {
            setEditTitle(res.data?.title ?? '');
            toast.success('Title generated by AI');
        }
        setAiGenerating(null);
    };
    const handleCopyUrl = () => {
        if (activeItem?.url) {
            navigator.clipboard.writeText(activeItem.url);
            toast.success('URL copied to clipboard');
        }
    };
    const handleUploadFiles = async (files) => {
        if (!files || files.length === 0)
            return;
        setUploading(true);
        let successCount = 0;
        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const formData = new FormData();
            formData.append('file', file);
            const res = await cmsApi('/media/upload', { method: 'POST', body: formData });
            if (res.error) {
                toast.error(`Failed to upload ${file.name}: ${res.error}`);
            }
            else {
                const opt = res.data?.optimization;
                if (opt && opt.savings > 0) {
                    toast.success(`${file.name} → WebP (${opt.originalSizeFormatted} → ${opt.optimizedSizeFormatted}, ${opt.savings}% saved)`);
                }
                else {
                    toast.success(`Uploaded ${file.name}`);
                }
                successCount++;
            }
        }
        if (successCount > 0)
            refetch();
        if (fileInputRef.current)
            fileInputRef.current.value = '';
        setUploading(false);
    };
    const handleDropItem = useCallback(async (itemId, folderId) => {
        const res = await cmsApi(`/media/${itemId}/folder`, {
            method: 'PUT',
            body: JSON.stringify({ folderId }),
        });
        if (res.error) {
            toast.error(res.error);
        }
        else {
            toast.success(folderId ? 'Moved to folder' : 'Removed from folder');
            refetch();
        }
    }, [refetch]);
    const handleDragStart = (e, id) => {
        e.dataTransfer.setData('text/actuate-item-id', String(id));
        e.dataTransfer.effectAllowed = 'move';
    };
    const panelOpen = activeItem !== null;
    const issues = activeItem
        ? [
            ...(!activeItem.altTag ? ['Missing alt tag'] : []),
            ...(!activeItem.title ? ['Missing title'] : []),
            ...(activeItem.sizeBytes > 2000000 ? ['File size over 2 MB — consider optimizing'] : []),
            ...(activeItem.usedOn?.length === 0 ? ['Not used on any page'] : []),
        ]
        : [];
    function SortHeader({ label, sortKey }) {
        const active = sortConfig?.key === sortKey;
        return (_jsxs("button", { type: "button", onClick: () => setSortConfig(toggleSort(sortConfig, sortKey)), className: "text-foreground hover:text-foreground flex items-center gap-1 text-xs font-medium transition-colors", children: [label, active ? (sortConfig.direction === 'asc' ? (_jsx(ArrowUp, { className: "h-3 w-3" })) : (_jsx(ArrowDown, { className: "h-3 w-3" }))) : (_jsx(ArrowUpDown, { className: "text-muted-foreground h-3 w-3" }))] }));
    }
    if (loading) {
        return (_jsx("div", { className: "flex h-64 items-center justify-center p-3 pr-6 sm:p-4 sm:pr-8", children: _jsx(Loader2, { className: "text-primary h-6 w-6 animate-spin" }) }));
    }
    return (_jsxs("div", { className: "flex h-full flex-col p-3 pr-6 sm:p-4 sm:pr-8", children: [error && (_jsxs("div", { className: "border-destructive/30 bg-destructive/10 mb-4 flex items-center gap-3 rounded-lg border p-3", children: [_jsx(AlertTriangle, { className: "text-destructive h-5 w-5 shrink-0" }), _jsx("span", { className: "text-destructive flex-1 text-sm", children: error }), _jsx("button", { onClick: refetch, className: "border-destructive/40 text-destructive hover:bg-destructive/15 rounded-lg border px-3 py-1 text-sm transition-colors", children: "Retry" })] })), _jsxs("div", { className: "mb-4 flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("button", { type: "button", onClick: () => setSidebarOpen((prev) => !prev), className: "hover:bg-muted rounded-lg p-1.5 transition-colors", title: sidebarOpen ? 'Hide folders' : 'Show folders', children: _jsx(FolderInput, { className: "text-muted-foreground h-5 w-5" }) }), _jsxs("div", { children: [_jsx("h1", { className: "text-foreground mb-1 text-xl font-medium sm:text-2xl", children: "Media Library" }), _jsxs("p", { className: "text-muted-foreground text-sm", children: [filteredAndSorted.length, " files"] })] })] }), _jsxs("div", { children: [_jsx("input", { ref: fileInputRef, type: "file", multiple: true, accept: "image/*,video/*,application/pdf,.doc,.docx,.xls,.xlsx", className: "hidden", onChange: (e) => handleUploadFiles(e.target.files) }), _jsxs("button", { onClick: () => fileInputRef.current?.click(), disabled: uploading, className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors disabled:opacity-50", children: [uploading ? (_jsx(Loader2, { className: "h-4 w-4 animate-spin" })) : (_jsx(Upload, { className: "h-4 w-4" })), uploading ? 'Uploading...' : 'Upload Files'] })] })] }), _jsxs("div", { className: "flex min-h-0 flex-1 gap-4 overflow-hidden", children: [sidebarOpen && (_jsx("div", { className: "border-border bg-card flex w-56 shrink-0 flex-col overflow-hidden rounded-lg border", children: _jsx(FolderTree, { scope: "media", selected: folderSel, onSelect: (sel) => {
                                setFolderSel(sel);
                                setSelectedMedia([]);
                            }, totalCount: allData.data?.total, uncategorizedCount: uncatData.data?.total, onDropItem: handleDropItem }) })), _jsxs("div", { className: "flex min-w-0 flex-1 flex-col", children: [_jsx("div", { className: "border-border bg-card mb-4 rounded-lg border", children: _jsxs("div", { className: "flex items-center justify-between p-3", children: [_jsxs("div", { className: "flex flex-1 items-center gap-3", children: [_jsxs("div", { className: "relative max-w-md flex-1", children: [_jsx(Search, { className: "text-muted-foreground absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2" }), _jsx("input", { type: "text", placeholder: "Search media...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: "border-input focus:ring-ring w-full rounded-lg border py-2 pr-3 pl-9 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("select", { value: filterType, onChange: (e) => setFilterType(e.target.value), className: "border-input focus:ring-ring rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", children: [_jsx("option", { value: "all", children: "All Types" }), _jsx("option", { value: "image", children: "Images" }), _jsx("option", { value: "video", children: "Videos" }), _jsx("option", { value: "document", children: "Documents" })] })] }), _jsxs("div", { className: "bg-muted flex items-center gap-1 rounded-lg p-1", children: [_jsx("button", { onClick: () => setViewMode('grid'), className: `rounded p-1.5 transition-colors ${viewMode === 'grid' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`, children: _jsx(Grid3x3, { className: "h-4 w-4" }) }), _jsx("button", { onClick: () => setViewMode('list'), className: `rounded p-1.5 transition-colors ${viewMode === 'list' ? 'bg-card text-foreground shadow-sm' : 'text-muted-foreground hover:text-foreground'}`, children: _jsx(List, { className: "h-4 w-4" }) })] })] }) }), selectedMedia.length > 0 && (_jsx("div", { className: "border-primary/30 bg-primary/10 mb-4 rounded-lg border p-3", children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("span", { className: "text-primary text-sm", children: [selectedMedia.length, " file", selectedMedia.length !== 1 ? 's' : '', " selected"] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { onClick: async () => {
                                                        for (const id of selectedMedia)
                                                            await deleteMedia(id);
                                                        setSelectedMedia([]);
                                                    }, className: "bg-destructive text-destructive-foreground hover:bg-destructive/90 rounded-lg px-3 py-1.5 text-sm transition-colors", children: "Delete Selected" }), _jsx("button", { onClick: () => setSelectedMedia([]), className: "border-input bg-card hover:bg-muted rounded-lg border px-3 py-1.5 text-sm transition-colors", children: "Cancel" })] })] }) })), filteredAndSorted.length === 0 && !loading ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-16 text-center", children: [_jsx("div", { className: "bg-muted mb-4 flex h-12 w-12 items-center justify-center rounded-full", children: _jsx(ImageIcon, { className: "text-muted-foreground h-6 w-6" }) }), _jsx("h3", { className: "text-foreground mb-1 text-sm font-medium", children: folderSel.type === 'smart' && folderSel.smart === 'uncategorized'
                                            ? 'No uncategorized media'
                                            : folderSel.type === 'folder'
                                                ? 'No media in this folder'
                                                : 'No media yet' }), _jsx("p", { className: "text-muted-foreground text-sm", children: "Upload your first file to get started." })] })) : (_jsxs("div", { className: "flex min-h-0 flex-1 gap-4 overflow-hidden", children: [_jsx("div", { className: `border-border bg-card overflow-hidden rounded-lg border transition-all duration-200 ${panelOpen ? 'min-w-0 flex-1' : 'w-full'}`, children: viewMode === 'grid' ? (_jsx("div", { className: `grid h-full auto-rows-min content-start gap-3 overflow-y-auto p-2 sm:gap-4 sm:p-3 ${panelOpen
                                                ? 'grid-cols-2 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4'
                                                : 'grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 2xl:grid-cols-8'}`, children: filteredAndSorted.map((item) => {
                                                const isActive = activeItem?.id === item.id;
                                                const hasIssues = !item.altTag || !item.title || item.usedOn?.length === 0;
                                                const typeLabel = (item.name.includes('.')
                                                    ? item.name.split('.').pop()
                                                    : item.format || item.type || '')
                                                    .replace(/^.*\//, '')
                                                    .toUpperCase();
                                                return (_jsxs("div", { className: `group relative flex cursor-pointer flex-col overflow-hidden rounded-lg border-2 transition-all ${isActive
                                                        ? 'border-primary ring-primary/30 ring-2'
                                                        : selectedMedia.includes(item.id)
                                                            ? 'border-primary/60 ring-primary/20 ring-1'
                                                            : 'border-border hover:border-input'}`, onClick: () => openDetail(item), draggable: true, onDragStart: (e) => handleDragStart(e, item.id), children: [_jsxs("div", { className: "relative aspect-square w-full overflow-hidden", children: [_jsx("div", { className: "bg-muted flex h-full w-full items-center justify-center", children: _jsx(MediaPreview, { item: item }) }), hasIssues && (_jsx("div", { className: "bg-warning absolute top-1.5 left-1.5 flex h-5 w-5 items-center justify-center rounded-full", title: "Needs attention", children: _jsx(AlertTriangle, { className: "text-warning-foreground h-3 w-3" }) })), _jsx("div", { className: "absolute top-1.5 right-1.5 opacity-0 transition-opacity group-hover:opacity-100", onClick: (e) => handleCheckbox(e, item.id), children: _jsx("div", { className: `flex h-5 w-5 items-center justify-center rounded border-2 transition-colors ${selectedMedia.includes(item.id)
                                                                            ? 'border-primary bg-primary'
                                                                            : 'border-input bg-card/80'}`, children: selectedMedia.includes(item.id) && (_jsx("svg", { className: "text-primary-foreground h-3 w-3", fill: "none", viewBox: "0 0 12 12", children: _jsx("path", { d: "M10 3L4.5 8.5L2 6", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }) })) }) })] }), _jsxs("div", { className: "border-border bg-card flex items-center gap-2 border-t px-2 py-1.5", children: [_jsx("span", { className: `mt-0.5 h-2 w-2 shrink-0 self-start rounded-full ${hasIssues ? 'bg-warning' : 'bg-success'}`, title: hasIssues ? 'Needs attention' : 'SEO complete' }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("p", { className: "text-foreground truncate text-xs font-medium", children: item.name }), _jsx("p", { className: "text-muted-foreground truncate text-xs", children: [typeLabel, item.size].filter(Boolean).join(' · ') })] })] })] }, item.id));
                                            }) })) : (_jsx("div", { className: "h-full overflow-y-auto", children: _jsxs("table", { className: "w-full", children: [_jsx("thead", { className: "border-border bg-muted sticky top-0 border-b", children: _jsxs("tr", { children: [_jsx("th", { className: "w-8 px-3 py-2 text-left", children: _jsx("input", { type: "checkbox", checked: selectedMedia.length === filteredAndSorted.length &&
                                                                            filteredAndSorted.length > 0, onChange: handleSelectAll, className: "border-input rounded" }) }), _jsx("th", { className: "w-6 px-1 py-2" }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Name", sortKey: "name" }) }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Type", sortKey: "type" }) }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Size", sortKey: "size" }) }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Uploaded", sortKey: "date" }) }), _jsx("th", { className: "text-foreground px-3 py-2 text-left text-xs font-medium", children: "Status" })] }) }), _jsx("tbody", { className: "divide-border divide-y", children: filteredAndSorted.map((item) => {
                                                            const isActive = activeItem?.id === item.id;
                                                            const hasIssues = !item.altTag || !item.title || item.usedOn?.length === 0;
                                                            return (_jsxs("tr", { className: `cursor-pointer transition-colors ${isActive ? 'bg-primary/10' : 'hover:bg-muted'}`, onClick: () => openDetail(item), draggable: true, onDragStart: (e) => handleDragStart(e, item.id), children: [_jsx("td", { className: "px-3 py-2", onClick: (e) => e.stopPropagation(), children: _jsx("input", { type: "checkbox", checked: selectedMedia.includes(item.id), onChange: () => handleCheckbox({ stopPropagation: () => { } }, item.id), className: "border-input rounded" }) }), _jsx("td", { className: "cursor-grab px-1 py-2", children: _jsx(GripVertical, { className: "text-muted-foreground h-4 w-4" }) }), _jsx("td", { className: "px-3 py-2", children: _jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "bg-muted flex h-10 w-10 items-center justify-center overflow-hidden rounded", children: _jsx(MediaPreview, { item: item }) }), _jsx("span", { className: "text-foreground text-sm font-medium", children: item.name })] }) }), _jsx("td", { className: "text-muted-foreground px-3 py-2 text-sm", children: item.format ?? item.type }), _jsx("td", { className: "text-muted-foreground px-3 py-2 text-sm", children: item.size }), _jsx("td", { className: "text-muted-foreground px-3 py-2 text-sm", children: item.date }), _jsx("td", { className: "px-3 py-2", children: hasIssues ? (_jsxs("span", { className: "bg-warning/15 text-warning inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium", children: [_jsx(AlertTriangle, { className: "h-3 w-3" }), " Needs attention"] })) : (_jsx("span", { className: "bg-success/15 text-success inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium", children: "Complete" })) })] }, item.id));
                                                        }) })] }) })) }), panelOpen && activeItem && (_jsxs("div", { className: "border-border bg-card flex w-80 shrink-0 flex-col overflow-y-auto rounded-lg border lg:w-96", children: [_jsxs("div", { className: "border-border bg-card sticky top-0 z-10 flex items-center justify-between border-b p-4", children: [_jsx("h3", { className: "text-foreground truncate text-sm font-medium", children: activeItem.name }), _jsx("button", { onClick: closeDetail, className: "hover:bg-muted rounded p-1 transition-colors", "aria-label": "Close panel", children: _jsx(X, { className: "text-muted-foreground h-4 w-4" }) })] }), _jsxs("div", { className: "flex-1 overflow-y-auto", children: [_jsx("div", { className: "border-border border-b p-4", children: _jsx("div", { className: "bg-muted flex aspect-video items-center justify-center overflow-hidden rounded-lg", children: isImageMedia(activeItem) ? (_jsx(MediaPreview, { item: activeItem })) : (_jsx(ImageIcon, { className: "text-muted-foreground h-12 w-12" })) }) }), issues.length > 0 && (_jsxs("div", { className: "border-warning/30 bg-warning/10 mx-4 mt-4 rounded-lg border p-3", children: [_jsxs("div", { className: "flex items-start gap-2", children: [_jsx(AlertTriangle, { className: "text-warning mt-0.5 h-4 w-4 shrink-0" }), _jsxs("div", { children: [_jsxs("p", { className: "text-warning mb-1 text-xs font-medium", children: [issues.length, " issue", issues.length !== 1 ? 's' : '', " found"] }), _jsx("ul", { className: "space-y-0.5", children: issues.map((issue, i) => (_jsxs("li", { className: "text-warning text-xs", children: ["\u2022 ", issue] }, i))) })] })] }), _jsxs("button", { type: "button", onClick: async () => {
                                                                    if (!activeItem.altTag)
                                                                        await handleAiGenerate('alt');
                                                                    if (!activeItem.title)
                                                                        await handleAiGenerate('title');
                                                                    if (activeItem.sizeBytes > 2000000)
                                                                        await handleAiGenerate('optimize');
                                                                }, className: "bg-warning text-warning-foreground hover:bg-warning/90 mt-2 flex w-full items-center justify-center gap-1.5 rounded-lg px-3 py-1.5 text-xs transition-colors", children: [_jsx(Sparkles, { className: "h-3.5 w-3.5" }), "AI Fix All Issues"] })] })), _jsxs("div", { className: "border-border space-y-3 border-b p-4", children: [_jsx("h4", { className: "text-muted-foreground text-xs font-medium tracking-wide uppercase", children: "File Information" }), _jsxs("div", { className: "grid grid-cols-2 gap-3", children: [_jsxs("div", { children: [_jsx("div", { className: "text-muted-foreground mb-0.5 text-xs", children: "Format" }), _jsx("div", { className: "text-foreground text-sm", children: activeItem.format ?? 'Unknown' })] }), _jsxs("div", { children: [_jsx("div", { className: "text-muted-foreground mb-0.5 text-xs", children: "File Size" }), _jsxs("div", { className: "text-foreground flex items-center gap-1 text-sm", children: [activeItem.size, activeItem.sizeBytes > 2000000 && (_jsx("span", { className: "text-warning text-xs", children: "(large)" }))] })] }), _jsxs("div", { children: [_jsx("div", { className: "text-muted-foreground mb-0.5 text-xs", children: "Dimensions" }), _jsx("div", { className: "text-foreground text-sm", children: activeItem.dimensions ?? '—' })] }), _jsxs("div", { children: [_jsx("div", { className: "text-muted-foreground mb-0.5 text-xs", children: "Uploaded" }), _jsx("div", { className: "text-foreground text-sm", children: activeItem.date })] })] }), _jsxs("div", { children: [_jsx("div", { className: "text-muted-foreground mb-1 text-xs", children: "URL" }), _jsxs("div", { className: "flex items-center gap-1", children: [_jsx("code", { className: "border-border bg-muted text-foreground flex-1 truncate rounded border px-2 py-1.5 text-xs", children: activeItem.url }), _jsx("button", { onClick: handleCopyUrl, className: "hover:bg-muted shrink-0 rounded p-1.5 transition-colors", title: "Copy URL", children: _jsx(Copy, { className: "text-muted-foreground h-3.5 w-3.5" }) })] })] })] }), _jsxs("div", { className: "border-border space-y-4 border-b p-4", children: [_jsx("h4", { className: "text-muted-foreground text-xs font-medium tracking-wide uppercase", children: "SEO & Accessibility" }), _jsxs("div", { children: [_jsxs("div", { className: "mb-1 flex items-center justify-between", children: [_jsx("label", { className: "text-foreground text-sm font-medium", children: "Alt Tag" }), _jsxs("button", { type: "button", onClick: () => handleAiGenerate('alt'), disabled: aiGenerating === 'alt', className: "text-primary hover:text-primary/80 flex items-center gap-1 text-xs transition-colors disabled:opacity-50", children: [_jsx(Bot, { className: "h-3.5 w-3.5" }), aiGenerating === 'alt' ? 'Generating...' : 'AI Generate'] })] }), _jsx("textarea", { value: editAlt, onChange: (e) => setEditAlt(e.target.value), placeholder: "Describe this image for accessibility...", rows: 2, className: "border-input focus:ring-ring w-full resize-none rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" }), !editAlt && (_jsx("p", { className: "text-destructive mt-1 text-xs", children: "Required for accessibility and SEO" }))] }), _jsxs("div", { children: [_jsxs("div", { className: "mb-1 flex items-center justify-between", children: [_jsx("label", { className: "text-foreground text-sm font-medium", children: "Title" }), _jsxs("button", { type: "button", onClick: () => handleAiGenerate('title'), disabled: aiGenerating === 'title', className: "text-primary hover:text-primary/80 flex items-center gap-1 text-xs transition-colors disabled:opacity-50", children: [_jsx(Bot, { className: "h-3.5 w-3.5" }), aiGenerating === 'title' ? 'Generating...' : 'AI Generate'] })] }), _jsx("input", { type: "text", value: editTitle, onChange: (e) => setEditTitle(e.target.value), placeholder: "Image title...", className: "border-input focus:ring-ring w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { children: [_jsx("label", { className: "text-foreground mb-1 block text-sm font-medium", children: "File Name" }), _jsx("input", { type: "text", value: editFilename, onChange: (e) => setEditFilename(e.target.value), className: "border-input focus:ring-ring w-full rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none" })] })] }), _jsxs("div", { className: "border-border border-b p-4", children: [_jsxs("h4", { className: "text-muted-foreground mb-3 text-xs font-medium tracking-wide uppercase", children: ["Used On ", activeItem.usedOn && `(${activeItem.usedOn.length})`] }), activeItem.usedOn && activeItem.usedOn.length > 0 ? (_jsx("div", { className: "space-y-2", children: activeItem.usedOn.map((usage, i) => (_jsxs("button", { type: "button", onClick: () => onNavigate?.(usage.path), className: "border-border hover:bg-muted flex w-full items-center gap-2 rounded-lg border p-2 text-left transition-colors", children: [_jsx(Link2, { className: "text-muted-foreground h-4 w-4 shrink-0" }), _jsx("span", { className: "text-foreground flex-1 truncate text-sm", children: usage.page }), _jsx(ExternalLink, { className: "text-muted-foreground h-3.5 w-3.5 shrink-0" })] }, i))) })) : (_jsx("div", { className: "border-warning/30 bg-warning/10 rounded-lg border p-3", children: _jsxs("div", { className: "flex items-start gap-2", children: [_jsx(AlertTriangle, { className: "text-warning mt-0.5 h-4 w-4 shrink-0" }), _jsxs("div", { children: [_jsx("p", { className: "text-warning text-xs font-medium", children: "Orphaned media" }), _jsx("p", { className: "text-warning mt-0.5 text-xs", children: "This file isn't used on any page. Consider deleting it to save storage." })] })] }) }))] }), _jsxs("div", { className: "space-y-3 p-4", children: [_jsx("h4", { className: "text-muted-foreground text-xs font-medium tracking-wide uppercase", children: "AI Optimization" }), _jsxs("button", { type: "button", onClick: () => handleAiGenerate('optimize'), disabled: aiGenerating === 'optimize', className: "border-primary/30 bg-primary/10 hover:bg-primary/15 flex w-full items-center gap-2 rounded-lg border p-3 text-left transition-colors disabled:opacity-50", children: [_jsx(Sparkles, { className: `text-primary h-5 w-5 shrink-0 ${aiGenerating === 'optimize' ? 'animate-spin' : ''}` }), _jsxs("div", { className: "flex-1", children: [_jsx("div", { className: "text-primary text-sm font-medium", children: aiGenerating === 'optimize' ? 'Optimizing...' : 'Optimize Image' }), _jsx("div", { className: "text-primary mt-0.5 text-xs", children: "Compress and convert to modern format (WebP/AVIF)" })] })] }), _jsxs("button", { type: "button", className: "border-border hover:bg-muted flex w-full items-center gap-2 rounded-lg border p-3 text-left transition-colors", children: [_jsx(Bot, { className: "text-muted-foreground h-5 w-5 shrink-0" }), _jsxs("div", { className: "flex-1", children: [_jsx("div", { className: "text-foreground text-sm font-medium", children: "AI Content Analysis" }), _jsx("div", { className: "text-muted-foreground mt-0.5 text-xs", children: "Detect objects, faces, text, and suggest categories" })] })] })] })] }), _jsxs("div", { className: "border-border bg-card sticky bottom-0 flex items-center gap-2 border-t p-4", children: [_jsxs("button", { type: "button", onClick: handleSaveDetails, disabled: saving, className: "bg-primary text-primary-foreground hover:bg-primary/90 flex flex-1 items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors disabled:opacity-50", children: [saving && _jsx(Loader2, { className: "h-4 w-4 animate-spin" }), saving ? 'Saving...' : 'Save Changes'] }), _jsx("button", { type: "button", className: "hover:bg-muted rounded-lg p-2 transition-colors", title: "Download", children: _jsx(Download, { className: "text-muted-foreground h-4 w-4" }) }), _jsx("button", { type: "button", onClick: () => deleteMedia(activeItem.id), className: "hover:bg-muted rounded-lg p-2 transition-colors", title: "Delete", children: _jsx(Trash2, { className: "text-destructive h-4 w-4" }) })] })] }))] }))] })] })] }));
}
//# sourceMappingURL=MediaBrowser.js.map