'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { Plus, Search, Trash2, SlidersHorizontal, Pencil, ArrowUpDown, ArrowUp, ArrowDown, Loader2, AlertTriangle, GripVertical, FolderInput, } from 'lucide-react';
import { useState, useMemo, 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';
const COLOR_PALETTE = [
    { bg: 'bg-chart-1/15', text: 'text-chart-1' },
    { bg: 'bg-chart-2/15', text: 'text-chart-2' },
    { bg: 'bg-chart-3/15', text: 'text-chart-3' },
    { bg: 'bg-chart-4/15', text: 'text-chart-4' },
    { bg: 'bg-chart-5/15', text: 'text-chart-5' },
];
function hashString(s) {
    let hash = 0;
    for (let i = 0; i < s.length; i++) {
        hash = ((hash << 5) - hash + s.charCodeAt(i)) | 0;
    }
    return Math.abs(hash);
}
const folderColorCache = {};
function getFolderColor(name) {
    if (!folderColorCache[name]) {
        folderColorCache[name] = COLOR_PALETTE[hashString(name) % COLOR_PALETTE.length];
    }
    return folderColorCache[name];
}
function computeSeoScore(data) {
    if (!data)
        return 0;
    let score = 0;
    if (data.metaTitle || data.seoTitle)
        score += 25;
    if (data.metaDescription || data.seoDescription)
        score += 25;
    if (data.canonical)
        score += 25;
    if (data.schemaType)
        score += 25;
    return score;
}
function textValue(value) {
    return String(value ?? '');
}
function SeoScoreBadge({ score }) {
    const color = score >= 80 ? 'bg-success' : score >= 60 ? 'bg-warning' : 'bg-destructive';
    return (_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: `h-2.5 w-2.5 rounded-full ${color}` }), _jsx("span", { className: "text-muted-foreground text-xs", children: score })] }));
}
function FolderBadge({ name }) {
    const colors = getFolderColor(name);
    return (_jsx("span", { className: `inline-flex rounded px-2 py-0.5 text-xs font-medium ${colors.bg} ${colors.text}`, children: name }));
}
function buildApiUrl(folderSel) {
    const base = '/collections/pages?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 Pages({ onNavigate }) {
    const [folderSel, setFolderSel] = useState({ type: 'smart', smart: 'all' });
    const [sidebarOpen, setSidebarOpen] = useState(true);
    const apiUrl = useMemo(() => buildApiUrl(folderSel), [folderSel]);
    const { data, loading, error, refetch } = useApiData(apiUrl);
    const allData = useApiData('/collections/pages?pageSize=1');
    const uncatData = useApiData('/collections/pages?pageSize=1&folderId=none');
    const [searchQuery, setSearchQuery] = useState('');
    const [filterStatus, setFilterStatus] = useState('all');
    const [filterTemplate, setFilterTemplate] = useState('all');
    const [selectedPages, setSelectedPages] = useState([]);
    const [sortConfig, setSortConfig] = useState(null);
    const pages = data?.docs ?? [];
    const totalCount = data?.total ?? pages.length;
    const filteredAndSorted = useMemo(() => {
        let results = pages.filter((page) => {
            const matchesSearch = textValue(page.title).toLowerCase().includes(searchQuery.toLowerCase()) ||
                textValue(page.author).toLowerCase().includes(searchQuery.toLowerCase());
            const matchesStatus = filterStatus === 'all' ||
                textValue(page.status).toLowerCase() === filterStatus.toLowerCase();
            const matchesTemplate = filterTemplate === 'all' ||
                textValue(page.template).toLowerCase() === filterTemplate.toLowerCase();
            return matchesSearch && matchesStatus && matchesTemplate;
        });
        if (searchQuery.trim()) {
            results = sortByRelevance(results, searchQuery, (p) => [
                p.title,
                p.author ?? '',
                p.template ?? '',
            ]);
        }
        else if (sortConfig) {
            results = [...results].sort((a, b) => {
                const aVal = a[sortConfig.key] ?? '';
                const bVal = b[sortConfig.key] ?? '';
                const cmp = String(aVal).localeCompare(String(bVal));
                return sortConfig.direction === 'asc' ? cmp : -cmp;
            });
        }
        return results;
    }, [pages, searchQuery, filterStatus, filterTemplate, sortConfig]);
    const handleSelectAll = (checked) => {
        setSelectedPages(checked ? filteredAndSorted.map((p) => p.id) : []);
    };
    const handleSelectPage = (id) => {
        setSelectedPages((prev) => prev.includes(id) ? prev.filter((pid) => pid !== id) : [...prev, id]);
    };
    const handleBulkDelete = async () => {
        for (const id of selectedPages) {
            await cmsApi(`/collections/pages/${id}`, { method: 'DELETE' });
        }
        toast.success(`${selectedPages.length} pages deleted`);
        setSelectedPages([]);
        refetch();
    };
    const handleBulkPublish = async () => {
        for (const id of selectedPages) {
            await cmsApi(`/collections/pages/${id}`, {
                method: 'PUT',
                body: JSON.stringify({ status: 'PUBLISHED' }),
            });
        }
        toast.success(`${selectedPages.length} pages published`);
        setSelectedPages([]);
        refetch();
    };
    const handleBulkUnpublish = async () => {
        for (const id of selectedPages) {
            await cmsApi(`/collections/pages/${id}`, {
                method: 'PUT',
                body: JSON.stringify({ status: 'DRAFT' }),
            });
        }
        toast.success(`${selectedPages.length} pages unpublished`);
        setSelectedPages([]);
        refetch();
    };
    const handleDelete = async (id) => {
        await cmsApi(`/collections/pages/${id}`, { method: 'DELETE' });
        toast.success('Page deleted');
        setSelectedPages((prev) => prev.filter((pid) => pid !== id));
        refetch();
    };
    const handleDropItem = useCallback(async (itemId, folderId) => {
        const res = await cmsApi(`/documents/${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', id);
        e.dataTransfer.effectAllowed = 'move';
    };
    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 text-destructive hover:bg-destructive/10 rounded-lg border px-3 py-1 text-sm transition-colors", children: "Retry" })] })), _jsxs("div", { className: "mb-4 flex flex-col justify-between gap-3 sm:flex-row sm:items-center", 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 text-xl font-medium sm:text-2xl", children: "Pages" }), _jsxs("p", { className: "text-muted-foreground text-sm", children: [totalCount, " page", totalCount !== 1 ? 's' : ''] })] })] }), _jsxs("button", { onClick: () => onNavigate?.('/pages/new'), className: "bg-primary text-primary-foreground hover:bg-primary/90 flex items-center justify-center gap-2 rounded-lg px-4 py-2 text-sm transition-colors", children: [_jsx(Plus, { className: "h-4 w-4" }), _jsx("span", { className: "hidden sm:inline", children: "New Page" }), _jsx("span", { className: "sm:hidden", children: "New" })] })] }), _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: "pages", selected: folderSel, onSelect: (sel) => {
                                setFolderSel(sel);
                                setSelectedPages([]);
                            }, 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 flex-col gap-3 p-3", children: [_jsxs("div", { className: "relative", 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 pages...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: "border-border focus-visible:ring-ring/50 w-full rounded-lg border py-2 pr-3 pl-9 text-sm focus:ring-2 focus:outline-none" })] }), _jsxs("div", { className: "flex flex-col gap-2 sm:flex-row", children: [_jsxs("select", { value: filterStatus, onChange: (e) => setFilterStatus(e.target.value), className: "border-border focus-visible:ring-ring/50 flex-1 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", children: [_jsx("option", { value: "all", children: "All Status" }), _jsx("option", { value: "published", children: "Published" }), _jsx("option", { value: "draft", children: "Draft" })] }), _jsxs("select", { value: filterTemplate, onChange: (e) => setFilterTemplate(e.target.value), className: "border-border focus-visible:ring-ring/50 flex-1 rounded-lg border px-3 py-2 text-sm focus:ring-2 focus:outline-none", children: [_jsx("option", { value: "all", children: "All Templates" }), _jsx("option", { value: "landing", children: "Landing" }), _jsx("option", { value: "standard", children: "Standard" }), _jsx("option", { value: "marketing", children: "Marketing" }), _jsx("option", { value: "blog", children: "Blog" })] }), _jsxs("button", { type: "button", className: "border-border hover:bg-muted flex items-center justify-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors", children: [_jsx(SlidersHorizontal, { className: "h-4 w-4" }), _jsx("span", { className: "hidden sm:inline", children: "More Filters" })] })] })] }) }), selectedPages.length > 0 && (_jsx("div", { className: "border-info/30 bg-info/10 mb-4 rounded-lg border p-3", children: _jsxs("div", { className: "flex flex-col justify-between gap-2 sm:flex-row sm:items-center", children: [_jsxs("span", { className: "text-foreground text-sm", children: [selectedPages.length, " page", selectedPages.length !== 1 ? 's' : '', " selected"] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: handleBulkPublish, className: "bg-success text-success-foreground hover:bg-success/90 flex-1 rounded-lg px-3 py-1.5 text-sm transition-colors sm:flex-none", children: "Publish" }), _jsx("button", { type: "button", onClick: handleBulkUnpublish, className: "bg-warning text-warning-foreground hover:bg-warning/90 flex-1 rounded-lg px-3 py-1.5 text-sm transition-colors sm:flex-none", children: "Unpublish" }), _jsx("button", { type: "button", onClick: handleBulkDelete, className: "bg-destructive text-destructive-foreground hover:bg-destructive/90 flex-1 rounded-lg px-3 py-1.5 text-sm transition-colors sm:flex-none", children: "Delete" }), _jsx("button", { type: "button", onClick: () => setSelectedPages([]), className: "border-border bg-card hover:bg-muted flex-1 rounded-lg border px-3 py-1.5 text-sm transition-colors sm:flex-none", children: "Cancel" })] })] }) })), filteredAndSorted.length === 0 && !error ? (_jsxs("div", { className: "border-border bg-card flex flex-1 flex-col items-center justify-center rounded-lg border p-8 text-center", children: [_jsx("p", { className: "text-muted-foreground mb-2 text-sm", children: folderSel.type === 'smart' && folderSel.smart === 'uncategorized'
                                            ? 'No uncategorized pages'
                                            : folderSel.type === 'folder'
                                                ? 'No pages in this folder'
                                                : 'No pages yet' }), _jsx("button", { onClick: () => onNavigate?.('/pages/new'), className: "bg-primary text-primary-foreground hover:bg-primary/90 rounded-lg px-4 py-2 text-sm transition-colors", children: "Create your first page" })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { className: "border-border bg-card hidden flex-1 overflow-hidden rounded-lg border md:block", children: _jsx("div", { className: "h-full overflow-x-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: selectedPages.length === filteredAndSorted.length &&
                                                                            filteredAndSorted.length > 0, onChange: (e) => handleSelectAll(e.target.checked), className: "border-border rounded" }) }), _jsx("th", { className: "w-6 px-1 py-2" }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Title", sortKey: "title" }) }), _jsx("th", { className: "text-foreground px-3 py-2 text-left text-xs font-medium", children: "Folder" }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Author", sortKey: "author" }) }), _jsx("th", { className: "text-foreground px-3 py-2 text-left text-xs font-medium", children: "SEO" }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Status", sortKey: "status" }) }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Date", sortKey: "date" }) }), _jsx("th", { className: "text-foreground px-3 py-2 text-left text-xs font-medium", children: "Actions" })] }) }), _jsx("tbody", { className: "divide-border divide-y", children: filteredAndSorted.map((page) => {
                                                            const seoScore = computeSeoScore(page.data);
                                                            const folderName = page.folder?.name ?? page.folderName;
                                                            return (_jsxs("tr", { className: "hover:bg-muted transition-colors", draggable: true, onDragStart: (e) => handleDragStart(e, page.id), children: [_jsx("td", { className: "px-3 py-2", children: _jsx("input", { type: "checkbox", checked: selectedPages.includes(page.id), onChange: () => handleSelectPage(page.id), className: "border-border 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: _jsx("button", { type: "button", onClick: () => onNavigate?.(`/pages/${page.id}`), className: "text-foreground hover:text-primary text-left text-sm font-medium", children: page.title }) }), _jsx("td", { className: "px-3 py-2", children: folderName ? (_jsx(FolderBadge, { name: folderName })) : (_jsx("span", { className: "text-muted-foreground text-xs", children: "\u2014" })) }), _jsx("td", { className: "text-muted-foreground px-3 py-2 text-sm", children: page.author }), _jsx("td", { className: "px-3 py-2", children: _jsx(SeoScoreBadge, { score: seoScore }) }), _jsx("td", { className: "px-3 py-2", children: _jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ${page.status === 'Published' || page.status === 'PUBLISHED' ? 'bg-success/10 text-success' : 'bg-muted text-foreground'}`, children: page.status }) }), _jsx("td", { className: "text-muted-foreground px-3 py-2 text-sm", children: page.date }), _jsx("td", { className: "px-3 py-2", children: _jsxs("div", { className: "flex items-center gap-2", children: [_jsx("button", { type: "button", onClick: () => onNavigate?.(`/pages/${page.id}`), className: "hover:bg-muted rounded p-1.5 transition-colors", title: "Edit", children: _jsx(Pencil, { className: "text-muted-foreground h-4 w-4" }) }), _jsx("button", { type: "button", onClick: () => handleDelete(page.id), className: "hover:bg-muted rounded p-1.5 transition-colors", title: "Delete", children: _jsx(Trash2, { className: "text-destructive h-4 w-4" }) })] }) })] }, page.id));
                                                        }) })] }) }) }), _jsx("div", { className: "border-border bg-card flex-1 overflow-auto rounded-lg border md:hidden", children: _jsx("div", { className: "divide-border divide-y", children: filteredAndSorted.map((page) => {
                                                const seoScore = computeSeoScore(page.data);
                                                const folderName = page.folder?.name ?? page.folderName;
                                                return (_jsx("div", { className: "p-3", draggable: true, onDragStart: (e) => handleDragStart(e, page.id), children: _jsxs("div", { className: "flex items-start gap-3", children: [_jsx("input", { type: "checkbox", checked: selectedPages.includes(page.id), onChange: () => handleSelectPage(page.id), className: "border-border mt-1 rounded" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("button", { type: "button", onClick: () => onNavigate?.(`/pages/${page.id}`), className: "text-foreground hover:text-primary mb-1 block text-left text-sm font-medium", children: page.title }), _jsxs("div", { className: "text-muted-foreground mb-2 flex flex-wrap items-center gap-2 text-xs", children: [folderName && _jsx(FolderBadge, { name: folderName }), _jsx("span", { children: page.author }), _jsx("span", { children: "\u00B7" }), _jsx("span", { children: page.date }), _jsx(SeoScoreBadge, { score: seoScore }), _jsx("span", { className: `rounded-full px-2 py-0.5 text-xs font-medium ${page.status === 'Published' || page.status === 'PUBLISHED' ? 'bg-success/10 text-success' : 'bg-muted text-foreground'}`, children: page.status })] })] }), _jsx("button", { type: "button", onClick: () => handleDelete(page.id), className: "hover:bg-muted rounded p-1.5 transition-colors", children: _jsx(Trash2, { className: "text-destructive h-4 w-4" }) })] }) }, page.id));
                                            }) }) })] }))] })] })] }));
}
//# sourceMappingURL=Pages.js.map