'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-blue-100', text: 'text-blue-700' },
    { bg: 'bg-green-100', text: 'text-green-700' },
    { bg: 'bg-purple-100', text: 'text-purple-700' },
    { bg: 'bg-orange-100', text: 'text-orange-700' },
    { bg: 'bg-pink-100', text: 'text-pink-700' },
    { bg: 'bg-teal-100', text: 'text-teal-700' },
    { bg: 'bg-indigo-100', text: 'text-indigo-700' },
    { bg: 'bg-rose-100', text: 'text-rose-700' },
];
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-green-500' : score >= 60 ? 'bg-amber-500' : 'bg-red-500';
    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-xs text-gray-600", 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: "flex items-center gap-1 text-xs font-medium text-gray-700 transition-colors hover:text-gray-900", children: [label, active ? (sortConfig.direction === 'asc' ? (_jsx(ArrowUp, { className: "h-3 w-3" })) : (_jsx(ArrowDown, { className: "h-3 w-3" }))) : (_jsx(ArrowUpDown, { className: "h-3 w-3 text-gray-400" }))] }));
    }
    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: "h-6 w-6 animate-spin text-blue-600" }) }));
    }
    return (_jsxs("div", { className: "flex h-full flex-col p-3 pr-6 sm:p-4 sm:pr-8", children: [error && (_jsxs("div", { className: "mb-4 flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-3", children: [_jsx(AlertTriangle, { className: "h-5 w-5 shrink-0 text-red-600" }), _jsx("span", { className: "flex-1 text-sm text-red-800", children: error }), _jsx("button", { onClick: refetch, className: "rounded-lg border border-red-300 px-3 py-1 text-sm text-red-700 transition-colors hover:bg-red-100", 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: "rounded-lg p-1.5 transition-colors hover:bg-gray-100", title: sidebarOpen ? 'Hide folders' : 'Show folders', children: _jsx(FolderInput, { className: "h-5 w-5 text-gray-600" }) }), _jsxs("div", { children: [_jsx("h1", { className: "text-xl font-semibold text-gray-900 sm:text-2xl", children: "Pages" }), _jsxs("p", { className: "text-sm text-gray-500", children: [totalCount, " page", totalCount !== 1 ? 's' : ''] })] })] }), _jsxs("button", { onClick: () => onNavigate?.('/pages/new'), className: "flex items-center justify-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700", 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: "flex w-56 shrink-0 flex-col overflow-hidden rounded-lg border border-gray-200 bg-white", 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: "mb-4 rounded-lg border border-gray-200 bg-white", children: _jsxs("div", { className: "flex flex-col gap-3 p-3", children: [_jsxs("div", { className: "relative", children: [_jsx(Search, { className: "absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-gray-400" }), _jsx("input", { type: "text", placeholder: "Search pages...", value: searchQuery, onChange: (e) => setSearchQuery(e.target.value), className: "w-full rounded-lg border border-gray-300 py-2 pr-3 pl-9 text-sm focus:ring-2 focus:ring-blue-500 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: "flex-1 rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 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: "flex-1 rounded-lg border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 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: "flex items-center justify-center gap-2 rounded-lg border border-gray-300 px-3 py-2 text-sm transition-colors hover:bg-gray-50", children: [_jsx(SlidersHorizontal, { className: "h-4 w-4" }), _jsx("span", { className: "hidden sm:inline", children: "More Filters" })] })] })] }) }), selectedPages.length > 0 && (_jsx("div", { className: "mb-4 rounded-lg border border-blue-200 bg-blue-50 p-3", children: _jsxs("div", { className: "flex flex-col justify-between gap-2 sm:flex-row sm:items-center", children: [_jsxs("span", { className: "text-sm text-blue-900", 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: "flex-1 rounded-lg bg-green-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-green-700 sm:flex-none", children: "Publish" }), _jsx("button", { type: "button", onClick: handleBulkUnpublish, className: "flex-1 rounded-lg bg-yellow-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-yellow-700 sm:flex-none", children: "Unpublish" }), _jsx("button", { type: "button", onClick: handleBulkDelete, className: "flex-1 rounded-lg bg-red-600 px-3 py-1.5 text-sm text-white transition-colors hover:bg-red-700 sm:flex-none", children: "Delete" }), _jsx("button", { type: "button", onClick: () => setSelectedPages([]), className: "flex-1 rounded-lg border border-gray-300 bg-white px-3 py-1.5 text-sm transition-colors hover:bg-gray-50 sm:flex-none", children: "Cancel" })] })] }) })), filteredAndSorted.length === 0 && !error ? (_jsxs("div", { className: "flex flex-1 flex-col items-center justify-center rounded-lg border border-gray-200 bg-white p-8 text-center", children: [_jsx("p", { className: "mb-2 text-sm text-gray-500", 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: "rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700", children: "Create your first page" })] })) : (_jsxs(_Fragment, { children: [_jsx("div", { className: "hidden flex-1 overflow-hidden rounded-lg border border-gray-200 bg-white md:block", children: _jsx("div", { className: "h-full overflow-x-auto", children: _jsxs("table", { className: "w-full", children: [_jsx("thead", { className: "sticky top-0 border-b border-gray-200 bg-gray-50", 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: "rounded border-gray-300" }) }), _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: "px-3 py-2 text-left text-xs font-medium text-gray-700", children: "Folder" }), _jsx("th", { className: "px-3 py-2 text-left", children: _jsx(SortHeader, { label: "Author", sortKey: "author" }) }), _jsx("th", { className: "px-3 py-2 text-left text-xs font-medium text-gray-700", 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: "px-3 py-2 text-left text-xs font-medium text-gray-700", children: "Actions" })] }) }), _jsx("tbody", { className: "divide-y divide-gray-200", children: filteredAndSorted.map((page) => {
                                                            const seoScore = computeSeoScore(page.data);
                                                            const folderName = page.folder?.name ?? page.folderName;
                                                            return (_jsxs("tr", { className: "transition-colors hover:bg-gray-50", 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: "rounded border-gray-300" }) }), _jsx("td", { className: "cursor-grab px-1 py-2", children: _jsx(GripVertical, { className: "h-4 w-4 text-gray-300" }) }), _jsx("td", { className: "px-3 py-2", children: _jsx("button", { type: "button", onClick: () => onNavigate?.(`/pages/${page.id}`), className: "text-left text-sm font-medium text-gray-900 hover:text-blue-600", children: page.title }) }), _jsx("td", { className: "px-3 py-2", children: folderName ? (_jsx(FolderBadge, { name: folderName })) : (_jsx("span", { className: "text-xs text-gray-400", children: "\u2014" })) }), _jsx("td", { className: "px-3 py-2 text-sm text-gray-600", 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-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`, children: page.status }) }), _jsx("td", { className: "px-3 py-2 text-sm text-gray-600", 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: "rounded p-1.5 transition-colors hover:bg-gray-100", title: "Edit", children: _jsx(Pencil, { className: "h-4 w-4 text-gray-600" }) }), _jsx("button", { type: "button", onClick: () => handleDelete(page.id), className: "rounded p-1.5 transition-colors hover:bg-gray-100", title: "Delete", children: _jsx(Trash2, { className: "h-4 w-4 text-red-600" }) })] }) })] }, page.id));
                                                        }) })] }) }) }), _jsx("div", { className: "flex-1 overflow-auto rounded-lg border border-gray-200 bg-white md:hidden", children: _jsx("div", { className: "divide-y divide-gray-200", 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: "mt-1 rounded border-gray-300" }), _jsxs("div", { className: "min-w-0 flex-1", children: [_jsx("button", { type: "button", onClick: () => onNavigate?.(`/pages/${page.id}`), className: "mb-1 block text-left text-sm font-medium text-gray-900 hover:text-blue-600", children: page.title }), _jsxs("div", { className: "mb-2 flex flex-wrap items-center gap-2 text-xs text-gray-600", 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-green-100 text-green-800' : 'bg-gray-100 text-gray-800'}`, children: page.status })] })] }), _jsx("button", { type: "button", onClick: () => handleDelete(page.id), className: "rounded p-1.5 transition-colors hover:bg-gray-100", children: _jsx(Trash2, { className: "h-4 w-4 text-red-600" }) })] }) }, page.id));
                                            }) }) })] }))] })] })] }));
}
//# sourceMappingURL=Pages.js.map