"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ResponsiveLayout = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const useMediaQuery_js_1 = require("./hooks/useMediaQuery.js");
const useLayoutPersistence_js_1 = require("./hooks/useLayoutPersistence.js");
const useThemeManager_js_1 = require("./hooks/useThemeManager.js");
const useLayoutOptimization_js_1 = require("./hooks/useLayoutOptimization.js");
const GridSystem_js_1 = require("./components/GridSystem.js");
const LayoutRegion_js_1 = require("./components/LayoutRegion.js");
const ThemeProvider_js_1 = require("./components/ThemeProvider.js");
const LayoutToolbar_js_1 = require("./components/LayoutToolbar.js");
const BreakpointIndicator_js_1 = require("./components/BreakpointIndicator.js");
const LayoutPreview_js_1 = require("./components/LayoutPreview.js");
const ResponsiveControls_js_1 = require("./components/ResponsiveControls.js");
const ComponentPalette_js_1 = require("./components/ComponentPalette.js");
const Modal_js_1 = require("../feedback/Modal.js");
const Button_js_1 = require("../Button.js");
const lucide_react_1 = require("lucide-react");
/**
 * ResponsiveLayout - Advanced Responsive Layout System
 *
 * A comprehensive layout system featuring:
 * - Responsive grid system with breakpoints
 * - Advanced theme management with CSS variables
 * - Drag-and-drop layout builder
 * - Component-based architecture
 * - Real-time preview across devices
 * - Layout persistence and sharing
 * - Performance optimization
 * - Accessibility compliance
 * - CSS Grid and Flexbox support
 * - Design system integration
 * - Code generation and export
 */
const ResponsiveLayout = ({ initialLayout, breakpoints = {
    xs: 320,
    sm: 640,
    md: 768,
    lg: 1024,
    xl: 1280,
    '2xl': 1536
}, themes = {}, components = [], onLayoutChange, onThemeChange, enableEditor = false, enablePreview = true, enableThemeEditor = true, enableResponsivePreview = true, enableCodeGeneration = false, persistenceKey, className = '', constraints = {}, optimizations = {
    lazyLoad: true,
    virtualScrolling: true,
    imageOptimization: true,
    cssOptimization: true
} }) => {
    // State management
    const [currentLayout, setCurrentLayout] = (0, react_1.useState)(initialLayout);
    const [activeBreakpoint, setActiveBreakpoint] = (0, react_1.useState)('lg');
    const [isEditorMode, setIsEditorMode] = (0, react_1.useState)(enableEditor);
    const [isPreviewMode, setIsPreviewMode] = (0, react_1.useState)(false);
    const [selectedRegion, setSelectedRegion] = (0, react_1.useState)(null);
    const [showThemeEditor, setShowThemeEditor] = (0, react_1.useState)(false);
    const [showResponsivePreview, setShowResponsivePreview] = (0, react_1.useState)(false);
    const [showComponentPalette, setShowComponentPalette] = (0, react_1.useState)(false);
    const [showCodeExport, setShowCodeExport] = (0, react_1.useState)(false);
    const [draggedComponent, setDraggedComponent] = (0, react_1.useState)(null);
    // Refs
    const layoutRef = (0, react_1.useRef)(null);
    const previewRef = (0, react_1.useRef)(null);
    // Media queries for breakpoint detection
    const isXs = (0, useMediaQuery_js_1.useMediaQuery)(`(max-width: ${breakpoints.sm - 1}px)`);
    const isSm = (0, useMediaQuery_js_1.useMediaQuery)(`(min-width: ${breakpoints.sm}px) and (max-width: ${breakpoints.md - 1}px)`);
    const isMd = (0, useMediaQuery_js_1.useMediaQuery)(`(min-width: ${breakpoints.md}px) and (max-width: ${breakpoints.lg - 1}px)`);
    const isLg = (0, useMediaQuery_js_1.useMediaQuery)(`(min-width: ${breakpoints.lg}px) and (max-width: ${breakpoints.xl - 1}px)`);
    const isXl = (0, useMediaQuery_js_1.useMediaQuery)(`(min-width: ${breakpoints.xl}px) and (max-width: ${breakpoints['2xl'] - 1}px)`);
    const is2Xl = (0, useMediaQuery_js_1.useMediaQuery)(`(min-width: ${breakpoints['2xl']}px)`);
    // Custom hooks
    const { currentTheme, availableThemes, setTheme, customizeTheme, exportTheme, importTheme, resetTheme } = (0, useThemeManager_js_1.useThemeManager)(themes);
    const { saveLayout, loadLayout, getLayoutHistory, shareLayout, importLayout } = (0, useLayoutPersistence_js_1.useLayoutPersistence)(persistenceKey);
    const { optimizeLayout, analyzePerformance, generateOptimizations, applyOptimizations } = (0, useLayoutOptimization_js_1.useLayoutOptimization)(optimizations);
    // Breakpoint detection
    (0, react_1.useEffect)(() => {
        if (isXs)
            setActiveBreakpoint('xs');
        else if (isSm)
            setActiveBreakpoint('sm');
        else if (isMd)
            setActiveBreakpoint('md');
        else if (isLg)
            setActiveBreakpoint('lg');
        else if (isXl)
            setActiveBreakpoint('xl');
        else if (is2Xl)
            setActiveBreakpoint('2xl');
    }, [isXs, isSm, isMd, isLg, isXl, is2Xl]);
    // Layout change handling
    (0, react_1.useEffect)(() => {
        onLayoutChange?.(currentLayout, activeBreakpoint);
    }, [currentLayout, activeBreakpoint, onLayoutChange]);
    // Theme change handling
    (0, react_1.useEffect)(() => {
        onThemeChange?.(currentTheme);
    }, [currentTheme, onThemeChange]);
    // Auto-save layout
    (0, react_1.useEffect)(() => {
        if (persistenceKey && currentLayout) {
            const autoSaveTimer = setTimeout(() => {
                saveLayout(currentLayout);
            }, 2000);
            return () => clearTimeout(autoSaveTimer);
        }
    }, [currentLayout, persistenceKey, saveLayout]);
    // Layout management
    const updateLayout = (0, react_1.useCallback)((newLayout) => {
        setCurrentLayout(newLayout);
    }, []);
    const updateRegion = (0, react_1.useCallback)((regionId, updates) => {
        setCurrentLayout(prev => ({
            ...prev,
            regions: prev.regions.map(region => region.id === regionId ? { ...region, ...updates } : region)
        }));
    }, []);
    const addRegion = (0, react_1.useCallback)((region) => {
        setCurrentLayout(prev => ({
            ...prev,
            regions: [...prev.regions, region]
        }));
    }, []);
    const removeRegion = (0, react_1.useCallback)((regionId) => {
        setCurrentLayout(prev => ({
            ...prev,
            regions: prev.regions.filter(region => region.id !== regionId)
        }));
    }, []);
    const duplicateRegion = (0, react_1.useCallback)((regionId) => {
        const region = currentLayout.regions.find(r => r.id === regionId);
        if (region) {
            const duplicate = {
                ...region,
                id: `${region.id}_copy_${Date.now()}`,
                position: {
                    ...region.position,
                    x: region.position.x + 1,
                    y: region.position.y + 1
                }
            };
            addRegion(duplicate);
        }
    }, [currentLayout.regions, addRegion]);
    // Component management
    const addComponent = (0, react_1.useCallback)((component, regionId, position) => {
        const newComponent = {
            ...component,
            id: `${component.type}_${Date.now()}`,
            position: position || { x: 0, y: 0 }
        };
        updateRegion(regionId, {
            components: [
                ...(currentLayout.regions.find(r => r.id === regionId)?.components || []),
                newComponent
            ]
        });
    }, [currentLayout.regions, updateRegion]);
    const removeComponent = (0, react_1.useCallback)((componentId, regionId) => {
        const region = currentLayout.regions.find(r => r.id === regionId);
        if (region) {
            updateRegion(regionId, {
                components: region.components.filter(c => c.id !== componentId)
            });
        }
    }, [currentLayout.regions, updateRegion]);
    const updateComponent = (0, react_1.useCallback)((componentId, regionId, updates) => {
        const region = currentLayout.regions.find(r => r.id === regionId);
        if (region) {
            updateRegion(regionId, {
                components: region.components.map(c => c.id === componentId ? { ...c, ...updates } : c)
            });
        }
    }, [currentLayout.regions, updateRegion]);
    // Drag and drop handling
    const handleDragStart = (0, react_1.useCallback)((component) => {
        setDraggedComponent(component);
    }, []);
    const handleDragEnd = (0, react_1.useCallback)(() => {
        setDraggedComponent(null);
    }, []);
    const handleDrop = (0, react_1.useCallback)((regionId, position) => {
        if (draggedComponent) {
            addComponent(draggedComponent, regionId, position);
            setDraggedComponent(null);
        }
    }, [draggedComponent, addComponent]);
    // Layout operations
    const resetLayout = (0, react_1.useCallback)(() => {
        setCurrentLayout(initialLayout);
    }, [initialLayout]);
    const optimizeCurrentLayout = (0, react_1.useCallback)(async () => {
        const optimized = await optimizeLayout(currentLayout);
        setCurrentLayout(optimized);
    }, [currentLayout, optimizeLayout]);
    const exportLayout = (0, react_1.useCallback)(() => {
        const exportData = {
            layout: currentLayout,
            theme: currentTheme,
            breakpoints,
            timestamp: new Date().toISOString(),
            version: '1.0'
        };
        const blob = new Blob([JSON.stringify(exportData, null, 2)], {
            type: 'application/json'
        });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `layout-${Date.now()}.json`;
        link.click();
        URL.revokeObjectURL(url);
    }, [currentLayout, currentTheme, breakpoints]);
    const importLayoutFile = (0, react_1.useCallback)((event) => {
        const file = event.target.files?.[0];
        if (!file)
            return;
        const reader = new FileReader();
        reader.onload = (e) => {
            try {
                const importData = JSON.parse(e.target?.result);
                if (importData.layout) {
                    setCurrentLayout(importData.layout);
                }
                if (importData.theme) {
                    setTheme(importData.theme);
                }
            }
            catch (error) {
                console.error('Failed to import layout:', error);
            }
        };
        reader.readAsText(file);
    }, [setTheme]);
    // Code generation
    const generateCode = (0, react_1.useCallback)(() => {
        const cssCode = generateCSSFromLayout(currentLayout, currentTheme, breakpoints);
        const htmlCode = generateHTMLFromLayout(currentLayout);
        const reactCode = generateReactFromLayout(currentLayout);
        return {
            css: cssCode,
            html: htmlCode,
            react: reactCode
        };
    }, [currentLayout, currentTheme, breakpoints]);
    // Responsive configuration for current breakpoint
    const responsiveConfig = (0, react_1.useMemo)(() => {
        return currentLayout.responsive?.[activeBreakpoint] || {
            columns: 12,
            gap: 16,
            margins: 16
        };
    }, [currentLayout, activeBreakpoint]);
    // Render functions
    const renderRegion = (region) => {
        return ((0, jsx_runtime_1.jsx)(LayoutRegion_js_1.LayoutRegionComponent, { region: region, isSelected: selectedRegion === region.id, isEditable: isEditorMode, breakpoint: activeBreakpoint, theme: currentTheme, onSelect: () => setSelectedRegion(region.id), onUpdate: (updates) => updateRegion(region.id, updates), onRemove: () => removeRegion(region.id), onDuplicate: () => duplicateRegion(region.id), onDrop: (position) => handleDrop(region.id, position), onComponentUpdate: (componentId, updates) => updateComponent(componentId, region.id, updates), onComponentRemove: (componentId) => removeComponent(componentId, region.id), constraints: constraints }, region.id));
    };
    const renderLayout = () => {
        return ((0, jsx_runtime_1.jsx)(GridSystem_js_1.GridSystem, { config: responsiveConfig, breakpoint: activeBreakpoint, theme: currentTheme, isEditable: isEditorMode, constraints: constraints, className: "layout-grid", children: currentLayout.regions.map(renderRegion) }));
    };
    return ((0, jsx_runtime_1.jsx)(ThemeProvider_js_1.ThemeProvider, { theme: currentTheme, children: (0, jsx_runtime_1.jsxs)("div", { ref: layoutRef, className: `responsive-layout ${activeBreakpoint} ${isEditorMode ? 'editor-mode' : ''} ${className}`, "data-theme": currentTheme.name, style: {
                '--grid-columns': responsiveConfig.columns,
                '--grid-gap': `${responsiveConfig.gap}px`,
                '--grid-margins': `${responsiveConfig.margins}px`
            }, children: [(isEditorMode || enablePreview) && ((0, jsx_runtime_1.jsx)(LayoutToolbar_js_1.LayoutToolbar, { currentBreakpoint: activeBreakpoint, isEditorMode: isEditorMode, isPreviewMode: isPreviewMode, onBreakpointChange: setActiveBreakpoint, onEditorToggle: () => setIsEditorMode(!isEditorMode), onPreviewToggle: () => setIsPreviewMode(!isPreviewMode), onThemeEditor: () => setShowThemeEditor(true), onResponsivePreview: () => setShowResponsivePreview(true), onComponentPalette: () => setShowComponentPalette(true), onCodeExport: enableCodeGeneration ? () => setShowCodeExport(true) : undefined, onSave: () => saveLayout(currentLayout), onExport: exportLayout, onImport: (event) => importLayoutFile(event), onReset: resetLayout, onOptimize: optimizeCurrentLayout, enableThemeEditor: enableThemeEditor, enableResponsivePreview: enableResponsivePreview, enableCodeGeneration: enableCodeGeneration })), (0, jsx_runtime_1.jsx)(BreakpointIndicator_js_1.BreakpointIndicator, { current: activeBreakpoint, breakpoints: breakpoints, onBreakpointChange: setActiveBreakpoint }), (0, jsx_runtime_1.jsx)("div", { className: "layout-container", children: isPreviewMode ? ((0, jsx_runtime_1.jsx)(LayoutPreview_js_1.LayoutPreview, { layout: currentLayout, theme: currentTheme, breakpoint: activeBreakpoint, components: components, optimizations: optimizations })) : (renderLayout()) }), showComponentPalette && isEditorMode && ((0, jsx_runtime_1.jsx)(ComponentPalette_js_1.ComponentPalette, { components: components, onComponentDragStart: handleDragStart, onComponentDragEnd: handleDragEnd, onClose: () => setShowComponentPalette(false) })), showResponsivePreview && enableResponsivePreview && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showResponsivePreview, onClose: () => setShowResponsivePreview(false), title: "Responsive Preview", size: "full", children: (0, jsx_runtime_1.jsx)(ResponsiveControls_js_1.ResponsiveControls, { layout: currentLayout, theme: currentTheme, breakpoints: breakpoints, components: components, onBreakpointChange: setActiveBreakpoint, currentBreakpoint: activeBreakpoint }) })), showThemeEditor && enableThemeEditor && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showThemeEditor, onClose: () => setShowThemeEditor(false), title: "Theme Editor", size: "lg", children: (0, jsx_runtime_1.jsxs)("div", { className: "theme-editor space-y-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "theme-selector", children: [(0, jsx_runtime_1.jsx)("label", { className: "block text-sm font-medium mb-2", children: "Base Theme" }), (0, jsx_runtime_1.jsx)("select", { className: "form-select w-full", value: currentTheme.name, onChange: (e) => setTheme(availableThemes[e.target.value]), children: Object.keys(availableThemes).map(themeName => ((0, jsx_runtime_1.jsx)("option", { value: themeName, children: themeName.charAt(0).toUpperCase() + themeName.slice(1) }, themeName))) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "color-customization", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-medium mb-4", children: "Colors" }), (0, jsx_runtime_1.jsx)("div", { className: "grid grid-cols-2 gap-4", children: Object.entries(currentTheme.colors || {}).map(([key, value]) => ((0, jsx_runtime_1.jsxs)("div", { className: "color-input", children: [(0, jsx_runtime_1.jsx)("label", { className: "block text-sm font-medium mb-1", children: key.replace(/([A-Z])/g, ' $1').toLowerCase() }), (0, jsx_runtime_1.jsxs)("div", { className: "flex items-center space-x-2", children: [(0, jsx_runtime_1.jsx)("input", { type: "color", value: value, onChange: (e) => customizeTheme({
                                                                colors: { ...currentTheme.colors, [key]: e.target.value }
                                                            }), className: "w-8 h-8 rounded border" }), (0, jsx_runtime_1.jsx)("input", { type: "text", value: value, onChange: (e) => customizeTheme({
                                                                colors: { ...currentTheme.colors, [key]: e.target.value }
                                                            }), className: "form-input flex-1" })] })] }, key))) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "theme-actions", children: [(0, jsx_runtime_1.jsxs)(Button_js_1.Button, { onClick: () => exportTheme(currentTheme), children: [(0, jsx_runtime_1.jsx)(lucide_react_1.Download, { className: "w-4 h-4 mr-2" }), "Export Theme"] }), (0, jsx_runtime_1.jsxs)(Button_js_1.Button, { variant: "outline", onClick: resetTheme, children: [(0, jsx_runtime_1.jsx)(lucide_react_1.RotateCcw, { className: "w-4 h-4 mr-2" }), "Reset Theme"] })] })] }) })), showCodeExport && enableCodeGeneration && ((0, jsx_runtime_1.jsx)(Modal_js_1.Modal, { isOpen: showCodeExport, onClose: () => setShowCodeExport(false), title: "Generated Code", size: "xl", children: (0, jsx_runtime_1.jsx)("div", { className: "code-export", children: (() => {
                            const generatedCode = generateCode();
                            return ((0, jsx_runtime_1.jsxs)("div", { className: "space-y-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "code-section", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-medium mb-2", children: "CSS" }), (0, jsx_runtime_1.jsx)("pre", { className: "bg-gray-100 p-4 rounded text-sm overflow-auto max-h-64", children: (0, jsx_runtime_1.jsx)("code", { children: generatedCode.css }) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "code-section", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-medium mb-2", children: "HTML" }), (0, jsx_runtime_1.jsx)("pre", { className: "bg-gray-100 p-4 rounded text-sm overflow-auto max-h-64", children: (0, jsx_runtime_1.jsx)("code", { children: generatedCode.html }) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "code-section", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-medium mb-2", children: "React" }), (0, jsx_runtime_1.jsx)("pre", { className: "bg-gray-100 p-4 rounded text-sm overflow-auto max-h-64", children: (0, jsx_runtime_1.jsx)("code", { children: generatedCode.react }) })] })] }));
                        })() }) })), isEditorMode && selectedRegion && ((0, jsx_runtime_1.jsx)("div", { className: "selection-overlay", children: (0, jsx_runtime_1.jsxs)("div", { className: "selection-toolbar", children: [(0, jsx_runtime_1.jsx)(Button_js_1.Button, { size: "sm", onClick: () => duplicateRegion(selectedRegion), children: "Duplicate" }), (0, jsx_runtime_1.jsx)(Button_js_1.Button, { size: "sm", variant: "danger", onClick: () => removeRegion(selectedRegion), children: "Delete" })] }) }))] }) }));
};
exports.ResponsiveLayout = ResponsiveLayout;
// Helper functions for code generation
function generateCSSFromLayout(layout, theme, breakpoints) {
    // Generate CSS from layout and theme
    return `/* Generated CSS */
.layout-grid {
  display: grid;
  grid-template-columns: repeat(var(--grid-columns), 1fr);
  gap: var(--grid-gap);
  margin: var(--grid-margins);
}

/* Theme Variables */
:root {
  ${Object.entries(theme.colors || {}).map(([key, value]) => `--color-${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`).join('\n  ')}
}

/* Responsive Breakpoints */
${Object.entries(breakpoints).map(([name, size]) => `
@media (min-width: ${size}px) {
  .layout-${name} {
    /* Breakpoint-specific styles */
  }
}`).join('\n')}`;
}
function generateHTMLFromLayout(layout) {
    // Generate HTML structure from layout
    return `<!-- Generated HTML -->
<div class="layout-grid">
  ${layout.regions.map(region => `
  <div class="layout-region" data-region-id="${region.id}">
    ${region.components.map(component => `
    <div class="layout-component ${component.type}" data-component-id="${component.id}">
      <!-- ${component.type} component -->
    </div>`).join('')}
  </div>`).join('')}
</div>`;
}
function generateReactFromLayout(layout) {
    // Generate React component from layout
    return `// Generated React Component
import React from 'react';

export const GeneratedLayout = () => {
  return (
    <div className="layout-grid">
      ${layout.regions.map(region => `
      <div className="layout-region" data-region-id="${region.id}">
        ${region.components.map(component => `
        <${component.type.charAt(0).toUpperCase() + component.type.slice(1)}Component 
          id="${component.id}"
          {...${JSON.stringify(component.props || {})}}
        />`).join('')}
      </div>`).join('')}
    </div>
  );
};`;
}
exports.default = exports.ResponsiveLayout;
//# sourceMappingURL=ResponsiveLayout.js.map