'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from 'react';
import { Loader2, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
import { cmsApi } from '../../lib/api.js';
import { ErrorBoundary } from '../../components/ErrorBoundary.js';
import { useBuilderState, } from '../../hooks/useBuilderState.js';
import { BuilderToolbar } from './BuilderToolbar.js';
import { BottomBar } from './BottomBar.js';
import { BuilderCanvas } from './canvas/index.js';
import { ContextPanel } from './ContextPanel.js';
import { AIGenerateDialog } from './AIGenerateDialog.js';
const DEVICE_WIDTHS = {
    desktop: '100%',
    tablet: '768px',
    mobile: '375px',
};
export function PageBuilder({ documentId, collectionSlug, config, onNavigate }) {
    const [loading, setLoading] = useState(!!documentId);
    const [loadError, setLoadError] = useState(null);
    const [saving, setSaving] = useState(false);
    const [status, setStatus] = useState('DRAFT');
    const [aiDialogOpen, setAiDialogOpen] = useState(false);
    const builder = useBuilderState();
    const { tree, pageSettings, deviceMode, dirty, canUndo, canRedo, selectedNodeId, selectedNode, activeTab, showGridOverlay, selectNode, setDeviceMode, setActiveTab, setPageSettings, setShowGridOverlay, addSection, addRowToSection, addBlockToColumn, addNodeAtId, removeNodeById, moveNodeById, updateSettings, updateBlock, duplicateNode, moveNodeUp, moveNodeDown, undo, redo, markClean, replaceTree, } = builder;
    useEffect(() => {
        if (!documentId) {
            setLoading(false);
            return;
        }
        let cancelled = false;
        async function loadDocument() {
            const res = await cmsApi(`/collections/${collectionSlug}/${documentId}`);
            if (cancelled)
                return;
            if (res.error) {
                setLoadError(res.error);
                setLoading(false);
                return;
            }
            const doc = res.data;
            if (doc?.layout) {
                replaceTree(doc.layout);
                markClean();
            }
            if (doc?.pageSettings) {
                setPageSettings(doc.pageSettings);
            }
            if (doc?.status) {
                setStatus(doc.status);
            }
            if (doc?.title) {
                setPageSettings({ title: doc.title });
            }
            setLoading(false);
        }
        loadDocument();
        return () => {
            cancelled = true;
        };
    }, [documentId, collectionSlug]);
    const handleSave = useCallback(async () => {
        setSaving(true);
        const body = JSON.stringify({
            layout: tree,
            pageSettings,
            title: pageSettings.title,
            slug: pageSettings.slug,
        });
        const endpoint = documentId
            ? `/collections/${collectionSlug}/${documentId}`
            : `/collections/${collectionSlug}`;
        const method = documentId ? 'PUT' : 'POST';
        const res = await cmsApi(endpoint, { method, body });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
        }
        else {
            markClean();
            toast.success('Page saved');
            if (!documentId && res.data?.id) {
                onNavigate(`/pages/${res.data.id}/builder`);
            }
        }
    }, [tree, pageSettings, documentId, collectionSlug, markClean, onNavigate]);
    const handlePublish = useCallback(async () => {
        setSaving(true);
        const body = JSON.stringify({
            layout: tree,
            pageSettings,
            title: pageSettings.title,
            slug: pageSettings.slug,
            status: 'PUBLISHED',
        });
        const endpoint = documentId
            ? `/collections/${collectionSlug}/${documentId}`
            : `/collections/${collectionSlug}`;
        const method = documentId ? 'PUT' : 'POST';
        const res = await cmsApi(endpoint, { method, body });
        setSaving(false);
        if (res.error) {
            toast.error(res.error);
        }
        else {
            markClean();
            setStatus('PUBLISHED');
            toast.success('Page published');
            if (!documentId && res.data?.id) {
                onNavigate(`/pages/${res.data.id}/builder`);
            }
        }
    }, [tree, pageSettings, documentId, collectionSlug, markClean, onNavigate]);
    const handleAIAccept = useCallback((generatedTree) => {
        replaceTree(generatedTree);
    }, [replaceTree]);
    if (loading) {
        return (_jsx("div", { className: "bg-background flex h-full items-center justify-center", children: _jsx(Loader2, { className: "text-muted-foreground animate-spin", size: 24 }) }));
    }
    if (loadError) {
        return (_jsx("div", { className: "bg-background flex h-full items-center justify-center", children: _jsxs("div", { className: "border-destructive/30 bg-destructive/5 flex max-w-md items-center gap-3 rounded-lg border p-4", children: [_jsx(AlertTriangle, { className: "text-destructive shrink-0", size: 20 }), _jsxs("div", { children: [_jsx("p", { className: "text-foreground text-sm font-medium", children: "Failed to load page" }), _jsx("p", { className: "text-muted-foreground mt-1 text-sm", children: loadError })] })] }) }));
    }
    const canvasWidth = DEVICE_WIDTHS[deviceMode];
    const isConstrained = deviceMode !== 'desktop';
    // `pageBuilder.previewTheme` lets consumers preview blocks with their
    // brand fonts/colors/radii without baking them into the admin's tokens.
    // We scope the CSS variables to the canvas wrapper so they never leak
    // into the rest of the admin chrome.
    const previewTheme = config?.pageBuilder?.previewTheme ?? {};
    const previewStyle = {};
    if (previewTheme.fontFamily)
        previewStyle['--preview-font-family'] = previewTheme.fontFamily;
    if (previewTheme.headingFontFamily)
        previewStyle['--preview-heading-font-family'] = previewTheme.headingFontFamily;
    if (previewTheme.primaryColor)
        previewStyle['--preview-primary'] = previewTheme.primaryColor;
    if (previewTheme.secondaryColor)
        previewStyle['--preview-secondary'] = previewTheme.secondaryColor;
    if (previewTheme.borderRadius)
        previewStyle['--preview-radius'] = previewTheme.borderRadius;
    const canvasShellStyle = {
        ...previewStyle,
        fontFamily: previewTheme.fontFamily ?? undefined,
    };
    return (_jsxs(ErrorBoundary, { children: [_jsxs("div", { className: "bg-background flex h-full flex-col overflow-hidden", children: [_jsx(BuilderToolbar, { collectionSlug: collectionSlug, pageSettings: pageSettings, status: status, dirty: dirty, saving: saving, canUndo: canUndo, canRedo: canRedo, deviceMode: deviceMode, onNavigate: onNavigate, onTitleChange: (title) => setPageSettings({ title }), onUndo: undo, onRedo: redo, onDeviceMode: setDeviceMode, onSave: handleSave, onPublish: handlePublish, onOpenAI: () => setAiDialogOpen(true) }), _jsxs("div", { className: "flex flex-1 overflow-hidden", children: [_jsx("div", { className: "bg-muted flex-1 overflow-auto", children: _jsx("div", { className: "mx-auto h-full max-w-full transition-all duration-200", style: { width: canvasWidth }, children: _jsx("div", { className: `bg-background page-builder-canvas-shell h-full ${isConstrained ? 'border-border border-x shadow-lg' : ''}`, style: canvasShellStyle, children: _jsx(BuilderCanvas, { tree: tree, selectedNodeId: selectedNodeId, showGridOverlay: showGridOverlay, deviceMode: deviceMode, onSelectNode: selectNode }) }) }) }), _jsx("div", { className: "border-border bg-card w-[35%] max-w-[420px] min-w-[280px] overflow-y-auto border-l", children: _jsx(ContextPanel, { activeTab: activeTab, onTabChange: setActiveTab, selectedNode: selectedNode, tree: tree, pageSettings: pageSettings, onUpdateSettings: updateSettings, onUpdateBlock: updateBlock, onRemoveNode: removeNodeById, onDuplicateNode: duplicateNode, onMoveNodeUp: moveNodeUp, onMoveNodeDown: moveNodeDown, onPageSettingsChange: setPageSettings, onAddRow: addRowToSection, config: config }) })] }), _jsx(BottomBar, { deviceMode: deviceMode, showGridOverlay: showGridOverlay, onAddSection: addSection, onToggleGrid: setShowGridOverlay })] }), _jsx(AIGenerateDialog, { open: aiDialogOpen, onClose: () => setAiDialogOpen(false), onAccept: handleAIAccept })] }));
}
//# sourceMappingURL=PageBuilder.js.map