'use client';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useState, useCallback } from 'react';
import dynamic from 'next/dynamic';
import { Plus, FileText, Trash2, Star, StarOff, ChevronRight } from 'lucide-react';
import { cn } from '../../../lib/utils.js';
import { Button } from '../../ui/button.js';
import { Input } from '../../ui/input.js';
import { createPage, updatePage, deletePage } from '../../../app/actions/manage-pages.js';
// Defer the Tiptap-based editor (13 @tiptap/* packages + lowlight syntax
// grammars). This panel is mounted on every project route but most users
// don't open the editor on every visit — splitting the editor chunk cuts
// the project-route initial bundle by ~200KB gzip.
const PageEditor = dynamic(() => import('./page-editor.js').then((m) => m.PageEditor), {
    ssr: false,
});
export function PagesPanel({ projectId, pages: initialPages, className }) {
    const [pages, setPages] = useState(initialPages);
    const [selectedPageId, setSelectedPageId] = useState(null);
    const [isCreating, setIsCreating] = useState(false);
    const [newTitle, setNewTitle] = useState('');
    const [editingTitle, setEditingTitle] = useState(null);
    const selectedPage = pages.find((p) => p.id === selectedPageId);
    const rootPages = pages.filter((p) => !p.parentId);
    const getChildren = useCallback((parentId) => pages.filter((p) => p.parentId === parentId), [pages]);
    const handleCreate = useCallback(async () => {
        const title = newTitle.trim();
        if (!title)
            return;
        const result = await createPage({ projectId, title });
        if (result.page) {
            setPages((prev) => [...prev, result.page]);
            setSelectedPageId(result.page.id);
            setNewTitle('');
            setIsCreating(false);
        }
    }, [projectId, newTitle]);
    const handleContentUpdate = useCallback(async (content) => {
        if (!selectedPageId)
            return;
        const result = await updatePage(selectedPageId, { content });
        if (result.page) {
            setPages((prev) => prev.map((p) => (p.id === result.page.id ? result.page : p)));
        }
    }, [selectedPageId]);
    const handleTitleUpdate = useCallback(async (pageId, title) => {
        const trimmed = title.trim();
        if (!trimmed)
            return;
        const result = await updatePage(pageId, { title: trimmed });
        if (result.page) {
            setPages((prev) => prev.map((p) => (p.id === result.page.id ? result.page : p)));
        }
        setEditingTitle(null);
    }, []);
    const handleDelete = useCallback(async (pageId) => {
        const result = await deletePage(pageId);
        if (!result.error) {
            setPages((prev) => prev.filter((p) => p.id !== pageId));
            if (selectedPageId === pageId)
                setSelectedPageId(null);
        }
    }, [selectedPageId]);
    const handleToggleFavorite = useCallback(async (pageId, current) => {
        const result = await updatePage(pageId, { isFavorite: !current });
        if (result.page) {
            setPages((prev) => prev.map((p) => (p.id === result.page.id ? result.page : p)));
        }
    }, []);
    const renderPageItem = (page, depth = 0) => {
        const children = getChildren(page.id);
        const isSelected = selectedPageId === page.id;
        const isEditing = editingTitle === page.id;
        return (_jsxs("div", { children: [_jsxs("div", { "data-testid": `page-item-${page.id}`, className: cn('group hover:bg-accent/50 flex cursor-pointer items-center gap-1 rounded-sm px-2 py-1 text-xs', isSelected && 'bg-accent'), style: { paddingLeft: `${8 + depth * 16}px` }, onClick: () => setSelectedPageId(page.id), children: [children.length > 0 && (_jsx(ChevronRight, { className: "text-muted-foreground h-3 w-3 shrink-0" })), _jsx(FileText, { className: "text-muted-foreground h-3 w-3 shrink-0" }), isEditing ? (_jsx(Input, { autoFocus: true, defaultValue: page.title, className: "h-5 text-xs", onBlur: (e) => handleTitleUpdate(page.id, e.target.value), onKeyDown: (e) => {
                                if (e.key === 'Enter')
                                    handleTitleUpdate(page.id, e.currentTarget.value);
                                if (e.key === 'Escape')
                                    setEditingTitle(null);
                            }, onClick: (e) => e.stopPropagation() })) : (_jsx("span", { className: "flex-1 truncate", onDoubleClick: (e) => {
                                e.stopPropagation();
                                setEditingTitle(page.id);
                            }, children: page.title })), _jsxs("div", { className: "hidden gap-0.5 group-hover:flex", children: [_jsx(Button, { variant: "ghost", size: "sm", className: "h-4 w-4 p-0", onClick: (e) => {
                                        e.stopPropagation();
                                        handleToggleFavorite(page.id, page.isFavorite);
                                    }, title: page.isFavorite ? 'Unfavorite' : 'Favorite', children: page.isFavorite ? (_jsx(Star, { className: "h-2.5 w-2.5 fill-yellow-400 text-yellow-400" })) : (_jsx(StarOff, { className: "h-2.5 w-2.5" })) }), _jsx(Button, { variant: "ghost", size: "sm", className: "text-destructive h-4 w-4 p-0", onClick: (e) => {
                                        e.stopPropagation();
                                        handleDelete(page.id);
                                    }, title: "Delete page", children: _jsx(Trash2, { className: "h-2.5 w-2.5" }) })] })] }), children.map((child) => renderPageItem(child, depth + 1))] }, page.id));
    };
    return (_jsxs("div", { "data-testid": "pages-panel", className: cn('flex h-full gap-0', className), children: [_jsxs("div", { className: "flex w-56 shrink-0 flex-col border-r", children: [_jsxs("div", { className: "flex items-center justify-between border-b px-3 py-2", children: [_jsx("span", { className: "text-xs font-medium", children: "Pages" }), _jsx(Button, { variant: "ghost", size: "sm", className: "h-5 w-5 p-0", onClick: () => setIsCreating(true), "data-testid": "create-page-btn", children: _jsx(Plus, { className: "h-3 w-3" }) })] }), _jsxs("div", { className: "flex-1 overflow-y-auto p-1", children: [isCreating ? (_jsx("div", { className: "mb-1 px-2", children: _jsx(Input, { autoFocus: true, placeholder: "Page title...", value: newTitle, onChange: (e) => setNewTitle(e.target.value), onKeyDown: (e) => {
                                        if (e.key === 'Enter')
                                            handleCreate();
                                        if (e.key === 'Escape') {
                                            setIsCreating(false);
                                            setNewTitle('');
                                        }
                                    }, onBlur: () => {
                                        if (newTitle.trim())
                                            handleCreate();
                                        else {
                                            setIsCreating(false);
                                            setNewTitle('');
                                        }
                                    }, className: "h-6 text-xs", "data-testid": "new-page-input" }) })) : null, rootPages.length === 0 && !isCreating ? (_jsxs("div", { className: "flex flex-col items-center justify-center py-8 text-center", children: [_jsx(FileText, { className: "mb-2 h-5 w-5 opacity-20" }), _jsx("p", { className: "text-muted-foreground text-[10px]", children: "No pages yet" })] })) : (rootPages.map((page) => renderPageItem(page)))] })] }), _jsx("div", { className: "flex flex-1 flex-col overflow-hidden", children: selectedPage ? (_jsxs(_Fragment, { children: [_jsx("div", { className: "border-b px-4 py-2", children: _jsx("h2", { className: "text-sm font-medium", children: selectedPage.title }) }), _jsx("div", { className: "flex-1 overflow-y-auto", children: _jsx(PageEditor, { content: selectedPage.content ?? '', onUpdate: handleContentUpdate }) })] })) : (_jsx("div", { className: "flex flex-1 items-center justify-center", children: _jsxs("div", { className: "text-center", children: [_jsx(FileText, { className: "mx-auto mb-2 h-8 w-8 opacity-20" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Select or create a page" })] }) })) })] }));
}
