import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import {
  Box,
  Flex,
  IconButton,
  VStack,
  HStack,
  Text,
  Button,
  useToast,
  Tooltip,
  Badge,
  useColorModeValue,
  Portal,
  Image,
  SimpleGrid,
  Heading,
  Divider,
  Tabs,
  TabList,
  TabPanels,
  Tab,
  TabPanel,
  FormControl,
  FormLabel,
  Input,
  Slider,
  SliderTrack,
  SliderFilledTrack,
  SliderThumb,
  Select,
  Switch,
  NumberInput,
  NumberInputField,
  NumberInputStepper,
  NumberIncrementStepper,
  NumberDecrementStepper,
  Icon,
} from '@chakra-ui/react';
import {
  FaPlus,
  FaCog,
  FaPaintBrush,
  FaLayerGroup,
  FaCube,
  FaRegEye,
  FaAngleLeft,
  FaAngleRight,
  FaTrash,
  FaGripVertical,
  FaChevronDown,
  FaChevronUp,
  FaMagic,
  FaRegSave,
  FaFileAlt,
  FaFileImport,
  FaExternalLinkAlt,
  FaBolt,
  FaFilter,
  FaBoxOpen,
  FaSearch,
  FaShapes,
  FaCopy,
  FaPaste,
  FaUndo,
  FaRedo,
  FaThLarge,
  FaNewspaper,
  FaPhotoVideo,
  FaGamepad,
  FaFutbol,
  FaSmile,
  FaExclamationCircle
} from 'react-icons/fa';
import {
  FiMonitor,
  FiTablet,
  FiSmartphone,
  FiSave,
  FiX,
  FiEdit,
  FiMove,
  FiChevronUp,
  FiChevronDown,
  FiTrash2,
  FiEyeOff,
  FiSettings,
  FiLock,
  FiAlertTriangle
} from 'react-icons/fi';
import {
  PageElementConfig,
  getPageElementConfigs,
  batchUpdatePageElementConfigs,
  ELEMENT_VARIANTS,
  ElementVariant,
  PREDEFINED_ELEMENTS,
  PredefinedElement,
} from '../../services/pageElements';
import { safeDOM } from '../../services/myuibrix';
import { useAuth } from '../../contexts/AuthContext';
import { useClubTheme } from '../../contexts/ClubThemeContext';
import VisualStylePanel from './VisualStylePanel';
import { DEFAULT_HOMEPAGE_ELEMENTS, HOMEPAGE_IMPLEMENTED_ELEMENTS } from '../../data/defaultElements';

const SUPPORTED_HOME_VARIANTS: Record<string, string[]> = {
  hero: ['grid', 'scroller', 'swiper', 'swiper_full'],
  news: ['grid', 'scroller'],
  matches: ['compact'],
  sponsors: ['grid', 'slider', 'scroller', 'pyramid'],
  gallery: ['grid'],
  videos: ['grid'],
  merch: ['grid'],
  table: ['split_news'],
  banner: ['top'],
  sidebar: ['right'],
  newsletter: ['default'],
};

interface MyUIbrixStyleEditorProps {
  pageType: string;
  onConfigChange?: (configs: PageElementConfig[]) => void;
}

interface ElementPosition {
  top: number;
  left: number;
  width: number;
  height: number;
}

const MyUIbrixStyleEditor: React.FC<MyUIbrixStyleEditorProps> = ({ pageType, onConfigChange }) => {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';
  const clubTheme = useClubTheme();
  
  const [isEditing, setIsEditing] = useState(false);
  const [configs, setConfigs] = useState<PageElementConfig[]>([]);
  const [localChanges, setLocalChanges] = useState<Record<string, string>>({});
  const [hasChanges, setHasChanges] = useState(false);
  const [selectedElement, setSelectedElement] = useState<string | null>(null);
  const [hoveredElement, setHoveredElement] = useState<string | null>(null);
  const [elementPosition, setElementPosition] = useState<ElementPosition | null>(null);
  const [showElementPicker, setShowElementPicker] = useState(false);
  const [showLayersPanel, setShowLayersPanel] = useState(false);
  const [visibleElements, setVisibleElements] = useState<Set<string>>(new Set());
  const [elementOrder, setElementOrder] = useState<string[]>([]);
  const [draggedElement, setDraggedElement] = useState<string | null>(null);
  const [dragOverElement, setDragOverElement] = useState<string | null>(null);
  const [viewport] = useState<'desktop'>('desktop');
  const [elementStyles, setElementStyles] = useState<Record<string, any>>({});
  const [showStylePanel, setShowStylePanel] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [showHelpHint, setShowHelpHint] = useState(true);
  const overlayRef = useRef<HTMLDivElement>(null);
  const isReorderingRef = useRef(false);
  
  // Draggable panel states
  const [panelPositions, setPanelPositions] = useState({
    stylePicker: { x: 0, y: 0, width: 360, height: 550 },
    layersPanel: { x: 0, y: 0, width: 320, height: 600 },
    visualStylePanel: { x: 0, y: 60, width: 320, height: 700 },
    elementPicker: { x: 0, y: 0, width: 600, height: 600 }
  });
  const [draggingPanel, setDraggingPanel] = useState<string | null>(null);
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 });
  const [resizingPanel, setResizingPanel] = useState<string | null>(null);
  
  const toast = useToast();
  const bgColor = useColorModeValue('white', 'gray.800');
  const borderColor = useColorModeValue('gray.200', 'gray.600');
  const hoverBg = useColorModeValue('blue.50', 'blue.900');
  const primaryColor = clubTheme.primary || '#0b5cff';
  const secondaryColor = clubTheme.secondary || '#ffd200';
  const selectedBg = primaryColor;

  const getAvailableVariants = useCallback((elementName: string) => {
    const variants = ELEMENT_VARIANTS[elementName] || [];
    if (pageType === 'homepage') {
      const allowed = SUPPORTED_HOME_VARIANTS[elementName];
      if (allowed && allowed.length > 0) {
        return variants.filter(variant => allowed.includes(variant.value));
      }
    }
    return variants;
  }, [pageType]);

  const getDefaultVariant = useCallback((elementName: string) => {
    const element = PREDEFINED_ELEMENTS.find(e => e.name === elementName);
    const candidate = element?.defaultVariant;
    const available = getAvailableVariants(elementName);
    if (available.length === 0) {
      return candidate || 'default';
    }
    if (candidate && available.some(v => v.value === candidate)) {
      return candidate;
    }
    return available[0].value;
  }, [getAvailableVariants]);

  const normalizeVariant = useCallback((elementName: string, variant?: string) => {
    const available = getAvailableVariants(elementName);
    if (available.length === 0) {
      return variant || getDefaultVariant(elementName);
    }
    if (variant && available.some(v => v.value === variant)) {
      return variant;
    }
    return getDefaultVariant(elementName);
  }, [getAvailableVariants, getDefaultVariant]);

  // Draggable panel handlers
  const handlePanelMouseDown = useCallback((panelName: string, e: React.MouseEvent) => {
    // Only allow dragging from header area
    const target = e.target as HTMLElement;
    if (!target.closest('.panel-header') && !target.classList.contains('panel-header')) {
      return;
    }
    
    e.preventDefault();
    e.stopPropagation();
    
    const rect = (e.currentTarget as HTMLElement).getBoundingClientRect();
    setDraggingPanel(panelName);
    setDragOffset({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    });
  }, []);

  const handlePanelMouseMove = useCallback((e: MouseEvent) => {
    if (!draggingPanel) return;
    
    const newX = e.clientX - dragOffset.x;
    const newY = e.clientY - dragOffset.y;
    
    setPanelPositions(prev => ({
      ...prev,
      [draggingPanel]: {
        ...prev[draggingPanel as keyof typeof prev],
        x: Math.max(0, Math.min(newX, window.innerWidth - prev[draggingPanel as keyof typeof prev].width)),
        y: Math.max(0, Math.min(newY, window.innerHeight - prev[draggingPanel as keyof typeof prev].height))
      }
    }));
  }, [draggingPanel, dragOffset]);

  const handlePanelMouseUp = useCallback(() => {
    setDraggingPanel(null);
    setResizingPanel(null);
  }, []);

  // Panel dragging effect
  useEffect(() => {
    if (draggingPanel) {
      window.addEventListener('mousemove', handlePanelMouseMove);
      window.addEventListener('mouseup', handlePanelMouseUp);
      return () => {
        window.removeEventListener('mousemove', handlePanelMouseMove);
        window.removeEventListener('mouseup', handlePanelMouseUp);
      };
    }
  }, [draggingPanel, handlePanelMouseMove, handlePanelMouseUp]);

  // Resize handler
  const handleResizeStart = useCallback((panelName: string, e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setResizingPanel(panelName);
    setDragOffset({ x: e.clientX, y: e.clientY });
  }, []);

  const handleResizeMove = useCallback((e: MouseEvent) => {
    if (!resizingPanel) return;
    
    const deltaX = e.clientX - dragOffset.x;
    const deltaY = e.clientY - dragOffset.y;
    
    setPanelPositions(prev => {
      const panel = prev[resizingPanel as keyof typeof prev];
      return {
        ...prev,
        [resizingPanel]: {
          ...panel,
          width: Math.max(280, panel.width + deltaX),
          height: Math.max(300, panel.height + deltaY)
        }
      };
    });
    
    setDragOffset({ x: e.clientX, y: e.clientY });
  }, [resizingPanel, dragOffset]);

  useEffect(() => {
    if (resizingPanel) {
      window.addEventListener('mousemove', handleResizeMove);
      window.addEventListener('mouseup', handlePanelMouseUp);
      return () => {
        window.removeEventListener('mousemove', handleResizeMove);
        window.removeEventListener('mouseup', handlePanelMouseUp);
      };
    }
  }, [resizingPanel, handleResizeMove, handlePanelMouseUp]);

  // Auto-activate editing mode if URL parameter is present
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    if (params.get('myuibrix') === 'edit') {
      setIsEditing(true);
      // Remove parameter from URL without reload
      const newUrl = window.location.pathname;
      window.history.replaceState({}, '', newUrl);
      
      toast({
        title: 'MyUIbrix Editor',
        description: 'Režim úprav byl aktivován. Klikněte na elementy pro jejich úpravu.',
        status: 'info',
        duration: 5000,
        isClosable: true,
      });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Auto-dismiss help hint after 5 seconds
  useEffect(() => {
    if (isEditing && showHelpHint) {
      const timer = setTimeout(() => {
        setShowHelpHint(false);
      }, 5000);
      return () => clearTimeout(timer);
    }
  }, [isEditing, showHelpHint]);

  // Load configurations
  useEffect(() => {
    const loadConfigs = async () => {
      try {
        const data = await getPageElementConfigs(pageType);
        const configsToUse = data.length > 0 ? data : DEFAULT_HOMEPAGE_ELEMENTS;
        const sanitizedConfigs = configsToUse.map(cfg => ({
          ...cfg,
          variant: normalizeVariant(cfg.element_name, cfg.variant)
        }));
        setConfigs(sanitizedConfigs);
        const changes: Record<string, string> = {};
        const visible = new Set<string>();
        const sorted = [...sanitizedConfigs].sort((a, b) => (a.display_order || 0) - (b.display_order || 0));
        const order: string[] = [];
        sorted.forEach(cfg => {
          changes[cfg.element_name] = cfg.variant;
          if (cfg.visible !== false) {
            visible.add(cfg.element_name);
          }
          order.push(cfg.element_name);
        });
        
        setLocalChanges(changes);
        setVisibleElements(visible);
        setElementOrder(order);
        
        // If using defaults and no data exists, mark as has changes so user can save
        if (data.length === 0) {
          setHasChanges(true);
        }
      } catch (error) {
        console.error('Failed to load page element configs:', error);
        
        const fallbackConfigs = DEFAULT_HOMEPAGE_ELEMENTS.map(cfg => ({
          ...cfg,
          variant: normalizeVariant(cfg.element_name, cfg.variant)
        }));
        const changes: Record<string, string> = {};
        const visible = new Set<string>();
        const order: string[] = [];
        fallbackConfigs.forEach(cfg => {
          changes[cfg.element_name] = cfg.variant;
          if (cfg.visible !== false) {
            visible.add(cfg.element_name);
          }
          order.push(cfg.element_name);
        });
        setConfigs(fallbackConfigs);
        setLocalChanges(changes);
        setVisibleElements(visible);
        setElementOrder(order);
        setHasChanges(true);
      }
    };

    loadConfigs();
  }, [pageType, normalizeVariant]);

  // Keyboard shortcuts
  useEffect(() => {
    if (!isEditing) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        if (showElementPicker) setShowElementPicker(false);
        else if (showLayersPanel) setShowLayersPanel(false);
        else if (selectedElement) setSelectedElement(null);
        else setIsEditing(false);
      }
      if ((e.ctrlKey || e.metaKey) && e.key === 's' && hasChanges) {
        e.preventDefault();
        handleSave();
      }
      if (e.key === 'l' && !e.ctrlKey && !e.metaKey && !e.altKey) {
        setShowLayersPanel(!showLayersPanel);
      }
      if (e.key === 'a' && !e.ctrlKey && !e.metaKey && !e.altKey) {
        setShowElementPicker(true);
      }
      if (selectedElement) {
        if (e.key === 'ArrowUp' && !e.shiftKey) {
          e.preventDefault();
          handleMoveUp(selectedElement);
        }
        if (e.key === 'ArrowDown' && !e.shiftKey) {
          e.preventDefault();
          handleMoveDown(selectedElement);
        }
        if (e.key === 'Delete' || e.key === 'Backspace') {
          e.preventDefault();
          handleRemoveElement(selectedElement);
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isEditing, selectedElement, showElementPicker, showLayersPanel, hasChanges]);

  // Add element highlighting and click handlers when editing
  useEffect(() => {
    if (!isEditing) {
      // Clean up overlays when exiting edit mode
      safeDOM.querySelectorAll('.elementor-overlay').forEach(el => {
        // Remove event listeners before removing element
        el.replaceWith(el.cloneNode(true));
        el.remove();
      });
      setSelectedElement(null);
      return;
    }

    const addOverlay = (elementName: string) => {
      const selector = `[data-element="${elementName}"]`;
      const elements = safeDOM.querySelectorAll(selector);
      
      elements.forEach((element) => {
        const existing = element.querySelector('.elementor-overlay');
        if (existing) return;

        const overlay = document.createElement('div');
        overlay.className = 'elementor-overlay';
        overlay.style.cssText = `
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          pointer-events: auto;
          border: 2px dashed transparent;
          transition: all 0.2s;
          z-index: 9998;
          cursor: move;
        `;

        const badge = document.createElement('div');
        badge.className = 'elementor-badge';
        badge.textContent = elementName.toUpperCase();
        badge.style.cssText = `
          position: absolute;
          top: -1px;
          left: -1px;
          background: ${primaryColor};
          color: white;
          padding: 4px 12px;
          font-size: 11px;
          font-weight: 700;
          border-radius: 0 0 6px 0;
          opacity: 0;
          transition: opacity 0.2s;
          pointer-events: none;
          z-index: 9999;
          text-transform: uppercase;
          letter-spacing: 0.5px;
        `;

        // Action buttons (visible on hover)
        const actionsBar = document.createElement('div');
        actionsBar.className = 'elementor-actions';
        actionsBar.style.cssText = `
          position: absolute;
          top: 8px;
          right: 8px;
          display: flex;
          gap: 4px;
          opacity: 0;
          transition: opacity 0.2s;
          z-index: 10000;
          pointer-events: auto;
        `;

        // Edit button
        const editBtn = document.createElement('button');
        editBtn.innerHTML = '⚙️';
        editBtn.title = 'Upravit styl';
        editBtn.style.cssText = `
          background: ${primaryColor};
          color: white;
          border: none;
          width: 32px;
          height: 32px;
          border-radius: 6px;
          cursor: pointer;
          font-size: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 2px 8px rgba(0,0,0,0.2);
          transition: transform 0.2s;
        `;
        editBtn.onmouseover = () => editBtn.style.transform = 'scale(1.1)';
        editBtn.onmouseout = () => editBtn.style.transform = 'scale(1)';

        // Move up button
        const moveUpBtn = document.createElement('button');
        moveUpBtn.innerHTML = '⬆️';
        moveUpBtn.title = 'Přesunout nahoru';
        moveUpBtn.style.cssText = editBtn.style.cssText;
        moveUpBtn.onmouseover = () => moveUpBtn.style.transform = 'scale(1.1)';
        moveUpBtn.onmouseout = () => moveUpBtn.style.transform = 'scale(1)';

        // Move down button
        const moveDownBtn = document.createElement('button');
        moveDownBtn.innerHTML = '⬇️';
        moveDownBtn.title = 'Přesunout dolů';
        moveDownBtn.style.cssText = editBtn.style.cssText;
        moveDownBtn.onmouseover = () => moveDownBtn.style.transform = 'scale(1.1)';
        moveDownBtn.onmouseout = () => moveDownBtn.style.transform = 'scale(1)';

        // Delete button
        const deleteBtn = document.createElement('button');
        deleteBtn.innerHTML = '🗑️';
        deleteBtn.title = 'Odstranit element';
        deleteBtn.style.cssText = `
          background: #e53e3e;
          color: white;
          border: none;
          width: 32px;
          height: 32px;
          border-radius: 6px;
          cursor: pointer;
          font-size: 16px;
          display: flex;
          align-items: center;
          justify-content: center;
          box-shadow: 0 2px 8px rgba(0,0,0,0.2);
          transition: transform 0.2s;
        `;
        deleteBtn.onmouseover = () => deleteBtn.style.transform = 'scale(1.1)';
        deleteBtn.onmouseout = () => deleteBtn.style.transform = 'scale(1)';

        // Use safeDOM to build overlay structure
        safeDOM.appendChild(actionsBar, editBtn);
        safeDOM.appendChild(actionsBar, moveUpBtn);
        safeDOM.appendChild(actionsBar, moveDownBtn);
        safeDOM.appendChild(actionsBar, deleteBtn);

        safeDOM.appendChild(overlay, badge);
        safeDOM.appendChild(overlay, actionsBar);
        
        const parentPos = window.getComputedStyle(element).position;
        if (parentPos === 'static') {
          (element as HTMLElement).style.position = 'relative';
        }

        // Add overlay using safeDOM to avoid React conflicts
        if (!safeDOM.appendChild(element, overlay)) {
          console.warn(`Failed to add overlay to element: ${elementName}`);
          return;
        }

        // Click to auto-select and open style panel
        overlay.addEventListener('click', (e) => {
          // Don't trigger if clicking on action buttons
          if ((e.target as HTMLElement).closest('.elementor-actions')) {
            return;
          }
          e.stopPropagation();
          const rect = element.getBoundingClientRect();
          setElementPosition({
            top: rect.top,
            left: rect.left,
            width: rect.width,
            height: rect.height,
          });
          setSelectedElement(elementName);
          setShowStylePanel(true);
        });

        // Hover effects
        overlay.addEventListener('mouseenter', () => {
          setHoveredElement(elementName);
          overlay.style.border = `2px dashed ${primaryColor}`;
          overlay.style.background = `${primaryColor}15`;
          badge.style.opacity = '1';
          actionsBar.style.opacity = '1';
        });

        overlay.addEventListener('mouseleave', () => {
          setHoveredElement(null);
          if (selectedElement !== elementName) {
            overlay.style.border = '2px dashed transparent';
            overlay.style.background = 'transparent';
            badge.style.opacity = '0';
            actionsBar.style.opacity = '0';
          }
        });

        // Button click handlers
        editBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          const rect = element.getBoundingClientRect();
          setElementPosition({
            top: rect.top,
            left: rect.left,
            width: rect.width,
            height: rect.height,
          });
          setSelectedElement(elementName);
          setShowStylePanel(true);
        });

        moveUpBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          handleMoveUp(elementName);
        });

        moveDownBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          handleMoveDown(elementName);
        });

        deleteBtn.addEventListener('click', (e) => {
          e.stopPropagation();
          if (confirm(`Opravdu chcete odstranit element "${elementName}"?`)) {
            handleRemoveElement(elementName);
          }
        });

        // Make overlay draggable
        overlay.draggable = true;
        overlay.addEventListener('dragstart', (e) => {
          e.stopPropagation();
          setDraggedElement(elementName);
          overlay.style.opacity = '0.5';
        });

        overlay.addEventListener('dragend', (e) => {
          e.stopPropagation();
          overlay.style.opacity = '1';
          setDraggedElement(null);
        });

        overlay.addEventListener('dragover', (e) => {
          e.preventDefault();
          e.stopPropagation();
          if (draggedElement && draggedElement !== elementName) {
            overlay.style.border = `3px solid ${secondaryColor}`;
            setDragOverElement(elementName);
          }
        });

        overlay.addEventListener('dragleave', (e) => {
          e.stopPropagation();
          if (selectedElement !== elementName) {
            overlay.style.border = `2px dashed ${primaryColor}`;
          }
          setDragOverElement(null);
        });

        overlay.addEventListener('drop', (e) => {
          e.preventDefault();
          e.stopPropagation();
          if (draggedElement && draggedElement !== elementName) {
            // Reorder elements
            const newOrder = [...elementOrder];
            const draggedIndex = newOrder.indexOf(draggedElement);
            const targetIndex = newOrder.indexOf(elementName);
            
            if (draggedIndex !== -1 && targetIndex !== -1) {
              newOrder.splice(draggedIndex, 1);
              newOrder.splice(targetIndex, 0, draggedElement);
              setElementOrder(newOrder);
              setHasChanges(true);
              applyVisualReorder(newOrder);
            }
          }
          overlay.style.border = `2px dashed ${primaryColor}`;
          setDragOverElement(null);
        });
      });
    };

    // Only add overlays for elements that are actually implemented on this page
    const implementedElements = pageType === 'homepage' ? HOMEPAGE_IMPLEMENTED_ELEMENTS : Object.keys(ELEMENT_VARIANTS);
    implementedElements.forEach((elementName) => {
      if (ELEMENT_VARIANTS[elementName]) {
        addOverlay(elementName);
      }
    });

    // Close panel on escape
    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setSelectedElement(null);
      }
    };
    document.addEventListener('keydown', handleEscape);

    return () => {
      // Cleanup: Remove all overlays and event listeners - with safe DOM
      try {
        const overlays = safeDOM.querySelectorAll('.elementor-overlay');
        overlays.forEach(el => {
          try {
            // Remove event listeners by cloning
            const clone = el.cloneNode(false) as Element;
            const parent = el.parentElement;
            if (parent && safeDOM.replaceChild(parent, clone, el)) {
              safeDOM.removeChild(parent, clone);
            }
          } catch (e) {
            console.warn('Failed to cleanup overlay:', e);
          }
        });
      } catch (e) {
        console.error('Error during cleanup:', e);
      }
      
      try {
        document.removeEventListener('keydown', handleEscape);
      } catch (e) {
        console.warn('Failed to remove event listener:', e);
      }
      
      // Clear debounce timer
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }
    };
  }, [isEditing, selectedElement, pageType]);

  // Update selected element overlay styling
  useEffect(() => {
    safeDOM.querySelectorAll('.elementor-overlay').forEach((overlay) => {
      const parent = overlay.parentElement;
      const elementName = parent?.getAttribute('data-element');
      
      if (elementName === selectedElement) {
        (overlay as HTMLElement).style.border = `3px solid ${primaryColor}`;
        (overlay as HTMLElement).style.background = `${primaryColor}1A`;
        const badge = overlay.querySelector('.elementor-badge') as HTMLElement;
        if (badge) {
          badge.style.opacity = '1';
          badge.style.background = primaryColor;
        }
      } else if (elementName === hoveredElement) {
        (overlay as HTMLElement).style.border = `2px dashed ${primaryColor}`;
        (overlay as HTMLElement).style.background = `${primaryColor}15`;
        const badge = overlay.querySelector('.elementor-badge') as HTMLElement;
        if (badge) badge.style.opacity = '1';
      } else {
        (overlay as HTMLElement).style.border = '2px dashed transparent';
        (overlay as HTMLElement).style.background = 'transparent';
        const badge = overlay.querySelector('.elementor-badge') as HTMLElement;
        if (badge) badge.style.opacity = '0';
      }
    });
  }, [selectedElement, hoveredElement]);

  const handleVariantChange = useCallback((elementName: string, variant: string) => {
    // Prevent crashes by checking if variant exists
    const variants = getAvailableVariants(elementName);
    if (!variants || variants.length === 0) {
      console.warn(`Invalid variant "${variant}" for element "${elementName}"`);
      return;
    }
    const safeVariant = normalizeVariant(elementName, variant);

    // Helper function to apply the variant change
    const applyChange = () => {
      try {
        const newChanges = { ...localChanges, [elementName]: safeVariant };
        setLocalChanges(newChanges);
        setHasChanges(true);
        
        // Update configs array to reflect the change
        setConfigs(prevConfigs => {
          const configIndex = prevConfigs.findIndex(c => c.element_name === elementName);
          if (configIndex !== -1) {
            const updated = [...prevConfigs];
            updated[configIndex] = { ...updated[configIndex], variant: safeVariant };
            return updated;
          }
          return prevConfigs;
        });
        
        // Live preview ONLY during editing (not visible in production)
        // Use requestAnimationFrame to avoid DOM conflicts
        if (isEditing) {
          requestAnimationFrame(() => {
            window.dispatchEvent(new CustomEvent('myuibrix-change', {
              detail: { elementName, variant: safeVariant, visible: visibleElements.has(elementName), previewMode: true }
            }));
          });
        }
      } catch (error) {
        console.error('Error applying variant change:', error);
        toast({
          title: 'Chyba při aplikaci stylu',
          description: 'Styl se nepodařilo aplikovat. Zkuste to prosím znovu.',
          status: 'error',
          duration: 3000,
          isClosable: true,
        });
      }
    };
    
    // Wait if we're currently reordering to avoid DOM conflicts
    if (isReorderingRef.current) {
      // Wait for reordering to complete, then apply change
      const checkAndApply = () => {
        if (!isReorderingRef.current) {
          applyChange();
        } else {
          setTimeout(checkAndApply, 50);
        }
      };
      setTimeout(checkAndApply, 50);
      return;
    }
    
    applyChange();
  }, [localChanges, visibleElements, isEditing, toast, getAvailableVariants, normalizeVariant]);

  // Debounce style changes to prevent lag
  const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
  
  const handleStyleChange = useCallback((elementName: string, styles: Record<string, any>) => {
    setElementStyles(prev => ({
      ...prev,
      [elementName]: styles
    }));
    setHasChanges(true);
    
    // Debounce the dispatch to reduce event flooding
    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }
    
    debounceTimerRef.current = setTimeout(() => {
      // Live preview ONLY during editing
      if (isEditing) {
        window.dispatchEvent(new CustomEvent('myuibrix-style-change', {
          detail: { elementName, styles, previewMode: true }
        }));
      }
    }, 100); // 100ms debounce
  }, [isEditing]);

  const handleAddElement = useCallback((elementName: string) => {
    const element = PREDEFINED_ELEMENTS.find(e => e.name === elementName);
    if (!element) return;
    
    const newVisible = new Set(visibleElements);
    newVisible.add(elementName);
    setVisibleElements(newVisible);
    
    const existingVariant = localChanges[elementName];
    const defaultVariant = normalizeVariant(elementName, element.defaultVariant);
    const variantToUse = normalizeVariant(elementName, existingVariant || defaultVariant);
    if (!localChanges[elementName]) {
      setLocalChanges(prev => ({ ...prev, [elementName]: variantToUse }));
    }
    setConfigs(prev => {
      const index = prev.findIndex(cfg => cfg.element_name === elementName);
      if (index !== -1) {
        const updated = [...prev];
        updated[index] = { ...updated[index], variant: variantToUse, visible: true };
        return updated;
      }
      return [...prev, {
        page_type: pageType,
        element_name: elementName,
        variant: variantToUse,
        visible: true,
        display_order: prev.length,
      }];
    });

    setHasChanges(true);
    setShowElementPicker(false);
    setSearchQuery('');
    setSelectedCategory('all');
    
    // Live preview ONLY during editing
    if (isEditing) {
      window.dispatchEvent(new CustomEvent('myuibrix-change', {
        detail: { elementName, variant: variantToUse, visible: true, previewMode: true }
      }));
    }
  }, [visibleElements, localChanges, isEditing, normalizeVariant, pageType]);

  const handleRemoveElement = useCallback((elementName: string) => {
    // Update state - React will handle DOM removal
    const newVisible = new Set(visibleElements);
    newVisible.delete(elementName);
    setVisibleElements(newVisible);
    setHasChanges(true);
    setSelectedElement(null);
    
    // Hide the element via React state event
    if (isEditing) {
      window.dispatchEvent(new CustomEvent('myuibrix-change', {
        detail: { elementName, variant: localChanges[elementName], visible: false, previewMode: true }
      }));
    }
    
    // Force React to re-render by triggering a state update
    setTimeout(() => {
      const element = safeDOM.querySelector(`[data-element="${elementName}"]`);
      if (element) {
        (element as HTMLElement).style.display = 'none';
      }
    }, 0);
  }, [visibleElements, localChanges, isEditing]);

  // Apply visual reordering using CSS order property instead of DOM manipulation
  const applyVisualReorder = useCallback((order: string[]) => {
    // Prevent concurrent reordering operations
    if (isReorderingRef.current) {
      return;
    }
    
    isReorderingRef.current = true;
    
    // Use CSS order property to avoid DOM manipulation conflicts with React
    requestAnimationFrame(() => {
      try {
        order.forEach((elementName, index) => {
          const element = safeDOM.querySelector(`[data-element="${elementName}"]`) as HTMLElement;
          if (element) {
            // Use CSS order instead of moving DOM nodes
            element.style.order = String(index);
          }
        });
        
        // Ensure parent container uses flexbox
        const viewport = safeDOM.querySelector('.myuibrix-viewport-wrapper');
        const container = viewport || safeDOM.querySelector('.container') || safeDOM.querySelector('main');
        if (container) {
          (container as HTMLElement).style.display = 'flex';
          (container as HTMLElement).style.flexDirection = 'column';
        }
        
        console.log('Visual reorder applied via CSS order');
        
        // Dispatch reorder event for HomePage to update
        window.dispatchEvent(new CustomEvent('myuibrix-reorder', {
          detail: { order, previewMode: true }
        }));
        
        setTimeout(() => {
          isReorderingRef.current = false;
        }, 50);
      } catch (error) {
        console.error('Error during visual reordering:', error);
        isReorderingRef.current = false;
      }
    });
  }, []);

  const handleMoveUp = useCallback((elementName: string) => {
    const currentIndex = elementOrder.indexOf(elementName);
    if (currentIndex <= 0) return;
    
    const newOrder = [...elementOrder];
    [newOrder[currentIndex - 1], newOrder[currentIndex]] = [newOrder[currentIndex], newOrder[currentIndex - 1]];
    setElementOrder(newOrder);
    setHasChanges(true);
    
    // Trigger reorder event and apply visual reordering
    if (isEditing) {
      applyVisualReorder(newOrder);
      window.dispatchEvent(new CustomEvent('myuibrix-reorder', {
        detail: { order: newOrder, previewMode: true }
      }));
    }
  }, [elementOrder, isEditing, applyVisualReorder]);

  const handleMoveDown = useCallback((elementName: string) => {
    const currentIndex = elementOrder.indexOf(elementName);
    if (currentIndex < 0 || currentIndex >= elementOrder.length - 1) return;
    
    const newOrder = [...elementOrder];
    [newOrder[currentIndex], newOrder[currentIndex + 1]] = [newOrder[currentIndex + 1], newOrder[currentIndex]];
    setElementOrder(newOrder);
    setHasChanges(true);
    
    // Trigger reorder event and apply visual reordering
    if (isEditing) {
      applyVisualReorder(newOrder);
      window.dispatchEvent(new CustomEvent('myuibrix-reorder', {
        detail: { order: newOrder, previewMode: true }
      }));
    }
  }, [elementOrder, isEditing, applyVisualReorder]);


  // Drag and drop handlers with improved state management
  const handleDragStart = useCallback((elementName: string, e: React.DragEvent) => {
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', elementName);
    setDraggedElement(elementName);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent, elementName: string) => {
    e.preventDefault();
    e.dataTransfer.dropEffect = 'move';
    if (draggedElement !== elementName) {
      setDragOverElement(elementName);
    }
  }, [draggedElement]);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    // Only clear if we're leaving to a non-child element
    const relatedTarget = e.relatedTarget as HTMLElement;
    if (!relatedTarget || !(e.currentTarget as HTMLElement).contains(relatedTarget)) {
      setDragOverElement(null);
    }
  }, []);
  
  const handleDragEnd = useCallback(() => {
    setDraggedElement(null);
    setDragOverElement(null);
  }, []);

  const handleDrop = useCallback((e: React.DragEvent, targetElementName: string) => {
    e.preventDefault();
    
    if (!draggedElement || draggedElement === targetElementName) {
      setDraggedElement(null);
      setDragOverElement(null);
      return;
    }
    
    const newOrder = [...elementOrder];
    const draggedIndex = newOrder.indexOf(draggedElement);
    const targetIndex = newOrder.indexOf(targetElementName);
    
    if (draggedIndex === -1 || targetIndex === -1) {
      setDraggedElement(null);
      setDragOverElement(null);
      return;
    }
    
    // Remove dragged element and insert at target position
    newOrder.splice(draggedIndex, 1);
    newOrder.splice(targetIndex, 0, draggedElement);
    
    setElementOrder(newOrder);
    setHasChanges(true);
    setDraggedElement(null);
    setDragOverElement(null);
    
    // Apply visual reordering
    if (isEditing) {
      applyVisualReorder(newOrder);
      window.dispatchEvent(new CustomEvent('myuibrix-reorder', {
        detail: { order: newOrder, previewMode: true }
      }));
    }
  }, [draggedElement, elementOrder, isEditing, applyVisualReorder]);

  const handleSave = async () => {
    try {
      const configsToSave: PageElementConfig[] = elementOrder.map((elementName, index) => ({
        page_type: pageType,
        element_name: elementName,
        variant: localChanges[elementName] || 'default',
        visible: visibleElements.has(elementName),
        display_order: index,
      }));

      await batchUpdatePageElementConfigs(configsToSave);
      
      toast({
        title: 'Změny úspěšně uloženy!',
        description: 'Změny jsou nyní viditelné na produkci.',
        status: 'success',
        duration: 3000,
        isClosable: true,
      });

      setHasChanges(false);
      
      // Reload the page to apply changes in production view
      // This ensures saved changes are visible to all visitors
      setTimeout(() => {
        window.location.reload();
      }, 1500);
    } catch (error) {
      toast({
        title: 'Nepodařilo se uložit změny',
        description: 'Zkuste to prosím znovu nebo kontaktujte podporu.',
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    }
  };

  // Memoize current variants to avoid recalculation
  const currentVariants = useMemo(() => 
    selectedElement ? getAvailableVariants(selectedElement) : [],
    [selectedElement, getAvailableVariants]
  );

  const currentVariant = useMemo(() => 
    selectedElement ? normalizeVariant(selectedElement, localChanges[selectedElement]) : null,
    [selectedElement, localChanges, normalizeVariant]
  );

  // Calculate viewport width - USE REAL DEVICE WIDTHS WITHOUT SCALING
  const getViewportConfig = useCallback(() => ({
    width: '100%',
    label: 'Desktop (100%)'
  }), []);

  const viewportConfig = useMemo(() => getViewportConfig(), [getViewportConfig]);

  // Prevent all clicks on page content during edit mode
  useEffect(() => {
    if (!isEditing) return;
    
    const preventPageInteractions = (e: MouseEvent) => {
      const target = e.target as HTMLElement;
      
      // Allow clicks on MyUIbrix UI elements (panels, buttons, overlays)
      if (
        target.closest('.myuibrix-panel') ||
        target.closest('.myuibrix-toolbar') ||
        target.closest('.elementor-overlay') ||
        target.closest('[role="dialog"]') ||
        target.closest('.chakra-portal') ||
        target.closest('.chakra-modal') ||
        target.classList.contains('elementor-overlay')
      ) {
        return; // Allow MyUIbrix interactions
      }
      
      // Prevent all other interactions on the page content
      const wrapper = safeDOM.querySelector('.myuibrix-viewport-wrapper');
      if (wrapper && wrapper.contains(target)) {
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();
      }
    };
    
    // Capture phase to ensure we intercept before any handlers
    document.addEventListener('click', preventPageInteractions, true);
    document.addEventListener('mousedown', preventPageInteractions, true);
    
    return () => {
      document.removeEventListener('click', preventPageInteractions, true);
      document.removeEventListener('mousedown', preventPageInteractions, true);
    };
  }, [isEditing]);

  // Add padding to body when editor is active and apply viewport width
  useEffect(() => {
    if (isEditing) {
      document.body.style.paddingTop = '60px';
      document.body.style.backgroundColor = '#e2e8f0';
      document.body.style.userSelect = 'none'; // Prevent text selection during editing
      
      // Apply viewport wrapper - wrap ALL content including navbar
      if (!safeDOM.querySelector('.myuibrix-viewport-wrapper')) {
        // Find all chakra containers (navbar + content) using safeDOM
        const allContainers = safeDOM.querySelectorAll('.chakra-container');
        const pageContainer = safeDOM.querySelector('.container');
        
        if (allContainers.length > 0 && pageContainer) {
          // Create viewport wrapper
          const wrapper = document.createElement('div');
          wrapper.className = 'myuibrix-viewport-wrapper';
          wrapper.style.cssText = `
            margin: 0 auto;
            transition: all 0.3s ease;
            background: white;
            min-height: 100vh;
            position: relative;
            overflow: visible;
            cursor: default;
            width: 100%;
            max-width: 100%;
          `;
          
          // Store reference to parent and next sibling for restoration
          const firstContainer = allContainers[0];
          const parent = firstContainer.parentElement;
          const nextSibling = firstContainer.nextSibling;
          
          if (parent) {
            parent.setAttribute('data-myuibrix-restore', 'true');
            
            // Move all chakra containers into wrapper using safeDOM
            allContainers.forEach(container => {
              // Store original styles
              container.setAttribute('data-myuibrix-original-maxw', 
                (container as HTMLElement).style.maxWidth || '');
              container.setAttribute('data-myuibrix-original-width',
                (container as HTMLElement).style.width || '');
              
              // Remove max-width constraints for viewport simulation
              (container as HTMLElement).style.maxWidth = 'none';
              (container as HTMLElement).style.width = '100%';
              
              // Use safe appendChild to avoid React conflicts
              safeDOM.appendChild(wrapper, container);
            });
            
            // Insert wrapper back into DOM using safeDOM
            if (nextSibling) {
              safeDOM.insertBefore(parent, wrapper, nextSibling);
            } else {
              safeDOM.appendChild(parent, wrapper);
            }
          }
        }
      }
    } else {
      document.body.style.paddingTop = '0';
      document.body.style.backgroundColor = '';
      document.body.style.userSelect = '';
      
      // Remove viewport wrapper and restore original structure
      const wrapper = safeDOM.querySelector('.myuibrix-viewport-wrapper');
      if (wrapper) {
        const parent = safeDOM.querySelector('[data-myuibrix-restore]');
        if (parent) {
          // Move all children back to parent using safeDOM
          const children = Array.from(wrapper.children);
          children.forEach(child => {
            // Restore original styles
            const originalMaxW = child.getAttribute('data-myuibrix-original-maxw');
            const originalWidth = child.getAttribute('data-myuibrix-original-width');
            
            if (originalMaxW !== null) {
              (child as HTMLElement).style.maxWidth = originalMaxW;
              child.removeAttribute('data-myuibrix-original-maxw');
            }
            if (originalWidth !== null) {
              (child as HTMLElement).style.width = originalWidth;
              child.removeAttribute('data-myuibrix-original-width');
            }
            
            // Use safe appendChild to avoid React conflicts
            safeDOM.appendChild(parent, child as Element);
          });
          
          parent.removeAttribute('data-myuibrix-restore');
          // Use safeDOM to remove wrapper
          if (wrapper.parentElement) {
            safeDOM.removeChild(wrapper.parentElement, wrapper);
          }
        }
      }
    }
    return () => {
      document.body.style.paddingTop = '0';
      document.body.style.backgroundColor = '';
      document.body.style.userSelect = '';
      const wrapper = safeDOM.querySelector('.myuibrix-viewport-wrapper');
      if (wrapper) {
        const parent = safeDOM.querySelector('[data-myuibrix-restore]');
        if (parent) {
          const children = Array.from(wrapper.children);
          children.forEach(child => {
            const originalMaxW = child.getAttribute('data-myuibrix-original-maxw');
            const originalWidth = child.getAttribute('data-myuibrix-original-width');
            
            if (originalMaxW !== null) {
              (child as HTMLElement).style.maxWidth = originalMaxW;
              child.removeAttribute('data-myuibrix-original-maxw');
            }
            if (originalWidth !== null) {
              (child as HTMLElement).style.width = originalWidth;
              child.removeAttribute('data-myuibrix-original-width');
            }
            
            // Use safe appendChild to avoid React conflicts
            safeDOM.appendChild(parent, child as Element);
          });
          
          parent.removeAttribute('data-myuibrix-restore');
          // Use safeDOM to remove wrapper
          if (wrapper.parentElement) {
            safeDOM.removeChild(wrapper.parentElement, wrapper);
          }
        }
      }
    };
  }, [isEditing]);

  // Apply viewport width changes with smooth transitions - REAL WIDTH CONSTRAINTS
  useEffect(() => {
    if (!isEditing) return;
    
    const wrapper = safeDOM.querySelector('.myuibrix-viewport-wrapper') as HTMLElement;
    if (!wrapper) return;
    
    // Apply actual width constraints without scaling for real responsive behavior
    wrapper.style.width = '100%';
    wrapper.style.maxWidth = '100%';
    wrapper.style.transition = 'all 0.3s ease';
    wrapper.style.margin = '0 auto';
    wrapper.style.transform = 'none';
    wrapper.style.transformOrigin = '';
    
    // Add visual indicator for non-desktop viewports only
    if (viewport !== 'desktop') {
      wrapper.style.border = `3px solid ${primaryColor}`;
      wrapper.style.boxShadow = `0 0 0 9999px rgba(0,0,0,0.25), 0 8px 32px rgba(0,0,0,0.2)`;
      wrapper.style.marginTop = '20px';
      wrapper.style.marginBottom = '20px';
      wrapper.style.minHeight = 'calc(100vh - 100px)';
    } else {
      wrapper.style.border = 'none';
      wrapper.style.boxShadow = 'none';
      wrapper.style.marginTop = '0';
      wrapper.style.marginBottom = '0';
      wrapper.style.minHeight = '100vh';
    }
    
    // Show toast notification when changing viewport
    toast({
      title: 'Viewport nastaven na Desktop',
      description: 'Zobrazení na plnou šířku (100%)',
      status: 'info',
      duration: 2000,
      isClosable: true,
      position: 'bottom-right',
    });
  }, [isEditing, viewport, primaryColor, toast, viewportConfig]);

  // Early return if not admin (after all hooks)
  if (!isAdmin) return null;

  return (
    <>
      {/* Edit Mode - Active */}
      {isEditing && (
        <>
          {/* Top Control Bar - Viewport Switcher & Actions */}
          <Box
            className="myuibrix-toolbar"
            position="fixed"
            top={0}
            left={0}
            right={0}
            bgGradient={`linear(to-r, ${primaryColor}, ${primaryColor}dd)`}
            color="white"
            p={3}
            zIndex={9999}
            boxShadow="0 4px 20px rgba(0,0,0,0.15), 0 2px 8px rgba(0,0,0,0.1)"
            backdropFilter="blur(10px)"
            borderBottom="1px solid rgba(255,255,255,0.1)"
            fontFamily="var(--chakra-fonts-body)"
          >
            <Flex align="center" justify="space-between" maxW="100%">
              {/* Left: Elementor Logo */}
              <HStack spacing={3}>
                <Box 
                  bgGradient={`linear(135deg, ${secondaryColor}, ${secondaryColor}dd)`}
                  px={4} 
                  py={2} 
                  borderRadius="xl" 
                  color={clubTheme.textOnSecondary || 'black'}
                  boxShadow="0 4px 12px rgba(0,0,0,0.2)"
                  border="2px solid rgba(255,255,255,0.2)"
                  transition="all 0.3s"
                  _hover={{ transform: 'translateY(-1px)', boxShadow: '0 6px 16px rgba(0,0,0,0.25)' }}
                >
                  <HStack spacing={2} align="center">
                    <Icon as={FaFutbol} color="white" boxSize={5} />
                    <Text fontWeight="800" fontSize="md" color="white" letterSpacing="tight">
                      MyUIbrix
                    </Text>
                  </HStack>
                </Box>
                <Badge
                  bg="orange.500"
                  color="white"
                  fontSize="xs"
                  px={3}
                  py={1.5}
                  borderRadius="full"
                  fontWeight="700"
                  display="flex"
                  alignItems="center"
                  gap={1}
                  boxShadow="0 2px 8px rgba(237, 137, 54, 0.4)"
                  border="1px solid rgba(255,255,255,0.3)"
                  sx={{
                    '@keyframes pulseBadge': {
                      '0%, 100%': { transform: 'scale(1)', opacity: 1 },
                      '50%': { transform: 'scale(1.05)', opacity: 0.9 }
                    },
                    animation: 'pulseBadge 2s infinite'
                  }}
                >
                  <Icon as={FiLock} boxSize={3} />
                  REŽIM NÁHLEDU
                </Badge>
                <Text fontSize="sm" fontWeight="600" color="whiteAlpha.800">Změny vidíte pouze vy</Text>
              </HStack>

              <Text fontSize="sm" fontWeight="700" color="whiteAlpha.900">
                Náhled: Desktop (100%)
              </Text>

              {/* Right: Actions */}
              <HStack spacing={2}>
                {hasChanges && (
                  <Badge 
                    bg="yellow.400" 
                    color="gray.900"
                    fontSize="sm"
                    px={3}
                    py={1.5}
                    borderRadius="full"
                    fontWeight="700"
                    boxShadow="0 2px 8px rgba(250, 204, 21, 0.4)"
                    border="1px solid rgba(255,255,255,0.5)"
                    sx={{
                      '@keyframes bounce': {
                        '0%, 100%': { transform: 'translateY(0)' },
                        '50%': { transform: 'translateY(-2px)' }
                      },
                      animation: 'bounce 1s infinite'
                    }}
                  >
                    {Object.keys(localChanges).length} neuložených změn
                  </Badge>
                )}
                <Button
                  leftIcon={<FiSave />}
                  bgGradient={`linear(135deg, ${secondaryColor}, ${secondaryColor}dd)`}
                  color="white"
                  size="sm"
                  onClick={handleSave}
                  isDisabled={!hasChanges}
                  fontWeight="700"
                  px={6}
                  borderRadius="xl"
                  boxShadow="0 4px 12px rgba(0,0,0,0.2)"
                  border="2px solid rgba(255,255,255,0.2)"
                  _hover={{ 
                    transform: 'translateY(-2px)', 
                    boxShadow: '0 6px 16px rgba(0,0,0,0.25)'
                  }}
                  _active={{ transform: 'translateY(0)' }}
                  transition="all 0.2s"
                >
                  Publikovat
                </Button>
                <IconButton
                  aria-label="Ukončit"
                  icon={<FiX />}
                  size="sm"
                  variant="ghost"
                  colorScheme="whiteAlpha"
                  onClick={() => setIsEditing(false)}
                />
              </HStack>
            </Flex>
          </Box>
          {/* Left Visual Style Panel */}
          {showStylePanel && selectedElement && (
            <Box
              className="myuibrix-panel"
              position="fixed"
              left={`${panelPositions.visualStylePanel.x}px`}
              top={`${panelPositions.visualStylePanel.y}px`}
              width={`${panelPositions.visualStylePanel.width}px`}
              height={`${panelPositions.visualStylePanel.height}px`}
              zIndex={9998}
              onMouseDown={(e) => handlePanelMouseDown('visualStylePanel', e)}
              cursor={draggingPanel === 'visualStylePanel' ? 'grabbing' : 'default'}
              overflow="hidden"
              display="flex"
              flexDirection="column"
              fontFamily="var(--chakra-fonts-body)"
              bg="rgba(255, 255, 255, 0.95)"
              backdropFilter="blur(12px) saturate(180%)"
              borderRadius="2xl"
              boxShadow="0 20px 60px rgba(0,0,0,0.3), 0 8px 24px rgba(0,0,0,0.2)"
              border="1px solid rgba(255,255,255,0.3)"
              sx={{
                '@keyframes slideInLeft': {
                  from: { opacity: 0, transform: 'translateX(-40px)' },
                  to: { opacity: 1, transform: 'translateX(0)' }
                },
                animation: 'slideInLeft 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
              }}
            >
              <Box 
                className="panel-header"
                bgGradient={`linear(135deg, ${primaryColor}, ${primaryColor}dd)`}
                color="white"
                p={3}
                cursor="move"
                display="flex"
                alignItems="center"
                justifyContent="space-between"
                flexShrink={0}
                borderTopRadius="2xl"
                borderBottom="1px solid rgba(255,255,255,0.2)"
                boxShadow="0 2px 8px rgba(0,0,0,0.1)"
              >
                <HStack>
                  <Icon as={FaPaintBrush} />
                  <Text fontWeight="bold" fontSize="sm">Vizuální Styly</Text>
                </HStack>
                <IconButton
                  aria-label="Zavřít"
                  icon={<FiX />}
                  size="xs"
                  variant="ghost"
                  colorScheme="whiteAlpha"
                  onClick={() => setShowStylePanel(false)}
                />
              </Box>
              <Box flex="1" overflow="auto">
                <VisualStylePanel
                  elementName={selectedElement}
                  onStyleChange={(styles) => handleStyleChange(selectedElement, styles)}
                  currentStyles={elementStyles[selectedElement]}
                />
              </Box>
              {/* Resize handle */}
              <Box
                position="absolute"
                bottom={0}
                right={0}
                width="24px"
                height="24px"
                cursor="nwse-resize"
                bgGradient="linear(135deg, transparent, rgba(0,0,0,0.15))"
                opacity={0.4}
                _hover={{ opacity: 1 }}
                onMouseDown={(e) => handleResizeStart('visualStylePanel', e)}
                sx={{
                  clipPath: 'polygon(100% 0, 100% 100%, 0 100%)'
                }}
                transition="opacity 0.2s"
              />
            </Box>
          )}
        </>
      )}

      {/* Floating Control Panel - Minimalist */}
      <Box
        position="fixed"
        left={4}
        bottom={4}
        zIndex={10000}
        bg={isEditing ? 'rgba(255,255,255,0.95)' : primaryColor}
        borderRadius="full"
        boxShadow="0 12px 40px rgba(0,0,0,0.25), 0 4px 16px rgba(0,0,0,0.15)"
        border="2px solid"
        borderColor={isEditing ? selectedBg : primaryColor}
        backdropFilter="blur(12px)"
        transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
        _hover={{ transform: 'scale(1.05)', boxShadow: '0 16px 48px rgba(0,0,0,0.3), 0 6px 20px rgba(0,0,0,0.2)' }}
      >
        <VStack spacing={0}>
          {/* Edit Toggle */}
          <Tooltip label={isEditing ? "Ukončit režim úprav (ESC)" : "Aktivovat MyUIbrix Editor"} placement="right">
            <IconButton
              aria-label="Toggle edit mode"
              icon={isEditing ? <FiX /> : <FiEdit />}
              colorScheme={isEditing ? "red" : "whiteAlpha"}
              size="lg"
              onClick={() => {
                setIsEditing(!isEditing);
                if (isEditing) {
                  setSelectedElement(null);
                  setShowLayersPanel(false);
                  setShowElementPicker(false);
                }
              }}
              borderRadius="full"
              variant="solid"
              color={isEditing ? undefined : "white"}
              _hover={{
                transform: 'scale(1.1)',
                boxShadow: 'lg',
              }}
              transition="all 0.2s"
            />
          </Tooltip>

          {isEditing && (
            <>
              <Divider my={1} />
              
              {/* Add Element Button */}
              <Tooltip label="Přidat element (A)" placement="right">
                <IconButton
                  aria-label="Přidat element"
                  icon={<FaPlus />}
                  bgGradient={`linear(135deg, ${primaryColor}, ${primaryColor}dd)`}
                  color="white"
                  _hover={{ transform: 'scale(1.15) rotate(90deg)', boxShadow: 'lg' }}
                  size="md"
                  onClick={() => setShowElementPicker(true)}
                  borderRadius="full"
                  boxShadow="0 4px 12px rgba(0,0,0,0.2)"
                  transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
                />
              </Tooltip>
              
              <Divider my={1} />
              
              {/* Layers Panel Toggle */}
              <Tooltip label="Vrstvy elementů (L)" placement="right">
                <IconButton
                  aria-label="Zobrazit vrstvy"
                  icon={<FiMove />}
                  bg={showLayersPanel ? secondaryColor : undefined}
                  color={showLayersPanel ? (clubTheme.textOnSecondary || 'black') : undefined}
                  _hover={{ bg: secondaryColor, color: clubTheme.textOnSecondary || 'black' }}
                  size="md"
                  onClick={() => setShowLayersPanel(!showLayersPanel)}
                  borderRadius="full"
                  variant={showLayersPanel ? "solid" : "ghost"}
                  sx={{
                    '&:hover': {
                      transform: 'scale(1.1)',
                      boxShadow: 'md',
                    }
                  }}
                  transition="all 0.2s"
                />
              </Tooltip>
              
              {hasChanges && (
                <>
                  <Divider my={1} />
                  <Tooltip label="Uložit změny (Ctrl+S)" placement="right">
                    <IconButton
                      aria-label="Uložit"
                      icon={<FiSave />}
                      bgGradient="linear(135deg, green.400, green.600)"
                      color="white"
                      _hover={{ transform: 'scale(1.2)', bgGradient: 'linear(135deg, green.500, green.700)' }}
                      size="md"
                      onClick={handleSave}
                      borderRadius="full"
                      boxShadow="0 0 0 0 rgba(72, 187, 120, 0.4)"
                      transition="all 0.2s"
                      sx={{
                        '@keyframes pulseGreen': {
                          '0%, 100%': { boxShadow: '0 0 0 0 rgba(72, 187, 120, 0.6), 0 4px 12px rgba(72, 187, 120, 0.4)' },
                          '50%': { boxShadow: '0 0 0 10px rgba(72, 187, 120, 0), 0 6px 16px rgba(72, 187, 120, 0.2)' },
                        },
                        animation: 'pulseGreen 2s infinite'
                      }}
                    />
                  </Tooltip>
                </>
              )}
            </>
          )}
        </VStack>
      </Box>

      {/* Contextual Style Selector - Appears near clicked element */}
      {isEditing && selectedElement && elementPosition && (
        <Portal>
          <Box
            className="myuibrix-panel"
            ref={overlayRef}
            position="fixed"
            top={panelPositions.stylePicker.y === 0 ? `${Math.min(elementPosition.top + elementPosition.height + 10, window.innerHeight - 450)}px` : `${panelPositions.stylePicker.y}px`}
            left={panelPositions.stylePicker.x === 0 ? `${Math.min(elementPosition.left, window.innerWidth - 380)}px` : `${panelPositions.stylePicker.x}px`}
            width={`${panelPositions.stylePicker.width}px`}
            height={`${panelPositions.stylePicker.height}px`}
            bg="rgba(255, 255, 255, 0.98)"
            backdropFilter="blur(16px) saturate(180%)"
            borderRadius="2xl"
            boxShadow="0 24px 70px rgba(0,0,0,0.3), 0 10px 30px rgba(0,0,0,0.22), inset 0 1px 0 rgba(255,255,255,0.5)"
            border="2px solid"
            borderColor="rgba(255,255,255,0.4)"
            zIndex={10001}
            overflow="hidden"
            onMouseDown={(e) => handlePanelMouseDown('stylePicker', e)}
            cursor={draggingPanel === 'stylePicker' ? 'grabbing' : 'default'}
            fontFamily="var(--chakra-fonts-body)"
            sx={{
              '@keyframes slideInBounce': {
                '0%': { opacity: 0, transform: 'translateY(-30px) scale(0.9)' },
                '60%': { opacity: 1, transform: 'translateY(5px) scale(1.02)' },
                '100%': { opacity: 1, transform: 'translateY(0) scale(1)' },
              },
              animation: 'slideInBounce 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)',
              '&::before': {
                content: '""',
                position: 'absolute',
                top: 0,
                left: 0,
                right: 0,
                height: '2px',
                background: `linear-gradient(90deg, ${selectedBg}, transparent)`,
                opacity: 0.6
              }
            }}
          >
            {/* Header */}
            <Flex
              className="panel-header"
              bgGradient={`linear(135deg, ${selectedBg}, ${selectedBg}dd)`}
              color="white"
              p={4}
              align="center"
              justify="space-between"
              cursor="move"
              borderTopRadius="2xl"
              boxShadow="0 4px 12px rgba(0,0,0,0.1)"
              borderBottom="1px solid rgba(255,255,255,0.2)"
            >
              <HStack>
                <FiSettings />
                <Heading size="sm" textTransform="uppercase" letterSpacing="wider" fontWeight="800">
                  {PREDEFINED_ELEMENTS.find(e => e.name === selectedElement)?.label || selectedElement}
                </Heading>
              </HStack>
              <HStack spacing={1}>
                <Tooltip label="Přesunout nahoru">
                  <IconButton
                    aria-label="Přesunout nahoru"
                    icon={<FiChevronUp />}
                    size="sm"
                    variant="ghost"
                    colorScheme="whiteAlpha"
                    onClick={() => handleMoveUp(selectedElement)}
                    isDisabled={elementOrder.indexOf(selectedElement) === 0}
                  />
                </Tooltip>
                <Tooltip label="Přesunout dolů">
                  <IconButton
                    aria-label="Přesunout dolů"
                    icon={<FiChevronDown />}
                    size="sm"
                    variant="ghost"
                    colorScheme="whiteAlpha"
                    onClick={() => handleMoveDown(selectedElement)}
                    isDisabled={elementOrder.indexOf(selectedElement) === elementOrder.length - 1}
                  />
                </Tooltip>
                <Divider orientation="vertical" h="20px" borderColor="whiteAlpha.400" />
                <Tooltip label="Odebrat element">
                  <IconButton
                    aria-label="Odebrat element"
                    icon={<FiTrash2 />}
                    size="sm"
                    variant="ghost"
                    colorScheme="whiteAlpha"
                    onClick={() => handleRemoveElement(selectedElement)}
                  />
                </Tooltip>
                <IconButton
                  aria-label="Zavřít"
                  icon={<FiX />}
                  size="sm"
                  variant="ghost"
                  colorScheme="whiteAlpha"
                  onClick={() => setSelectedElement(null)}
                  borderRadius="full"
                />
              </HStack>
            </Flex>

            {/* Variant Grid */}
            <VStack align="stretch" p={4} spacing={3} maxH="450px" overflowY="auto">
              {/* Position Info */}
              <Flex justify="space-between" align="center" pb={2}>
                <HStack spacing={2}>
                  <FiMove size={14} />
                  <Text fontSize="xs" fontWeight="bold" color="gray.500" textTransform="uppercase">
                    Pozice {elementOrder.indexOf(selectedElement) + 1} z {elementOrder.length}
                  </Text>
                </HStack>
                <HStack spacing={1}>
                  <IconButton
                    aria-label="Přesunout nahoru"
                    icon={<FiChevronUp />}
                    size="xs"
                    variant="ghost"
                    onClick={() => handleMoveUp(selectedElement)}
                    isDisabled={elementOrder.indexOf(selectedElement) === 0}
                  />
                  <IconButton
                    aria-label="Přesunout dolů"
                    icon={<FiChevronDown />}
                    size="xs"
                    variant="ghost"
                    onClick={() => handleMoveDown(selectedElement)}
                    isDisabled={elementOrder.indexOf(selectedElement) === elementOrder.length - 1}
                  />
                </HStack>
              </Flex>
              
              <Divider />
              
              <Text fontSize="xs" fontWeight="bold" color="gray.500" textTransform="uppercase">
                Vyberte Styl
              </Text>
              
              <SimpleGrid columns={2} spacing={3}>
                {currentVariants.map((variant) => {
                  const isActive = currentVariant === variant.value;
                  return (
                    <Box
                      key={variant.value}
                      p={3}
                      borderRadius="lg"
                      border="2px"
                      borderColor={isActive ? selectedBg : borderColor}
                      bg={isActive ? useColorModeValue('blue.50', 'blue.900') : 'transparent'}
                      cursor="pointer"
                      transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
                      _hover={{
                        borderColor: selectedBg,
                        transform: 'translateY(-4px) scale(1.02)',
                        boxShadow: 'lg',
                      }}
                      _active={{
                        transform: 'translateY(-2px) scale(0.98)',
                      }}
                      onClick={() => handleVariantChange(selectedElement, variant.value)}
                      position="relative"
                    >
                      {isActive && (
                        <Badge
                          position="absolute"
                          top={1}
                          right={1}
                          colorScheme="green"
                          fontSize="9px"
                        >
                          AKTIVNÍ
                        </Badge>
                      )}
                      <VStack align="start" spacing={1}>
                        <Text fontWeight="bold" fontSize="sm">
                          {variant.label}
                        </Text>
                        <Text fontSize="xs" color="gray.500" noOfLines={2}>
                          {variant.description}
                        </Text>
                      </VStack>
                    </Box>
                  );
                })}
              </SimpleGrid>

              <Divider />

              {/* Quick Actions */}
              <HStack justify="space-between">
                <Text fontSize="xs" color="gray.500">
                  {currentVariants.length} dostupných stylů
                </Text>
                <Badge colorScheme={hasChanges ? 'orange' : 'gray'}>
                  {hasChanges ? 'Změněno' : 'Uloženo'}
                </Badge>
              </HStack>
            </VStack>
            {/* Resize handle */}
            <Box
              position="absolute"
              bottom={0}
              right={0}
              width="24px"
              height="24px"
              cursor="nwse-resize"
              bgGradient="linear(135deg, transparent, rgba(0,0,0,0.15))"
              opacity={0.4}
              _hover={{ opacity: 1, bgGradient: 'linear(135deg, transparent, rgba(0,0,0,0.25))' }}
              onMouseDown={(e) => handleResizeStart('stylePicker', e)}
              sx={{
                clipPath: 'polygon(100% 0, 100% 100%, 0 100%)'
              }}
              transition="all 0.2s"
            />
          </Box>
        </Portal>
      )}

      {/* Unsaved Changes Indicator */}
      {isEditing && hasChanges && (
        <Box
          position="fixed"
          top={4}
          right={4}
          zIndex={10000}
          bgGradient="linear(135deg, orange.400, orange.600)"
          color="white"
          px={5}
          py={2.5}
          borderRadius="full"
          boxShadow="0 8px 24px rgba(237, 137, 54, 0.4), 0 4px 12px rgba(0,0,0,0.2)"
          fontSize="sm"
          fontWeight="800"
          display="flex"
          alignItems="center"
          gap={2}
          border="2px solid rgba(255,255,255,0.3)"
          backdropFilter="blur(8px)"
          sx={{
            '@keyframes wiggle': {
              '0%, 100%': { transform: 'rotate(0deg)' },
              '25%': { transform: 'rotate(-3deg)' },
              '75%': { transform: 'rotate(3deg)' }
            },
            animation: 'wiggle 2s infinite'
          }}
        >
          <Icon as={FiAlertTriangle} boxSize={4} />
          Neuložené změny: {Object.keys(localChanges).filter(k => localChanges[k] !== (configs.find(c => c.element_name === k)?.variant)).length}
        </Box>
      )}

      {/* Help Hint */}
      {isEditing && showHelpHint && !selectedElement && (
        <Box
          position="fixed"
          top="50%"
          left="50%"
          transform="translate(-50%, -50%)"
          bg="rgba(255, 255, 255, 0.98)"
          backdropFilter="blur(20px) saturate(180%)"
          p={8}
          borderRadius="3xl"
          boxShadow="0 30px 90px rgba(0,0,0,0.3), 0 12px 40px rgba(0,0,0,0.22)"
          border="2px solid"
          borderColor="rgba(255,255,255,0.4)"
          zIndex={9999}
          maxW="450px"
          textAlign="center"
          fontFamily="var(--chakra-fonts-body)"
          sx={{
            '@keyframes fadeInScale': {
              '0%': { opacity: 0, transform: 'translate(-50%, -50%) scale(0.8)' },
              '100%': { opacity: 1, transform: 'translate(-50%, -50%) scale(1)' },
            },
            animation: 'fadeInScale 0.4s cubic-bezier(0.34, 1.56, 0.64, 1)'
          }}
        >
          <IconButton
            aria-label="Zavřít nápovědu"
            icon={<FiX />}
            size="sm"
            position="absolute"
            top={2}
            right={2}
            variant="ghost"
            onClick={() => setShowHelpHint(false)}
          />
          <VStack spacing={3}>
            <Box fontSize="48px">👆</Box>
            <Heading size="md">Klikněte na element pro úpravu</Heading>
            <Text color="gray.500" fontSize="sm">
              • Přejetím myši zvýrazníte sekce
              <br />
              • Klikněte přímo na element pro úpravu stylu
              <br />
              • Použijte tlačítka ⬆️⬇️ pro změnu pozice
              <br />
              • Klikněte na 🗑️ pro odstranění
              <br />
              • Přepněte viewport pro test responzivity
            </Text>
            <Button
              size="sm"
              colorScheme="blue"
              onClick={() => {
                setShowHelpHint(false);
                setShowElementPicker(true);
              }}
              leftIcon={<FaPlus />}
            >
              Přidat nový element
            </Button>
          </VStack>
        </Box>
      )}

      {/* Layers Panel - Visual element list with drag-drop */}
      {isEditing && showLayersPanel && (
        <Box
          className="myuibrix-panel"
          position="fixed"
          left={panelPositions.layersPanel.x === 0 ? undefined : `${panelPositions.layersPanel.x}px`}
          right={panelPositions.layersPanel.x === 0 ? 4 : undefined}
          top={panelPositions.layersPanel.y === 0 ? "50%" : `${panelPositions.layersPanel.y}px`}
          transform={panelPositions.layersPanel.y === 0 ? "translateY(-50%)" : undefined}
          width={`${panelPositions.layersPanel.width}px`}
          height={`${panelPositions.layersPanel.height}px`}
          bg="rgba(255, 255, 255, 0.97)"
          backdropFilter="blur(16px) saturate(180%)"
          borderRadius="2xl"
          boxShadow="0 24px 70px rgba(0,0,0,0.3), 0 10px 30px rgba(0,0,0,0.22)"
          border="2px solid"
          borderColor="rgba(255,255,255,0.4)"
          zIndex={10001}
          overflow="hidden"
          onMouseDown={(e) => handlePanelMouseDown('layersPanel', e)}
          cursor={draggingPanel === 'layersPanel' ? 'grabbing' : 'default'}
          fontFamily="var(--chakra-fonts-body)"
          sx={{
            '@keyframes slideInRight': {
              from: { opacity: 0, transform: panelPositions.layersPanel.y === 0 ? 'translate(40px, -50%)' : 'translateX(40px)' },
              to: { opacity: 1, transform: panelPositions.layersPanel.y === 0 ? 'translateY(-50%)' : 'translateX(0)' }
            },
            animation: 'slideInRight 0.3s cubic-bezier(0.4, 0, 0.2, 1)'
          }}
        >
          {/* Header */}
          <Flex
            className="panel-header"
            bgGradient={`linear(135deg, ${secondaryColor}, ${secondaryColor}dd)`}
            color="white"
            p={4}
            align="center"
            justify="space-between"
            cursor="move"
            borderTopRadius="2xl"
            boxShadow="0 4px 12px rgba(0,0,0,0.15)"
            borderBottom="1px solid rgba(255,255,255,0.2)"
          >
            <HStack>
              <FiMove />
              <Heading size="sm" fontWeight="800" letterSpacing="wide">Vrstvy Elementů</Heading>
            </HStack>
            <IconButton
              aria-label="Zavřít"
              icon={<FiX />}
              size="sm"
              variant="ghost"
              colorScheme="whiteAlpha"
              onClick={() => setShowLayersPanel(false)}
            />
          </Flex>

          {/* Layers List */}
          <VStack align="stretch" p={3} spacing={2} maxH="calc(80vh - 60px)" overflowY="auto">
            {elementOrder.map((elementName, index) => {
              const element = PREDEFINED_ELEMENTS.find(e => e.name === elementName);
              const isVisible = visibleElements.has(elementName);
              const isSelected = selectedElement === elementName;
              
              const isDragging = draggedElement === elementName;
              const isDragOver = dragOverElement === elementName;
              
              return (
                <Box
                  key={elementName}
                  p={3}
                  borderRadius="lg"
                  border="2px"
                  borderColor={isDragOver ? primaryColor : isSelected ? secondaryColor : 'gray.200'}
                  bgGradient={isDragging ? 'linear(to-r, gray.100, gray.200)' : isSelected ? `linear(135deg, ${secondaryColor}15, ${secondaryColor}25)` : isVisible ? 'linear(to-r, white, gray.50)' : 'linear(to-r, gray.100, gray.150)'}
                  cursor={isDragging ? 'grabbing' : 'grab'}
                  opacity={isDragging ? 0.6 : isVisible ? 1 : 0.5}
                  transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
                  transform={isDragOver ? 'scale(1.03) translateX(8px)' : undefined}
                  boxShadow={isSelected ? '0 4px 12px rgba(0,0,0,0.1)' : '0 2px 4px rgba(0,0,0,0.05)'}
                  _hover={{
                    borderColor: secondaryColor,
                    transform: isDragOver ? 'scale(1.03) translateX(8px)' : 'translateX(6px) translateY(-2px)',
                    boxShadow: '0 6px 16px rgba(0,0,0,0.12)'
                  }}
                  draggable
                  onDragStart={(e) => {
                    handleDragStart(elementName, e);
                    (e.target as HTMLElement).style.cursor = 'grabbing';
                  }}
                  onDragEnd={(e) => {
                    (e.target as HTMLElement).style.cursor = 'grab';
                    handleDragEnd();
                  }}
                  onDragOver={(e) => handleDragOver(e, elementName)}
                  onDragLeave={(e) => handleDragLeave(e)}
                  onDrop={(e) => handleDrop(e, elementName)}
                  onClick={() => {
                    setSelectedElement(elementName);
                    const el = safeDOM.querySelector(`[data-element="${elementName}"]`);
                    if (el) {
                      const rect = el.getBoundingClientRect();
                      setElementPosition({
                        top: rect.top,
                        left: rect.left,
                        width: rect.width,
                        height: rect.height,
                      });
                    }
                  }}
                >
                  <Flex align="center" justify="space-between">
                    <HStack flex={1} spacing={2}>
                      <Icon 
                        as={FaGripVertical} 
                        boxSize={4} 
                        color="gray.400"
                        cursor="grab"
                        _active={{ cursor: 'grabbing' }}
                      />
                      <Box
                        p={2}
                        bg={isSelected ? secondaryColor : `${secondaryColor}20`}
                        borderRadius="lg"
                        transition="all 0.2s"
                      >
                        <Icon as={element?.icon || FaCube} boxSize={5} color={isSelected ? 'white' : secondaryColor} />
                      </Box>
                      <VStack align="start" spacing={0} flex={1}>
                        <Text fontWeight="bold" fontSize="sm">
                          {element?.label || elementName}
                        </Text>
                        <Text fontSize="xs" color="gray.500">
                          Pozice {index + 1}
                        </Text>
                      </VStack>
                    </HStack>
                    
                    <HStack spacing={1}>
                      <IconButton
                        aria-label="Přesunout nahoru"
                        icon={<FiChevronUp />}
                        size="xs"
                        variant="ghost"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleMoveUp(elementName);
                        }}
                        isDisabled={index === 0}
                      />
                      <IconButton
                        aria-label="Přesunout dolů"
                        icon={<FiChevronDown />}
                        size="xs"
                        variant="ghost"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleMoveDown(elementName);
                        }}
                        isDisabled={index === elementOrder.length - 1}
                      />
                      <IconButton
                        aria-label={isVisible ? "Skrýt" : "Zobrazit"}
                        icon={<FiEyeOff />}
                        size="xs"
                        variant="ghost"
                        colorScheme={isVisible ? "gray" : "red"}
                        onClick={(e) => {
                          e.stopPropagation();
                          if (isVisible) {
                            handleRemoveElement(elementName);
                          } else {
                            const newVisible = new Set(visibleElements);
                            newVisible.add(elementName);
                            setVisibleElements(newVisible);
                            setHasChanges(true);
                          }
                        }}
                      />
                    </HStack>
                  </Flex>
                </Box>
              );
            })}
            
            {elementOrder.length === 0 && (
              <Box textAlign="center" py={8}>
                  <Icon as={FaBoxOpen} boxSize={12} color="gray.300" mb={3} />
                  <Text fontSize="sm" color="gray.500" fontWeight="bold">
                    Zatím žádné elementy
                  </Text>
                  <Text fontSize="xs" color="gray.400" mb={3}>
                    Začněte přidáním prvého elementu
                  </Text>
                  <Button
                    size="sm"
                    bg={primaryColor}
                    color="white"
                    _hover={{ opacity: 0.9 }}
                    leftIcon={<FaPlus />}
                    onClick={() => {
                      setShowLayersPanel(false);
                      setShowElementPicker(true);
                    }}
                  >
                    Přidat Element
                  </Button>
              </Box>
            )}
          </VStack>
          {/* Resize handle */}
          <Box
            position="absolute"
            bottom={0}
            right={0}
            width="20px"
            height="20px"
            cursor="nwse-resize"
            bg="gray.400"
            opacity={0.6}
            _hover={{ opacity: 1 }}
            onMouseDown={(e) => handleResizeStart('layersPanel', e)}
            sx={{
              clipPath: 'polygon(100% 0, 100% 100%, 0 100%)'
            }}
          />
        </Box>
      )}

      {/* Element Picker Modal */}
      {showElementPicker && (
        <Portal>
          <Box
            position="fixed"
            top={0}
            left={0}
            right={0}
            bottom={0}
            bg="blackAlpha.700"
            backdropFilter="blur(8px)"
            zIndex={10002}
            onClick={() => {
              setShowElementPicker(false);
              setSearchQuery('');
              setSelectedCategory('all');
            }}
            sx={{
              '@keyframes fadeInBackdrop': {
                from: { opacity: 0 },
                to: { opacity: 1 }
              },
              animation: 'fadeInBackdrop 0.2s ease-out'
            }}
          />
          <Box
            className="myuibrix-panel"
            position="fixed"
            left={panelPositions.elementPicker.x === 0 ? "50%" : `${panelPositions.elementPicker.x}px`}
            top={panelPositions.elementPicker.y === 0 ? "50%" : `${panelPositions.elementPicker.y}px`}
            transform={panelPositions.elementPicker.x === 0 && panelPositions.elementPicker.y === 0 ? "translate(-50%, -50%)" : undefined}
            width={`${panelPositions.elementPicker.width}px`}
            height={`${panelPositions.elementPicker.height}px`}
            maxWidth="90vw"
            bg="rgba(255, 255, 255, 0.98)"
            backdropFilter="blur(20px) saturate(180%)"
            borderRadius="3xl"
            boxShadow="0 40px 120px rgba(0,0,0,0.4), 0 16px 50px rgba(0,0,0,0.3)"
            border="2px solid"
            borderColor="rgba(255,255,255,0.5)"
            zIndex={10003}
            overflow="hidden"
            onMouseDown={(e) => handlePanelMouseDown('elementPicker', e)}
            cursor={draggingPanel === 'elementPicker' ? 'grabbing' : 'default'}
            fontFamily="var(--chakra-fonts-body)"
            sx={{
              '@keyframes modalZoomIn': {
                '0%': { opacity: 0, transform: panelPositions.elementPicker.x === 0 && panelPositions.elementPicker.y === 0 ? 'translate(-50%, -50%) scale(0.85)' : 'scale(0.85)' },
                '100%': { opacity: 1, transform: panelPositions.elementPicker.x === 0 && panelPositions.elementPicker.y === 0 ? 'translate(-50%, -50%) scale(1)' : 'scale(1)' }
              },
              animation: 'modalZoomIn 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)'
            }}
          >
            {/* Header */}
            <Flex
              className="panel-header"
              bgGradient={`linear(135deg, ${primaryColor}, ${primaryColor}dd)`}
              color="white"
              p={5}
              align="center"
              justify="space-between"
              cursor="move"
              borderTopRadius="3xl"
              boxShadow="0 6px 16px rgba(0,0,0,0.15)"
              borderBottom="1px solid rgba(255,255,255,0.2)"
            >
              <HStack spacing={3}>
                <Box
                  p={2}
                  bg="whiteAlpha.300"
                  borderRadius="lg"
                  backdropFilter="blur(8px)"
                >
                  <Icon as={FaPlus} boxSize={6} />
                </Box>
                <Heading size="md" fontWeight="900" letterSpacing="tight">Přidat Element</Heading>
              </HStack>
              <IconButton
                aria-label="Zavřít"
                icon={<FiX />}
                size="sm"
                variant="ghost"
                colorScheme="whiteAlpha"
                onClick={() => {
                  setShowElementPicker(false);
                  setSearchQuery('');
                  setSelectedCategory('all');
                }}
              />
            </Flex>

            {/* Search and Filter Bar */}
            <Box p={5} borderBottom="1px" borderColor="gray.100" bg="gray.50">
              <VStack spacing={4}>
                <Input
                  placeholder="🔍 Hledat element..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  size="lg"
                  bg="white"
                  borderRadius="xl"
                  border="2px solid"
                  borderColor="gray.200"
                  _hover={{ borderColor: primaryColor }}
                  _focus={{ borderColor: primaryColor, boxShadow: `0 0 0 3px ${primaryColor}33` }}
                  fontSize="md"
                  fontWeight="500"
                  transition="all 0.2s"
                />
                <HStack spacing={2} w="full" overflowX="auto" pb={1}>
                  {[
                    { value: 'all', label: 'Všechny', icon: FaCube },
                    { value: 'layout', label: 'Rozvržení', icon: FaThLarge },
                    { value: 'content', label: 'Obsah', icon: FaNewspaper },
                    { value: 'media', label: 'Média', icon: FaPhotoVideo },
                    { value: 'interactive', label: 'Interaktivní', icon: FaGamepad },
                  ].map((cat) => (
                    <Button
                      key={cat.value}
                      size="md"
                      variant={selectedCategory === cat.value ? 'solid' : 'outline'}
                      bgGradient={selectedCategory === cat.value ? `linear(135deg, ${primaryColor}, ${primaryColor}dd)` : undefined}
                      color={selectedCategory === cat.value ? 'white' : 'gray.700'}
                      borderColor={selectedCategory === cat.value ? 'transparent' : 'gray.300'}
                      borderRadius="xl"
                      fontWeight="700"
                      boxShadow={selectedCategory === cat.value ? '0 4px 12px rgba(0,0,0,0.15)' : 'none'}
                      _hover={{ 
                        bg: selectedCategory === cat.value ? undefined : 'gray.100',
                        transform: 'translateY(-2px)',
                        boxShadow: selectedCategory === cat.value ? '0 6px 16px rgba(0,0,0,0.2)' : '0 2px 8px rgba(0,0,0,0.1)'
                      }}
                      onClick={() => setSelectedCategory(cat.value)}
                      leftIcon={<Icon as={cat.icon} />}
                      minW="fit-content"
                      transition="all 0.2s cubic-bezier(0.4, 0, 0.2, 1)"
                    >
                      {cat.label}
                    </Button>
                  ))}
                </HStack>
              </VStack>
            </Box>

            {/* Element Grid by Category */}
            <VStack align="stretch" p={4} spacing={4} maxH="calc(80vh - 200px)" overflowY="auto">
              {['layout', 'content', 'media', 'interactive'].map((category) => {
                // Filter by category selection
                if (selectedCategory !== 'all' && selectedCategory !== category) return null;
                
                // IMPORTANT: Only show elements that are actually implemented on this page
                const implementedForThisPage = pageType === 'homepage' ? HOMEPAGE_IMPLEMENTED_ELEMENTS : [];
                
                const elements = PREDEFINED_ELEMENTS.filter(e => 
                  e.category === category && 
                  (implementedForThisPage.length === 0 || implementedForThisPage.includes(e.name))
                );
                
                const availableElements = elements.filter(e => {
                  if (visibleElements.has(e.name)) return false;
                  // Filter by search query
                  if (searchQuery) {
                    const query = searchQuery.toLowerCase();
                    return e.label.toLowerCase().includes(query) || 
                           e.description.toLowerCase().includes(query);
                  }
                  return true;
                });
                
                if (availableElements.length === 0) return null;
                
                const categoryLabels = {
                  layout: 'Rozvržení',
                  content: 'Obsah',
                  media: 'Média',
                  interactive: 'Interaktivní'
                };
                
                return (
                  <Box key={category}>
                    <Text fontSize="sm" fontWeight="bold" color="gray.500" textTransform="uppercase" mb={2}>
                      {categoryLabels[category as keyof typeof categoryLabels]}
                    </Text>
                    <SimpleGrid columns={{ base: 1, md: 2 }} spacing={3}>
                      {availableElements.map((element) => (
                        <Box
                          key={element.name}
                          p={4}
                          borderRadius="xl"
                          border="2px solid"
                          borderColor="gray.200"
                          bg="white"
                          cursor="pointer"
                          transition="all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
                          _hover={{
                            borderColor: primaryColor,
                            transform: 'translateY(-4px) scale(1.02)',
                            boxShadow: `0 8px 24px rgba(0,0,0,0.12), 0 0 0 2px ${primaryColor}22`,
                            bg: `${primaryColor}05`
                          }}
                          _active={{
                            transform: 'translateY(-2px) scale(1)'
                          }}
                          onClick={() => handleAddElement(element.name)}
                        >
                          <HStack spacing={3}>
                            <Box
                              p={3}
                              bgGradient={`linear(135deg, ${primaryColor}15, ${primaryColor}25)`}
                              borderRadius="xl"
                              transition="all 0.2s"
                            >
                              <Icon as={element.icon} boxSize={6} color={primaryColor} />
                            </Box>
                            <VStack align="start" spacing={0} flex={1}>
                              <Text fontWeight="bold" fontSize="sm">
                                {element.label}
                              </Text>
                              <Text fontSize="xs" color="gray.500">
                                {element.description}
                              </Text>
                            </VStack>
                            <Icon as={FaPlus} color={primaryColor} />
                          </HStack>
                        </Box>
                      ))}
                    </SimpleGrid>
                  </Box>
                );
              })}
              
              {PREDEFINED_ELEMENTS.every(e => visibleElements.has(e.name)) && (
                <Box textAlign="center" py={8}>
                  <Icon as={FaSmile} boxSize={8} color={primaryColor} mb={2} />
                  <Text fontSize="lg" fontWeight="bold" mb={2}>
                    Všechny elementy přidány!
                  </Text>
                  <Text fontSize="sm" color="gray.500">
                    Používáte všechny dostupné elementy
                  </Text>
                </Box>
              )}
              
              {/* No results message */}
              {!PREDEFINED_ELEMENTS.some(e => {
                const matchesCategory = selectedCategory === 'all' || e.category === selectedCategory;
                const matchesSearch = !searchQuery || 
                  e.label.toLowerCase().includes(searchQuery.toLowerCase()) || 
                  e.description.toLowerCase().includes(searchQuery.toLowerCase());
                return !visibleElements.has(e.name) && matchesCategory && matchesSearch;
              }) && !PREDEFINED_ELEMENTS.every(e => visibleElements.has(e.name)) && (
                <Box textAlign="center" py={8}>
                  <Icon as={FaExclamationCircle} boxSize={8} color="gray.400" mb={2} />
                  <Text fontSize="md" fontWeight="bold" mb={1}>
                    Žádné výsledky
                  </Text>
                  <Text fontSize="sm" color="gray.500">
                    Zkuste změnit vyhledávací dotaz nebo filtr
                  </Text>
                </Box>
              )}
            </VStack>
            {/* Resize handle */}
              <Box
                position="absolute"
                bottom={0}
                right={0}
                width="24px"
                height="24px"
                cursor="nwse-resize"
                bgGradient="linear(135deg, transparent, rgba(0,0,0,0.15))"
                opacity={0.4}
                _hover={{ opacity: 1, bgGradient: 'linear(135deg, transparent, rgba(0,0,0,0.25))' }}
                onMouseDown={(e) => handleResizeStart('elementPicker', e)}
                sx={{
                  clipPath: 'polygon(100% 0, 100% 100%, 0 100%)'
                }}
                transition="all 0.2s"
              />
          </Box>
        </Portal>
      )}
    </>
  );
};

export default MyUIbrixStyleEditor;
