'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState } from 'react';
import { DndContext, KeyboardSensor, PointerSensor, pointerWithin, useDraggable, useDroppable, useSensor, useSensors, } from '@dnd-kit/core';
import { ChevronDown, Copy, GripVertical, PenLine, Plus, Trash2 } from 'lucide-react';
import { PostStatusBadge, SeoScoreIndicator } from '../../components/posts/badges.js';
import { AuthorAvatar } from '../../components/ui/AuthorAvatar.js';
import { Button } from '../../components/ui/Button.js';
import { RowActionButton, RowActions } from '../../components/ui/RowActions.js';
const TH_CLASS = 'px-3 py-2.5 text-left text-[11.5px] font-semibold tracking-[0.4px] uppercase text-[var(--muted)]';
export function PagesTreeTable({ rows, loading, error, flattened, selected, expanded, onToggleExpand, onToggleSelect, onToggleAll, onOpen, onAddSubPage, onDuplicate, onDelete, onReparent, canReparent, onRetry, onClearFilters, onNewPage, }) {
    const allSelected = rows.length > 0 && rows.every((r) => selected.has(r.page.id));
    const [draggingId, setDraggingId] = useState(null);
    // A small activation distance keeps plain clicks (title, checkbox,
    // chevron) from starting a drag.
    const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }), useSensor(KeyboardSensor));
    const handleDragStart = (event) => {
        setDraggingId(String(event.active.id));
    };
    const handleDragEnd = (event) => {
        setDraggingId(null);
        const sourceId = String(event.active.id);
        const targetId = event.over ? String(event.over.id) : null;
        if (!targetId || targetId === sourceId)
            return;
        if (!canReparent(sourceId, targetId))
            return;
        onReparent(sourceId, targetId);
    };
    return (_jsx(DndContext, { sensors: sensors, collisionDetection: pointerWithin, onDragStart: handleDragStart, onDragEnd: handleDragEnd, onDragCancel: () => setDraggingId(null), children: _jsx("div", { className: "overflow-x-auto", children: _jsxs("table", { className: "w-full min-w-[800px]", role: "table", "aria-label": "Pages tree", children: [_jsxs("colgroup", { children: [_jsx("col", { style: { width: '40px' } }), _jsx("col", {}), _jsx("col", { style: { width: '130px' } }), _jsx("col", { style: { width: '150px' } }), _jsx("col", { style: { width: '120px' } }), _jsx("col", { style: { width: '115px' } }), _jsx("col", { style: { width: '70px' } }), _jsx("col", { style: { width: '170px' } })] }), _jsx("thead", { className: "border-b border-[var(--bdr)]", children: _jsxs("tr", { children: [_jsx("th", { scope: "col", className: "px-3 py-2.5 text-left", children: _jsx("input", { type: "checkbox", "aria-label": "Select all visible pages", checked: allSelected, onChange: (e) => onToggleAll(e.target.checked), className: "accent-primary rounded border-[var(--bdr)]" }) }), _jsx("th", { scope: "col", className: `${TH_CLASS} min-w-[280px]`, children: "Title" }), _jsx("th", { scope: "col", className: TH_CLASS, children: "Template" }), _jsx("th", { scope: "col", className: TH_CLASS, children: "Author" }), _jsx("th", { scope: "col", className: TH_CLASS, children: "Status" }), _jsx("th", { scope: "col", className: TH_CLASS, children: "Last Modified" }), _jsx("th", { scope: "col", className: TH_CLASS, children: "SEO" }), _jsx("th", { scope: "col", className: "px-3 py-2.5 text-right", children: _jsx("span", { className: "sr-only", children: "Actions" }) })] }) }), _jsxs("tbody", { children: [loading && rows.length === 0 && _jsx(TreeLoadingRows, {}), !loading && error && (_jsx("tr", { children: _jsxs("td", { colSpan: 8, className: "px-3 py-12 text-center", children: [_jsx("div", { className: "mb-2 text-sm font-medium text-[var(--txt)]", children: error }), _jsx(Button, { variant: "link", size: "md", onClick: onRetry, children: "Try again" })] }) })), !loading && !error && rows.length === 0 && (_jsx("tr", { children: _jsxs("td", { colSpan: 8, className: "px-3 py-16 text-center", children: [_jsx("div", { className: "mb-2 text-sm font-medium text-[var(--txt)]", children: flattened ? 'No pages match your filters' : 'No pages yet' }), _jsx("div", { className: "mb-4 text-sm text-[var(--sub)]", children: flattened
                                                ? 'Try clearing the search or status filter above.'
                                                : 'Create your first page to get started.' }), flattened ? (_jsx(Button, { type: "button", variant: "link", size: "md", onClick: onClearFilters, children: "Clear filters" })) : (_jsx(Button, { type: "button", variant: "primary", size: "sm", className: "shadow-sm", onClick: onNewPage, leftIcon: _jsx(Plus, { size: 16, "aria-hidden": true }), children: "New page" }))] }) })), !loading &&
                                !error &&
                                rows.map((row) => (_jsx(TreeRow, { row: row, isSelected: selected.has(row.page.id), isExpanded: expanded.has(row.page.id), draggable: !flattened, isDropTarget: draggingId !== null &&
                                        draggingId !== row.page.id &&
                                        canReparent(draggingId, row.page.id), onToggleExpand: () => onToggleExpand(row.page.id), onToggleSelect: () => onToggleSelect(row.page.id), onOpen: () => onOpen(row.page), onAddSubPage: () => onAddSubPage(row.page), onDuplicate: () => onDuplicate(row.page), onDelete: () => onDelete(row.page) }, row.page.id)))] })] }) }) }));
}
function TreeRow({ row, isSelected, isExpanded, draggable, isDropTarget, onToggleExpand, onToggleSelect, onOpen, onAddSubPage, onDuplicate, onDelete, }) {
    const { page, depth, hasChildren } = row;
    const { attributes, listeners, setNodeRef: setDragRef, isDragging, } = useDraggable({ id: page.id, disabled: !draggable });
    const { setNodeRef: setDropRef, isOver } = useDroppable({
        id: page.id,
        disabled: !draggable || !isDropTarget,
    });
    return (_jsxs("tr", { ref: setDropRef, className: `group h-14 border-b border-[var(--bdr)] transition-colors last:border-b-0 hover:bg-[var(--acc-l)] ${isSelected ? 'bg-[var(--acc-l)]' : ''} ${isDragging ? 'opacity-40' : ''} ${isDropTarget && isOver
            ? 'bg-[var(--acc-l)] shadow-[inset_0_0_0_2px_var(--acc)]'
            : isDropTarget
                ? 'shadow-[inset_0_0_0_1px_var(--acc-m)]'
                : ''}`, children: [_jsx("td", { className: "px-3 align-middle", children: _jsx("input", { type: "checkbox", "aria-label": `Select "${page.title}"`, checked: isSelected, onChange: onToggleSelect, className: "accent-primary rounded border-[var(--bdr)]" }) }), _jsx("td", { className: "px-3 align-middle", children: _jsxs("div", { className: "flex items-center", style: { paddingLeft: depth * 24 }, children: [draggable && (_jsx("button", { type: "button", ref: setDragRef, ...attributes, ...listeners, "aria-label": `Move "${page.title}" — drag onto another page to nest it there`, title: "Drag to move under another page", className: "mr-1 flex h-5 w-5 shrink-0 cursor-grab items-center justify-center rounded-[5px] text-[var(--muted)] opacity-0 transition-opacity duration-[var(--motion-fast)] group-hover:opacity-100 hover:bg-[var(--acc-l)] hover:text-[var(--acc)] focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none active:cursor-grabbing", children: _jsx(GripVertical, { size: 13, "aria-hidden": true }) })), hasChildren ? (_jsx("button", { type: "button", "aria-expanded": isExpanded, "aria-label": `${isExpanded ? 'Collapse' : 'Expand'} ${page.title}`, onClick: onToggleExpand, className: "flex h-5 w-5 shrink-0 items-center justify-center rounded-[5px] text-[var(--muted)] transition-colors duration-[var(--motion-fast)] hover:bg-[var(--acc-l)] hover:text-[var(--acc)] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: _jsx(ChevronDown, { size: 13, "aria-hidden": true, className: `motion-safe:transition-transform motion-safe:duration-150 ${isExpanded ? '' : '-rotate-90'}` }) })) : (_jsx("span", { className: "w-5 shrink-0", "aria-hidden": true })), _jsxs("div", { className: "min-w-0", children: [_jsx("button", { type: "button", onClick: onOpen, className: "block max-w-[280px] truncate text-left text-[13.5px] font-[550] text-[var(--txt)] transition-colors duration-[var(--motion-fast)] hover:text-[var(--acc)]", children: page.title }), _jsx("div", { className: "max-w-[280px] truncate font-mono text-[11.5px] text-[var(--muted)]", children: page.path })] })] }) }), _jsx("td", { className: "px-3 align-middle", children: page.templateId ? (_jsx("span", { className: "rounded-[5px] border border-[var(--bdr)] bg-[var(--bg)] px-2 py-0.5 text-[11.5px] whitespace-nowrap text-[var(--sub)]", children: page.templateId })) : (_jsx("span", { className: "text-[var(--muted)]", children: "\u2014" })) }), _jsx("td", { className: "px-3 align-middle", children: _jsxs("div", { className: "flex items-center gap-[7px]", children: [_jsx(AuthorAvatar, { name: page.authorName, size: 22 }), _jsx("span", { className: "truncate text-[13px] text-[var(--txt)]", children: page.authorName })] }) }), _jsx("td", { className: "px-3 align-middle", children: _jsx(PostStatusBadge, { status: page.status }) }), _jsx("td", { className: "px-3 align-middle text-[12.5px] text-[var(--sub)] tabular-nums", children: formatDateShort(page.lastModified) }), _jsx("td", { className: "px-3 align-middle", children: _jsx(SeoScoreIndicator, { score: page.seoScore }) }), _jsx("td", { className: "px-3 align-middle", children: _jsxs(RowActions, { children: [_jsxs("button", { type: "button", onClick: onOpen, className: "flex items-center gap-[5px] rounded-[6px] border border-[var(--bdr)] bg-[var(--card)] px-[9px] py-[5px] text-[12px] font-medium whitespace-nowrap text-[var(--txt)] transition-colors duration-[var(--motion-fast)] hover:border-[var(--acc)] hover:bg-[var(--acc-l)] hover:text-[var(--acc)] focus-visible:ring-2 focus-visible:ring-[var(--ring)] focus-visible:outline-none", children: [_jsx(PenLine, { size: 12, "aria-hidden": true }), "Edit"] }), _jsx(RowActionButton, { "aria-label": `Add sub-page under "${page.title}"`, title: "Add sub-page", onClick: onAddSubPage, children: _jsx(Plus, { size: 12, "aria-hidden": true }) }), _jsx(RowActionButton, { "aria-label": `Duplicate "${page.title}"`, title: "Duplicate", onClick: onDuplicate, children: _jsx(Copy, { size: 12, "aria-hidden": true }) }), _jsx(RowActionButton, { "aria-label": `Delete "${page.title}"`, title: page.isHomepage ? 'The homepage cannot be deleted' : 'Delete', danger: true, disabled: page.isHomepage, onClick: onDelete, children: _jsx(Trash2, { size: 12, "aria-hidden": true }) })] }) })] }));
}
function TreeLoadingRows() {
    return (_jsx(_Fragment, { children: Array.from({ length: 8 }).map((_, i) => (_jsx("tr", { className: "h-14 border-b border-[var(--bdr)] last:border-b-0", children: Array.from({ length: 8 }).map((__, j) => (_jsx("td", { className: "px-3 align-middle", children: _jsx("div", { className: "bg-muted h-4 w-full animate-pulse rounded" }) }, j))) }, i))) }));
}
function formatDateShort(input) {
    const d = new Date(input);
    if (Number.isNaN(d.getTime()))
        return '—';
    return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });
}
//# sourceMappingURL=PagesTreeTable.js.map