"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useExperienceBuilder = exports.ExperienceBuilderIntegration = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const AgentProfiles_js_1 = require("../agent-profiles/AgentProfiles.js");
const WorkflowBuilder_js_1 = require("../workflow-builder/WorkflowBuilder.js");
const Dashboard_js_1 = require("../dashboard/Dashboard.js");
const AdvancedForm_js_1 = require("../forms/AdvancedForm.js");
const NotificationSystem_js_1 = require("../notifications/NotificationSystem.js");
const ResponsiveLayout_js_1 = require("../layout/ResponsiveLayout.js");
const DataTable_js_1 = require("../data-table/DataTable.js");
const ModelRegistry_js_1 = require("../model-registry/ModelRegistry.js");
const AgentFleetDashboard_js_1 = require("../dashboard/AgentFleetDashboard.js");
const UnifiedDashboard_js_1 = require("../dashboard/UnifiedDashboard.js");
const FleetOptimizer_js_1 = require("../dashboard/FleetOptimizer.js");
const MetricChart_js_1 = require("../charts/MetricChart.js");
const Card_js_1 = require("../Card/Card.js");
const Modal_js_1 = require("../feedback/Modal.js");
const Button_js_1 = require("../Button.js");
const lucide_react_1 = require("lucide-react");
/**
 * ExperienceBuilderIntegration - Drupal Experience Builder + React Components
 *
 * A comprehensive integration layer that bridges:
 * - Drupal Experience Builder layouts
 * - React BFUI component library
 * - Server-side rendering (SSR)
 * - Component mapping and discovery
 * - Theme integration
 * - Real-time preview
 * - Layout serialization
 * - Progressive enhancement
 */
const ExperienceBuilderIntegration = ({ initialLayout, componentMappings = {}, theme = 'default', mode = 'render', enableSSR = true, enablePreview = true, enableDrupalIntegration = true, drupalConfig = {}, onLayoutChange, onComponentUpdate, onThemeChange, className = '' }) => {
    // State management
    const [currentLayout, setCurrentLayout] = (0, react_1.useState)(initialLayout);
    const [isEditMode, setIsEditMode] = (0, react_1.useState)(mode === 'edit');
    const [selectedComponent, setSelectedComponent] = (0, react_1.useState)(null);
    const [previewMode, setPreviewMode] = (0, react_1.useState)('desktop');
    const [drupalContext, setDrupalContext] = (0, react_1.useState)(null);
    // Component registry with BFUI mappings
    const componentRegistry = (0, react_1.useMemo)(() => ({
        // AI Platform Components
        'agent_profiles': {
            component: AgentProfiles_js_1.AgentProfiles,
            category: 'ai',
            label: 'Agent Profiles',
            description: 'Comprehensive agent management with real-time updates',
            drupalMapping: 'agent_fleet_dashboard',
            sdcComponent: 'card',
            props: {
                showMetrics: true,
                enableRealtime: true,
                enableBulkOperations: true
            }
        },
        'workflow_builder': {
            component: WorkflowBuilder_js_1.WorkflowBuilder,
            category: 'ai',
            label: 'Workflow Builder',
            description: 'Visual programming interface for AI workflows',
            drupalMapping: 'workflow_builder',
            sdcComponent: 'canvas',
            props: {
                enableAISuggestions: true,
                enableCollaboration: true,
                enableVersionControl: true
            }
        },
        'ai_dashboard': {
            component: Dashboard_js_1.Dashboard,
            category: 'dashboard',
            label: 'AI Platform Dashboard',
            description: 'Real-time AI platform monitoring and analytics',
            drupalMapping: 'unified_dashboard',
            sdcComponent: 'card',
            props: {
                enableRealtime: true,
                enableAlerts: true,
                enableExport: true
            }
        },
        'model_registry': {
            component: ModelRegistry_js_1.ModelRegistry,
            category: 'ai',
            label: 'Model Registry',
            description: 'AI model management and deployment',
            drupalMapping: 'model_registry',
            sdcComponent: 'table',
            props: {
                enableVersioning: true,
                enableDeployment: true,
                showMetrics: true
            }
        },
        // Fleet Management Components
        'agent_fleet_dashboard': {
            component: AgentFleetDashboard_js_1.AgentFleetDashboard,
            category: 'dashboard',
            label: 'Agent Fleet Dashboard',
            description: 'Comprehensive agent fleet monitoring',
            drupalMapping: 'agent_fleet_dashboard',
            sdcComponent: 'card',
            props: {
                showTopology: true,
                enableOrchestration: true,
                showMetrics: true
            }
        },
        'unified_dashboard': {
            component: UnifiedDashboard_js_1.UnifiedDashboard,
            category: 'dashboard',
            label: 'Unified Dashboard',
            description: 'Comprehensive platform overview',
            drupalMapping: 'unified_dashboard',
            sdcComponent: 'grid',
            props: {
                configurable: true,
                enableWidgets: true,
                showAlerts: true
            }
        },
        'fleet_optimizer': {
            component: FleetOptimizer_js_1.FleetOptimizer,
            category: 'analytics',
            label: 'Fleet Optimizer',
            description: 'AI-powered optimization tools',
            drupalMapping: 'fleet_optimizer',
            sdcComponent: 'card',
            props: {
                enableAI: true,
                showRecommendations: true,
                enableAutoOptimization: false
            }
        },
        // Data & Analytics Components
        'data_table': {
            component: DataTable_js_1.DataTable,
            category: 'data',
            label: 'Advanced Data Table',
            description: 'High-performance data table with virtualization',
            drupalMapping: 'data_table',
            sdcComponent: 'table',
            props: {
                virtualized: true,
                enableFiltering: true,
                enableExport: true
            }
        },
        'metric_chart': {
            component: MetricChart_js_1.MetricChart,
            category: 'analytics',
            label: 'Metric Chart',
            description: 'Interactive charts for metrics visualization',
            drupalMapping: 'metric_chart',
            sdcComponent: 'card',
            props: {
                type: 'line',
                enableZoom: true,
                showLegend: true
            }
        },
        // Form & Input Components
        'advanced_form': {
            component: AdvancedForm_js_1.AdvancedForm,
            category: 'forms',
            label: 'AI-Powered Form',
            description: 'Advanced form system with AI validation',
            drupalMapping: 'advanced_form',
            sdcComponent: 'form',
            props: {
                enableAI: true,
                enableAutoSave: true,
                enableValidationSummary: true
            }
        },
        // Layout & UI Components
        'responsive_layout': {
            component: ResponsiveLayout_js_1.ResponsiveLayout,
            category: 'layout',
            label: 'Responsive Layout',
            description: 'Advanced responsive layout system',
            drupalMapping: 'responsive_layout',
            sdcComponent: 'grid',
            props: {
                enableEditor: true,
                enablePreview: true,
                enableThemeEditor: true
            }
        },
        'notification_system': {
            component: NotificationSystem_js_1.NotificationSystem,
            category: 'feedback',
            label: 'Notification System',
            description: 'Real-time notification management',
            drupalMapping: 'notification_system',
            sdcComponent: 'overlay',
            props: {
                enableRealtime: true,
                enablePersistence: true,
                enableSound: true
            }
        },
        // Basic UI Components
        'bfui_card': {
            component: Card_js_1.Card,
            category: 'layout',
            label: 'Enhanced Card',
            description: 'Card component with React interactivity',
            drupalMapping: 'bfui_card',
            sdcComponent: 'card',
            props: {
                elevation: 2,
                interactive: true
            }
        },
        'bfui_modal': {
            component: Modal_js_1.Modal,
            category: 'feedback',
            label: 'Interactive Modal',
            description: 'Modal dialog with React features',
            drupalMapping: 'bfui_modal',
            sdcComponent: 'modal',
            props: {
                closeOnOverlayClick: true,
                showCloseButton: true
            }
        },
        // Custom mappings from props
        ...componentMappings
    }), [componentMappings]);
    // Drupal integration
    (0, react_1.useEffect)(() => {
        if (enableDrupalIntegration && typeof window !== 'undefined') {
            // Initialize Drupal context
            const drupalSettings = window.drupalSettings;
            if (drupalSettings?.experienceBuilder) {
                setDrupalContext(drupalSettings.experienceBuilder);
            }
            // Listen for Drupal Experience Builder events
            const handleDrupalLayoutChange = (event) => {
                const { layout } = event.detail;
                setCurrentLayout(layout);
                onLayoutChange?.(layout);
            };
            const handleDrupalComponentUpdate = (event) => {
                const { componentId, updates } = event.detail;
                onComponentUpdate?.(componentId, updates);
            };
            window.addEventListener('drupal:experience-builder:layout-change', handleDrupalLayoutChange);
            window.addEventListener('drupal:experience-builder:component-update', handleDrupalComponentUpdate);
            return () => {
                window.removeEventListener('drupal:experience-builder:layout-change', handleDrupalLayoutChange);
                window.removeEventListener('drupal:experience-builder:component-update', handleDrupalComponentUpdate);
            };
        }
    }, [enableDrupalIntegration, onLayoutChange, onComponentUpdate]);
    // SSR support
    (0, react_1.useEffect)(() => {
        if (enableSSR && typeof window !== 'undefined') {
            // Progressive enhancement - take over from server-rendered content
            const existingLayout = document.querySelector('[data-experience-builder-layout]');
            if (existingLayout) {
                try {
                    const layoutData = JSON.parse(existingLayout.getAttribute('data-layout') || '{}');
                    setCurrentLayout(layoutData);
                }
                catch (error) {
                    console.warn('Failed to parse server-rendered layout data:', error);
                }
            }
        }
    }, [enableSSR]);
    // Layout change handling
    const handleLayoutChange = (0, react_1.useCallback)((newLayout) => {
        setCurrentLayout(newLayout);
        onLayoutChange?.(newLayout);
        // Send to Drupal if integration is enabled
        if (enableDrupalIntegration && typeof window !== 'undefined') {
            window.dispatchEvent(new CustomEvent('react:experience-builder:layout-change', {
                detail: { layout: newLayout }
            }));
        }
    }, [onLayoutChange, enableDrupalIntegration]);
    // Component update handling
    const handleComponentUpdate = (0, react_1.useCallback)((componentId, updates) => {
        const newLayout = {
            ...currentLayout,
            regions: currentLayout.regions.map(region => ({
                ...region,
                components: region.components.map(component => component.id === componentId ? { ...component, ...updates } : component)
            }))
        };
        handleLayoutChange(newLayout);
        onComponentUpdate?.(componentId, updates);
    }, [currentLayout, handleLayoutChange, onComponentUpdate]);
    // Render component by type
    const renderComponent = (0, react_1.useCallback)((componentConfig) => {
        const mapping = componentRegistry[componentConfig.type];
        if (!mapping) {
            console.warn(`Component type "${componentConfig.type}" not found in registry`);
            return ((0, jsx_runtime_1.jsx)("div", { className: "experience-builder-error", children: (0, jsx_runtime_1.jsxs)("p", { children: ["Component \"", componentConfig.type, "\" not found"] }) }));
        }
        const Component = mapping.component;
        const props = {
            ...mapping.props,
            ...componentConfig.props,
            key: componentConfig.id,
            'data-experience-builder-component': componentConfig.id,
            'data-drupal-mapping': mapping.drupalMapping,
            'data-sdc-component': mapping.sdcComponent
        };
        // Add edit mode props
        if (isEditMode) {
            props.onUpdate = (updates) => handleComponentUpdate(componentConfig.id, updates);
            props.onSelect = () => setSelectedComponent(componentConfig.id);
            props.selected = selectedComponent === componentConfig.id;
            props.editable = true;
        }
        return (0, jsx_runtime_1.jsx)(Component, { ...props });
    }, [componentRegistry, isEditMode, selectedComponent, handleComponentUpdate]);
    // Render layout region
    const renderRegion = (0, react_1.useCallback)((region) => {
        return ((0, jsx_runtime_1.jsx)("div", { className: `experience-builder-region ${region.className || ''}`, "data-region-id": region.id, "data-region-type": region.type, style: region.style, children: region.components.map(renderComponent) }, region.id));
    }, [renderComponent]);
    // Export layout for Drupal
    const exportToDrupal = (0, react_1.useCallback)(() => {
        const exportData = {
            layout: currentLayout,
            componentMappings: Object.entries(componentRegistry).reduce((acc, [key, mapping]) => {
                acc[key] = {
                    drupalMapping: mapping.drupalMapping,
                    sdcComponent: mapping.sdcComponent,
                    category: mapping.category
                };
                return acc;
            }, {}),
            theme,
            timestamp: new Date().toISOString()
        };
        // Send to Drupal backend
        if (enableDrupalIntegration) {
            fetch('/admin/experience-builder/export', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify(exportData)
            }).then(response => {
                if (response.ok) {
                    console.log('Layout exported to Drupal successfully');
                }
            }).catch(error => {
                console.error('Failed to export layout to Drupal:', error);
            });
        }
        return exportData;
    }, [currentLayout, componentRegistry, theme, enableDrupalIntegration]);
    // Toolbar for edit mode
    const renderToolbar = () => {
        if (!isEditMode && !enablePreview)
            return null;
        return ((0, jsx_runtime_1.jsxs)("div", { className: "experience-builder-toolbar", children: [(0, jsx_runtime_1.jsxs)("div", { className: "toolbar-section", children: [(0, jsx_runtime_1.jsxs)(Button_js_1.Button, { variant: isEditMode ? 'primary' : 'outline', size: "sm", onClick: () => setIsEditMode(!isEditMode), children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Layout, { className: "w-4 h-4 mr-2" }), isEditMode ? 'Exit Edit' : 'Edit Mode'] }), enablePreview && ((0, jsx_runtime_1.jsxs)("div", { className: "preview-controls", children: [(0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: previewMode === 'desktop' ? 'primary' : 'outline', size: "sm", onClick: () => setPreviewMode('desktop'), children: "Desktop" }), (0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: previewMode === 'tablet' ? 'primary' : 'outline', size: "sm", onClick: () => setPreviewMode('tablet'), children: "Tablet" }), (0, jsx_runtime_1.jsx)(Button_js_1.Button, { variant: previewMode === 'mobile' ? 'primary' : 'outline', size: "sm", onClick: () => setPreviewMode('mobile'), children: "Mobile" })] }))] }), (0, jsx_runtime_1.jsxs)("div", { className: "toolbar-section", children: [(0, jsx_runtime_1.jsxs)(Button_js_1.Button, { variant: "outline", size: "sm", onClick: exportToDrupal, children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Save, { className: "w-4 h-4 mr-2" }), "Save to Drupal"] }), (0, jsx_runtime_1.jsxs)(Button_js_1.Button, { variant: "outline", size: "sm", onClick: () => {
                                const data = exportToDrupal();
                                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                                const url = URL.createObjectURL(blob);
                                const a = document.createElement('a');
                                a.href = url;
                                a.download = `experience-builder-layout-${Date.now()}.json`;
                                a.click();
                                URL.revokeObjectURL(url);
                            }, children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Download, { className: "w-4 h-4 mr-2" }), "Export"] })] })] }));
    };
    // Component palette for edit mode
    const renderComponentPalette = () => {
        if (!isEditMode)
            return null;
        const categories = Object.entries(componentRegistry).reduce((acc, [key, mapping]) => {
            if (!acc[mapping.category]) {
                acc[mapping.category] = [];
            }
            acc[mapping.category].push({ key, ...mapping });
            return acc;
        }, {});
        return ((0, jsx_runtime_1.jsxs)("div", { className: "experience-builder-palette", children: [(0, jsx_runtime_1.jsx)("h3", { className: "palette-title", children: "Components" }), Object.entries(categories).map(([category, components]) => ((0, jsx_runtime_1.jsxs)("div", { className: "palette-category", children: [(0, jsx_runtime_1.jsx)("h4", { className: "category-title", children: category.charAt(0).toUpperCase() + category.slice(1) }), (0, jsx_runtime_1.jsx)("div", { className: "component-list", children: components.map(component => ((0, jsx_runtime_1.jsxs)("button", { className: "component-item", onClick: () => {
                                    // Add component to layout
                                    const newComponent = {
                                        id: `${component.key}_${Date.now()}`,
                                        type: component.key,
                                        props: { ...component.props }
                                    };
                                    // Add to first region or create new region
                                    const newLayout = { ...currentLayout };
                                    if (newLayout.regions.length === 0) {
                                        newLayout.regions.push({
                                            id: 'main',
                                            type: 'main',
                                            components: [newComponent]
                                        });
                                    }
                                    else {
                                        newLayout.regions[0].components.push(newComponent);
                                    }
                                    handleLayoutChange(newLayout);
                                }, children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Layers, { className: "w-4 h-4" }), (0, jsx_runtime_1.jsx)("span", { children: component.label })] }, component.key))) })] }, category)))] }));
    };
    return ((0, jsx_runtime_1.jsxs)("div", { className: `experience-builder-integration ${previewMode} ${isEditMode ? 'edit-mode' : 'view-mode'} ${className}`, "data-experience-builder-layout": currentLayout.id, "data-layout": JSON.stringify(currentLayout), "data-theme": theme, children: [renderToolbar(), (0, jsx_runtime_1.jsxs)("div", { className: "experience-builder-content", children: [isEditMode && renderComponentPalette(), (0, jsx_runtime_1.jsx)("div", { className: "experience-builder-canvas", children: currentLayout.regions.map(renderRegion) })] }), enableSSR && ((0, jsx_runtime_1.jsx)("script", { type: "application/json", id: "experience-builder-ssr-data", dangerouslySetInnerHTML: {
                    __html: JSON.stringify({
                        layout: currentLayout,
                        componentMappings: componentRegistry,
                        theme,
                        mode,
                        drupalConfig
                    })
                } }))] }));
};
exports.ExperienceBuilderIntegration = ExperienceBuilderIntegration;
// Hook for accessing Experience Builder context
const useExperienceBuilder = () => {
    const [layout, setLayout] = (0, react_1.useState)(null);
    const [isLoading, setIsLoading] = (0, react_1.useState)(true);
    (0, react_1.useEffect)(() => {
        // Load layout from Drupal or localStorage
        const loadLayout = async () => {
            try {
                setIsLoading(true);
                // Try Drupal first
                if (typeof window !== 'undefined' && window.drupalSettings?.experienceBuilder) {
                    const drupalLayout = window.drupalSettings.experienceBuilder.layout;
                    if (drupalLayout) {
                        setLayout(drupalLayout);
                        return;
                    }
                }
                // Fallback to localStorage
                const savedLayout = localStorage.getItem('experience-builder-layout');
                if (savedLayout) {
                    setLayout(JSON.parse(savedLayout));
                }
            }
            catch (error) {
                console.error('Failed to load Experience Builder layout:', error);
            }
            finally {
                setIsLoading(false);
            }
        };
        loadLayout();
    }, []);
    const updateLayout = (0, react_1.useCallback)((newLayout) => {
        setLayout(newLayout);
        localStorage.setItem('experience-builder-layout', JSON.stringify(newLayout));
    }, []);
    return {
        layout,
        setLayout: updateLayout,
        isLoading
    };
};
exports.useExperienceBuilder = useExperienceBuilder;
exports.default = exports.ExperienceBuilderIntegration;
//# sourceMappingURL=ExperienceBuilderIntegration.js.map