import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { fetch as fetchPage } from '../../stores/pages/pagesSlice';
import { fetch as fetchLayers, update as updateLayer, create as createLayer, deleteItem as removeLayerAction } from '../../stores/layers/layersSlice';
import BaseIcon from '../BaseIcon';
import {
  mdiCalendar,
  mdiCardOutline,
  mdiCellphone,
  mdiChevronDown,
  mdiCloudUploadOutline,
  mdiCursorDefaultClick,
  mdiCursorDefaultClickOutline,
  mdiFilterVariant,
  mdiFlash,
  mdiFlashOutline,
  mdiFolderImage,
  mdiFormatText,
  mdiHelpCircleOutline,
  mdiImageOutline,
  mdiLayers,
  mdiMenu,
  mdiMinus,
  mdiMonitor,
  mdiPencil,
  mdiPlay,
  mdiPlus,
  mdiSquareOutline,
  mdiStar,
  mdiTablet,
  mdiVectorSquare
} from '@mdi/js';
import LoadingSpinner from '../LoadingSpinner';
import CardBox from '../CardBox';
import Link from 'next/link';

interface PageBuilderProps {
  pageId: string;
}

const WIDGETS = [
  { type: 'frame', label: 'Frame', icon: mdiVectorSquare, description: 'Basic container' },
  { type: 'text', label: 'Text', icon: mdiFormatText, description: 'Text element' },
  { type: 'button', label: 'Button', icon: mdiCursorDefaultClick, description: 'Interactive button' },
  { type: 'card', label: 'Card', icon: mdiCardOutline, description: 'Styled card container' },
  { type: 'image', label: 'Image', icon: mdiImageOutline, description: 'Image placeholder' },
  { type: 'calendar', label: 'Calendar', icon: mdiCalendar, description: 'Event calendar' },
];

const PageBuilder: React.FC<PageBuilderProps> = ({ pageId }) => {
  const dispatch = useAppDispatch();
  const { pages: page, isFetching: isFetchingPage } = useAppSelector((state) => state.pages);
  const { layers: allLayers, isFetching: isFetchingLayers } = useAppSelector((state) => state.layers);
  
  const [selectedLayerId, setSelectedLayerId] = useState<string | null>(null);
  const [zoom, setZoom] = useState(100);
  const [localLayer, setLocalLayer] = useState<any>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [sidebarTab, setSidebarTab] = useState<'layers' | 'widgets' | 'assets'>('layers');
  const [activeTabRight, setActiveTabRight] = useState<'style' | 'settings' | 'interactions'>('style');
  const [viewportWidth, setViewportWidth] = useState(1440);
  
  const dragStartPos = useRef({ x: 0, y: 0 });
  const initialLayerPos = useRef({ x: 0, y: 0 });
  const canvasRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (pageId) {
      dispatch(fetchPage({ id: pageId }));
      dispatch(fetchLayers({})); 
    }
  }, [pageId, dispatch]);

  const pageLayers = Array.isArray(allLayers) 
    ? [...allLayers].filter((l: any) => l.pageId === pageId || l.page?.id === pageId)
        .sort((a, b) => (a.order || 0) - (b.order || 0))
    : [];

  const selectedLayerFromStore = pageLayers.find((l: any) => l.id === selectedLayerId);

  useEffect(() => {
    if (selectedLayerFromStore) {
      setLocalLayer({
        ...selectedLayerFromStore,
        parsedProps: selectedLayerFromStore.props ? JSON.parse(selectedLayerFromStore.props) : {}
      });
    } else {
      setLocalLayer(null);
    }
  }, [selectedLayerId, selectedLayerFromStore]);

  const handlePropertyChange = (key: string, value: any, isProp = true) => {
    if (!localLayer) return;

    if (isProp) {
      setLocalLayer({
        ...localLayer,
        parsedProps: {
          ...localLayer.parsedProps,
          [key]: value
        }
      });
    } else {
      setLocalLayer({
        ...localLayer,
        [key]: value
      });
    }
  };

  const saveLayer = useCallback(async (layerToSave: any) => {
    if (!layerToSave) return;
    const { parsedProps, ...rest } = layerToSave;
    await dispatch(updateLayer({
      id: rest.id,
      data: {
        ...rest,
        props: JSON.stringify(parsedProps)
      }
    }));
  }, [dispatch]);

  const handleBlur = () => {
    if (localLayer && JSON.stringify(localLayer) !== JSON.stringify({
      ...selectedLayerFromStore,
      parsedProps: selectedLayerFromStore.props ? JSON.parse(selectedLayerFromStore.props) : {}
    })) {
      saveLayer(localLayer);
    }
  };

  const addNewLayer = async (type: string, x = 50, y = 50) => {
    const defaultProps = {
      x,
      y,
      width: type === 'calendar' ? 500 : type === 'card' ? 300 : type === 'image' ? 300 : 200,
      height: type === 'calendar' ? 400 : type === 'card' ? 200 : type === 'image' ? 200 : (type === 'text' ? 40 : 200),
      backgroundColor: type === 'frame' ? '#ffffff' : type === 'button' ? '#0070f3' : type === 'card' ? '#ffffff' : 'transparent',
      color: type === 'button' ? '#ffffff' : '#000000',
      fontSize: '16px',
      borderRadius: type === 'button' || type === 'card' ? '8px' : '0px',
      padding: '16px'
    };

    const newLayerData = {
      name: `New ${type}`,
      layer_type: type,
      pageId: pageId,
      props: JSON.stringify(defaultProps),
      order: pageLayers.length,
      visible: true
    };

    const result: any = await dispatch(createLayer(newLayerData));
    if (result.payload?.id) {
       setSelectedLayerId(result.payload.id);
       dispatch(fetchLayers({})); 
    }
  };

  const removeLayer = async (id: string) => {
    await dispatch(removeLayerAction(id));
    setSelectedLayerId(null);
    dispatch(fetchLayers({}));
  };

  const handleMouseDown = (e: React.MouseEvent, layer: any) => {
    e.stopPropagation();
    if (selectedLayerId !== layer.id) {
      setSelectedLayerId(layer.id);
    }
    
    setIsDragging(true);
    dragStartPos.current = { x: e.clientX, y: e.clientY };
    const props = layer.props ? JSON.parse(layer.props) : {};
    initialLayerPos.current = { x: props.x || 0, y: props.y || 0 };
  };

  const handleMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !localLayer) return;

    const dx = (e.clientX - dragStartPos.current.x) / (zoom / 100);
    const dy = (e.clientY - dragStartPos.current.y) / (zoom / 100);

    setLocalLayer({
      ...localLayer,
      parsedProps: {
        ...localLayer.parsedProps,
        x: Math.round(initialLayerPos.current.x + dx),
        y: Math.round(initialLayerPos.current.y + dy)
      }
    });
  };

  const handleMouseUp = () => {
    if (isDragging) {
      setIsDragging(false);
      handleBlur();
    }
  };

  const handleWidgetDragStart = (e: React.DragEvent, type: string) => {
    e.dataTransfer.setData('widgetType', type);
  };

  const handleCanvasDrop = (e: React.DragEvent) => {
    e.preventDefault();
    const type = e.dataTransfer.getData('widgetType');
    if (!type || !canvasRef.current) return;

    const rect = canvasRef.current.getBoundingClientRect();
    const x = (e.clientX - rect.left) / (zoom / 100);
    const y = (e.clientY - rect.top) / (zoom / 100);

    addNewLayer(type, Math.round(x), Math.round(y));
  };

  if (isFetchingPage || isFetchingLayers) {
    return <LoadingSpinner />;
  }

  return (
    <div className="flex flex-col h-screen bg-[#000000] text-gray-300 font-sans overflow-hidden select-none">
      
      {/* --- TOP NAVIGATION BAR --- */}
      <div className="h-12 border-b border-white/5 bg-[#111111] flex items-center justify-between px-3 z-50">
        <div className="flex items-center space-x-1">
          <Link href="/dashboard" className="p-2 hover:bg-white/5 rounded-md transition-colors mr-2">
            <BaseIcon path={mdiMenu} size={20} className="text-gray-400" />
          </Link>
          
          <div className="flex items-center space-x-1 px-1">
            <button className="flex items-center space-x-2 px-3 py-1.5 rounded-md bg-white/5 text-xs font-medium text-white">
              <span>Design</span>
              <BaseIcon path={mdiChevronDown} size={14} className="opacity-50" />
            </button>
            <button className="px-3 py-1.5 rounded-md hover:bg-white/5 text-xs font-medium text-gray-400 transition-colors">CMS</button>
            <button className="flex items-center space-x-2 px-3 py-1.5 rounded-md hover:bg-white/5 text-xs font-medium text-gray-400 transition-colors">
              <BaseIcon path={mdiStar} size={14} className="text-blue-400" />
              <span>App Gen</span>
            </button>
            <button className="px-3 py-1.5 rounded-md hover:bg-white/5 text-xs font-medium text-gray-400 transition-colors">Insights</button>
          </div>
        </div>

        <div className="absolute left-1/2 -translate-x-1/2 flex items-center space-x-2 text-[11px] text-gray-500 font-medium">
          {localLayer ? (
            <div className="flex items-center space-x-2">
               <span className="text-blue-400">{localLayer.name}</span>
               <span className="opacity-30">|</span>
               <span>{localLayer.layer_type}</span>
            </div>
          ) : (
            <span>No element selected</span>
          )}
        </div>

        <div className="flex items-center space-x-4">
          <div className="flex items-center bg-white/5 p-0.5 rounded-lg border border-white/5">
             <button onClick={() => setViewportWidth(1440)} className={`p-1.5 rounded-md transition-all ${viewportWidth === 1440 ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'}`}>
                <BaseIcon path={mdiMonitor} size={16} />
             </button>
             <button onClick={() => setViewportWidth(768)} className={`p-1.5 rounded-md transition-all ${viewportWidth === 768 ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'}`}>
                <BaseIcon path={mdiTablet} size={16} />
             </button>
             <button onClick={() => setViewportWidth(375)} className={`p-1.5 rounded-md transition-all ${viewportWidth === 375 ? 'bg-white/10 text-white' : 'text-gray-500 hover:text-gray-300'}`}>
                <BaseIcon path={mdiCellphone} size={16} />
             </button>
          </div>

          <div className="flex items-center bg-white/5 rounded-lg px-2 py-1 h-8 border border-white/5">
            <button onClick={() => setZoom(z => Math.max(10, z - 10))} className="p-1 hover:text-white transition-colors">
              <BaseIcon path={mdiMinus} size={12} />
            </button>
            <span className="text-[10px] font-mono w-10 text-center">{zoom}%</span>
            <button onClick={() => setZoom(z => Math.min(400, z + 10))} className="p-1 hover:text-white transition-colors">
              <BaseIcon path={mdiPlus} size={12} />
            </button>
          </div>

          <div className="flex items-center space-x-2">
            <button className="p-2 hover:bg-white/5 rounded-md text-gray-400">
               <BaseIcon path={mdiPlay} size={18} />
            </button>
            <button className="px-3 py-1.5 text-xs font-bold text-gray-300 hover:text-white transition-colors">Share</button>
            <button className="bg-white text-black px-4 py-1.5 rounded-md text-xs font-bold hover:bg-gray-200 transition-all shadow-lg shadow-white/5">
              Publish
            </button>
          </div>
        </div>
      </div>

      <div className="flex flex-grow overflow-hidden">
        
        {/* --- LEFT SIDEBAR (Icon Rail + Panel) --- */}
        <div className="flex bg-[#111111] border-r border-white/5">
           {/* Icon Rail */}
           <div className="w-12 border-r border-white/5 flex flex-col items-center py-4 space-y-4">
              <button onClick={() => setSidebarTab('layers')} className={`p-2 rounded-lg transition-colors ${sidebarTab === 'layers' ? 'text-blue-500 bg-blue-500/10' : 'text-gray-500 hover:text-gray-300'}`}>
                 <BaseIcon path={mdiLayers} size={20} />
              </button>
              <button onClick={() => setSidebarTab('widgets')} className={`p-2 rounded-lg transition-colors ${sidebarTab === 'widgets' ? 'text-blue-500 bg-blue-500/10' : 'text-gray-500 hover:text-gray-300'}`}>
                 <BaseIcon path={mdiPencil} size={20} />
              </button>
              <button onClick={() => setSidebarTab('assets')} className={`p-2 rounded-lg transition-colors ${sidebarTab === 'assets' ? 'text-blue-500 bg-blue-500/10' : 'text-gray-500 hover:text-gray-300'}`}>
                 <BaseIcon path={mdiFolderImage} size={20} />
              </button>
           </div>

           {/* Content Panel */}
           <div className="w-60 flex flex-col bg-[#111111]">
              <div className="p-4 border-b border-white/5 flex items-center justify-between">
                 <span className="text-[11px] font-bold uppercase tracking-widest text-gray-500">
                    {sidebarTab === 'layers' ? 'Navigator' : sidebarTab === 'widgets' ? 'Components' : 'Assets'}
                 </span>
                 <BaseIcon path={mdiFilterVariant} size={14} className="text-gray-600 cursor-pointer" />
              </div>

              <div className="flex-grow overflow-y-auto">
                {sidebarTab === 'widgets' ? (
                  <div className="p-3 grid grid-cols-2 gap-2">
                    {WIDGETS.map((widget) => (
                      <div
                        key={widget.type}
                        draggable
                        onDragStart={(e) => handleWidgetDragStart(e, widget.type)}
                        onClick={() => addNewLayer(widget.type)}
                        className="bg-white/5 hover:bg-white/10 border border-white/5 rounded-lg p-3 flex flex-col items-center justify-center cursor-grab active:cursor-grabbing transition-all group"
                      >
                        <BaseIcon path={widget.icon} size={20} className="text-gray-400 group-hover:text-blue-400 mb-2" />
                        <span className="text-[10px] font-medium text-gray-400">{widget.label}</span>
                      </div>
                    ))}
                  </div>
                ) : sidebarTab === 'layers' ? (
                  <div className="p-2 space-y-0.5">
                    {pageLayers.length === 0 ? (
                      <div className="p-8 text-[10px] text-gray-600 italic text-center">No layers yet</div>
                    ) : (
                      <div className="space-y-1">
                         <div className="flex items-center px-3 py-1.5 text-xs text-gray-400 font-medium">
                            <BaseIcon path={mdiMonitor} size={14} className="mr-2 opacity-50" />
                            <span>Body</span>
                         </div>
                         <div className="pl-4 space-y-0.5">
                            {pageLayers.map((layer: any) => (
                              <div
                                key={layer.id}
                                onClick={() => setSelectedLayerId(layer.id)}
                                className={`flex items-center px-3 py-1.5 rounded cursor-pointer text-[12px] group transition-colors ${
                                  selectedLayerId === layer.id ? 'bg-blue-600 text-white' : 'hover:bg-white/5 text-gray-400'
                                }`}
                              >
                                <BaseIcon 
                                  path={WIDGETS.find(w => w.type === layer.layer_type)?.icon || mdiSquareOutline} 
                                  size={14} 
                                  className={`mr-2 ${selectedLayerId === layer.id ? 'opacity-100' : 'opacity-40'}`}
                                />
                                <span className="truncate flex-grow">{layer.name || layer.layer_type}</span>
                                {selectedLayerId === layer.id && (
                                   <BaseIcon path={mdiFlash} size={12} className="text-white/60" />
                                )}
                              </div>
                            ))}
                         </div>
                      </div>
                    )}
                  </div>
                ) : (
                  <div className="p-8 text-center space-y-3">
                     <BaseIcon path={mdiCloudUploadOutline} size={32} className="mx-auto text-gray-700" />
                     <p className="text-[10px] text-gray-600">Drag and drop assets here to upload</p>
                  </div>
                )}
              </div>
           </div>
        </div>

        {/* --- MAIN CANVAS AREA --- */}
        <div 
          className="flex-grow relative overflow-auto bg-[#080808] flex items-center justify-center p-60"
          onClick={() => setSelectedLayerId(null)}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
          onDragOver={(e) => e.preventDefault()}
          onDrop={handleCanvasDrop}
        >
          {/* Canvas Wrapper (The Frame) */}
          <div className="flex flex-col items-center">
             {/* Frame Info Header */}
             <div className="flex items-center justify-between w-full px-2 mb-2 text-[10px] font-mono text-gray-600">
                <div className="flex items-center space-x-2">
                   <BaseIcon path={mdiVectorSquare} size={12} />
                   <span>{viewportWidth === 1440 ? 'Desktop' : viewportWidth === 768 ? 'Tablet' : 'Mobile'}</span>
                </div>
                <span>{viewportWidth}px × 900px</span>
             </div>

             <div 
               ref={canvasRef}
               className="bg-white shadow-[0_0_80px_rgba(0,0,0,0.8)] relative transition-all duration-500 ease-in-out"
               style={{ 
                 width: `${viewportWidth}px`, 
                 height: '900px', 
                 transform: `scale(${zoom / 100})`,
                 transformOrigin: 'top center'
               }}
             >
               {/* Grid Pattern (Hidden in screenshot, but good for UX) */}
               {/* <div className="absolute inset-0 bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] [background-size:20px_20px] pointer-events-none opacity-20"></div> */}

               {/* Render Layers */}
               {pageLayers.map((layer: any) => {
                 const isSelected = selectedLayerId === layer.id;
                 const displayLayer = isSelected && localLayer ? localLayer : {
                   ...layer,
                   parsedProps: layer.props ? JSON.parse(layer.props) : {}
                 };
                 const props = displayLayer.parsedProps;

                 return (
                   <div
                     key={layer.id}
                     onMouseDown={(e) => handleMouseDown(e, layer)}
                     className={`absolute cursor-pointer flex items-center justify-center overflow-hidden transition-shadow ${
                       isSelected ? 'ring-1 ring-blue-500 shadow-2xl z-50' : 'hover:ring-1 hover:ring-blue-500/30'
                     }`}
                     style={{
                       left: Number(props.x) || 0,
                       top: Number(props.y) || 0,
                       width: Number(props.width) || 100,
                       height: Number(props.height) || 100,
                       backgroundColor: props.backgroundColor || 'transparent',
                       color: props.color || '#000',
                       fontSize: props.fontSize || '16px',
                       borderRadius: props.borderRadius || '0px',
                       zIndex: layer.order || 0,
                     }}
                   >
                     {/* Element Label (Visible when hovering or selected) */}
                     {isSelected && (
                        <div className="absolute -top-5 left-0 bg-blue-500 text-white text-[9px] px-1.5 py-0.5 rounded-t-sm whitespace-nowrap pointer-events-none">
                           {displayLayer.name}
                        </div>
                     )}

                     {layer.layer_type === 'text' && (
                       <div style={{ padding: props.padding || '0px' }}>
                         {displayLayer.name || 'Text Element'}
                       </div>
                     )}
                     {layer.layer_type === 'button' && (
                       <button 
                         className="w-full h-full font-bold pointer-events-none transition-colors"
                         style={{ 
                           backgroundColor: props.backgroundColor, 
                           color: props.color,
                           borderRadius: props.borderRadius
                         }}
                       >
                         {displayLayer.name || 'Button'}
                       </button>
                     )}
                     {layer.layer_type === 'card' && (
                       <CardBox className="w-full h-full pointer-events-none m-0 shadow-none border-none overflow-hidden">
                         <div className="p-4 h-full flex flex-col justify-center text-center">
                           <h4 className="font-bold text-lg mb-1">{displayLayer.name}</h4>
                           <p className="text-xs opacity-60">Visual component integration</p>
                         </div>
                       </CardBox>
                     )}
                     {layer.layer_type === 'calendar' && (
                       <div className="w-full h-full bg-gray-50 p-4 pointer-events-none flex flex-col overflow-hidden">
                          <div className="flex justify-between items-center mb-4 border-b pb-2">
                             <span className="font-bold text-gray-800 text-sm">Jan 2026</span>
                             <div className="flex space-x-1">
                                <div className="w-3 h-3 rounded bg-gray-200"></div>
                                <div className="w-3 h-3 rounded bg-gray-200"></div>
                             </div>
                          </div>
                          <div className="grid grid-cols-7 gap-1 flex-grow">
                             {Array.from({ length: 28 }).map((_, i) => (
                                <div key={i} className={`rounded border flex items-center justify-center text-[10px] ${i === 23 ? 'bg-blue-100 border-blue-300 text-blue-600 font-bold' : 'bg-white border-gray-100'}`}>
                                   {i + 1}
                                </div>
                             ))}
                          </div>
                       </div>
                     )}
                     {layer.layer_type === 'image' && (
                       <div className="w-full h-full bg-gray-200 flex flex-col items-center justify-center text-gray-400 border-2 border-dashed border-gray-300">
                          <BaseIcon path={mdiImageOutline} size={32} />
                       </div>
                     )}
                     {layer.layer_type === 'frame' && !props.backgroundColor && (
                       <div className="w-full h-full border-2 border-dashed border-gray-300"></div>
                     )}
                     
                     {isSelected && (
                       <div className="absolute -bottom-1 -right-1 w-2.5 h-2.5 bg-white border-2 border-blue-500 rounded-full cursor-nwse-resize z-50 shadow-sm"></div>
                     )}
                   </div>
                 );
               })}
             </div>
          </div>
        </div>

        {/* --- RIGHT SIDEBAR (Tabs: Style, Settings, Interactions) --- */}
        <div className="w-72 border-l border-white/5 bg-[#111111] flex flex-col">
          <div className="flex border-b border-white/5 px-2">
            {(['style', 'settings', 'interactions'] as const).map((tab) => (
              <button
                key={tab}
                onClick={() => setActiveTabRight(tab)}
                className={`px-4 py-3 text-[10px] font-bold uppercase tracking-wider transition-all border-b-2 ${
                  activeTabRight === tab ? 'text-white border-white' : 'text-gray-500 border-transparent hover:text-gray-300'
                }`}
              >
                {tab}
              </button>
            ))}
          </div>

          <div className="flex-grow overflow-y-auto">
            {!localLayer ? (
              <div className="flex flex-col items-center justify-center p-12 text-center h-full">
                <BaseIcon path={mdiCursorDefaultClickOutline} size={48} className="text-gray-800 mb-6" />
                <h3 className="text-white text-xs font-bold mb-2 uppercase tracking-widest">None Selected</h3>
                <p className="text-[10px] text-gray-600 leading-relaxed">
                  Select an element on the canvas to activate this panel
                </p>
              </div>
            ) : (
              <div className="p-4 space-y-6">
                {activeTabRight === 'style' && (
                   <>
                    <div>
                      <label className="text-[10px] font-bold text-gray-600 uppercase block mb-3 tracking-widest">Layout</label>
                      <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                        <div className="space-y-1">
                          <div className="flex justify-between items-center px-1">
                             <span className="text-[9px] text-gray-500 uppercase">X</span>
                          </div>
                          <input 
                            type="number"
                            value={localLayer.parsedProps.x || 0}
                            onChange={(e) => handlePropertyChange('x', Number(e.target.value))}
                            onBlur={handleBlur}
                            className="w-full bg-[#181818] border border-white/5 rounded px-2 py-1.5 text-[11px] outline-none focus:border-white/20 transition-colors"
                          />
                        </div>
                        <div className="space-y-1">
                          <div className="flex justify-between items-center px-1">
                             <span className="text-[9px] text-gray-500 uppercase">Y</span>
                          </div>
                          <input 
                            type="number"
                            value={localLayer.parsedProps.y || 0}
                            onChange={(e) => handlePropertyChange('y', Number(e.target.value))}
                            onBlur={handleBlur}
                            className="w-full bg-[#181818] border border-white/5 rounded px-2 py-1.5 text-[11px] outline-none focus:border-white/20 transition-colors"
                          />
                        </div>
                        <div className="space-y-1">
                          <div className="flex justify-between items-center px-1">
                             <span className="text-[9px] text-gray-500 uppercase">Width</span>
                          </div>
                          <input 
                            type="number"
                            value={localLayer.parsedProps.width || 0}
                            onChange={(e) => handlePropertyChange('width', Number(e.target.value))}
                            onBlur={handleBlur}
                            className="w-full bg-[#181818] border border-white/5 rounded px-2 py-1.5 text-[11px] outline-none focus:border-white/20 transition-colors"
                          />
                        </div>
                        <div className="space-y-1">
                          <div className="flex justify-between items-center px-1">
                             <span className="text-[9px] text-gray-500 uppercase">Height</span>
                          </div>
                          <input 
                            type="number"
                            value={localLayer.parsedProps.height || 0}
                            onChange={(e) => handlePropertyChange('height', Number(e.target.value))}
                            onBlur={handleBlur}
                            className="w-full bg-[#181818] border border-white/5 rounded px-2 py-1.5 text-[11px] outline-none focus:border-white/20 transition-colors"
                          />
                        </div>
                      </div>
                    </div>

                    <div className="pt-6 border-t border-white/5">
                      <label className="text-[10px] font-bold text-gray-600 uppercase block mb-3 tracking-widest">Fill & Stroke</label>
                      <div className="space-y-4">
                        <div className="flex items-center justify-between">
                          <span className="text-[11px] text-gray-400">Background</span>
                          <div className="flex items-center space-x-2 bg-[#181818] rounded px-2 py-1 border border-white/5">
                            <input 
                              type="color"
                              value={localLayer.parsedProps.backgroundColor || '#ffffff'}
                              onChange={(e) => handlePropertyChange('backgroundColor', e.target.value)}
                              onBlur={handleBlur}
                              className="w-4 h-4 bg-transparent border-none cursor-pointer"
                            />
                            <span className="text-[10px] font-mono text-gray-500 uppercase">
                              {localLayer.parsedProps.backgroundColor?.toUpperCase() || '#FFFFFF'}
                            </span>
                          </div>
                        </div>
                        <div className="flex items-center justify-between">
                          <span className="text-[11px] text-gray-400">Text Color</span>
                          <div className="flex items-center space-x-2 bg-[#181818] rounded px-2 py-1 border border-white/5">
                            <input 
                              type="color"
                              value={localLayer.parsedProps.color || '#000000'}
                              onChange={(e) => handlePropertyChange('color', e.target.value)}
                              onBlur={handleBlur}
                              className="w-4 h-4 bg-transparent border-none cursor-pointer"
                            />
                            <span className="text-[10px] font-mono text-gray-500 uppercase">
                              {localLayer.parsedProps.color?.toUpperCase() || '#000000'}
                            </span>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="pt-6 border-t border-white/5">
                      <label className="text-[10px] font-bold text-gray-600 uppercase block mb-3 tracking-widest">Radius</label>
                      <input 
                        type="text" 
                        value={localLayer.parsedProps.borderRadius || '0px'} 
                        onChange={(e) => handlePropertyChange('borderRadius', e.target.value)}
                        onBlur={handleBlur}
                        className="w-full bg-[#181818] border border-white/5 rounded px-2 py-1.5 text-[11px] outline-none focus:border-white/20"
                      />
                    </div>
                   </>
                )}

                {activeTabRight === 'settings' && (
                  <div className="space-y-4">
                    <div>
                      <label className="text-[10px] font-bold text-gray-600 uppercase block mb-2 tracking-wider">Layer Name</label>
                      <input 
                         type="text" 
                         value={localLayer.name || ''} 
                         onChange={(e) => handlePropertyChange('name', e.target.value, false)}
                         onBlur={handleBlur}
                         className="w-full bg-[#181818] border border-white/5 rounded px-2 py-1.5 text-xs outline-none focus:border-white/20"
                      />
                    </div>
                    <div className="pt-4 space-y-3">
                       <button 
                         onClick={() => removeLayer(localLayer.id)}
                         className="w-full py-2 bg-red-500/10 hover:bg-red-500/20 text-red-500 rounded text-[10px] font-bold transition-colors uppercase tracking-widest"
                       >
                         Delete Element
                       </button>
                    </div>
                  </div>
                )}

                {activeTabRight === 'interactions' && (
                   <div className="flex flex-col items-center justify-center py-12 text-center">
                      <BaseIcon path={mdiFlashOutline} size={32} className="text-gray-800 mb-4" />
                      <p className="text-[10px] text-gray-600">No interactions defined</p>
                   </div>
                )}
              </div>
            )}
          </div>

          <div className="p-4 border-t border-white/5 bg-black/20 flex justify-between items-center">
             <span className="text-[10px] text-gray-600 font-mono uppercase tracking-tighter">Project v1.0.4</span>
             <BaseIcon path={mdiHelpCircleOutline} size={14} className="text-gray-700 cursor-pointer" />
          </div>
        </div>
      </div>
    </div>
  );
};

export default PageBuilder;