/**
 * VisualEditor - Hostinger-Style Website Builder
 */

import React, { useState, useRef, useCallback } from 'react';
import { Canvas } from './Canvas';
import { StylePanel } from './StylePanel';
import { useVisualEditor } from '../hooks/useVisualEditor';

// Section templates for drag and drop
const SECTION_TEMPLATES = {
  hero: `<section style="padding: 80px 60px; background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); text-align: center;">
    <h1 style="font-size: 3.5rem; font-weight: 800; color: #fff; margin: 0 0 20px; letter-spacing: -1px;">Build Your Dream Website</h1>
    <p style="font-size: 1.25rem; color: rgba(255,255,255,0.8); margin: 0 0 32px; max-width: 600px; margin-left: auto; margin-right: auto;">Create stunning websites in minutes with our intuitive drag-and-drop builder. No coding required.</p>
    <button style="background: #6366f1; color: white; border: none; padding: 16px 40px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">Get Started Free</button>
  </section>`,
  
  features: `<section style="padding: 80px 60px; background: #ffffff;">
    <h2 style="font-size: 2.5rem; font-weight: 700; color: #111; text-align: center; margin: 0 0 16px;">Why Choose Us</h2>
    <p style="text-align: center; color: #666; margin: 0 0 48px; font-size: 1.1rem;">Everything you need to build a professional website</p>
    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 32px; max-width: 1100px; margin: 0 auto;">
      <div style="padding: 32px; background: #f8fafc; border-radius: 12px; text-align: center;">
        <div style="width: 56px; height: 56px; background: #ede9fe; border-radius: 12px; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; font-size: 24px;">⚡</div>
        <h3 style="font-size: 1.25rem; font-weight: 600; color: #111; margin: 0 0 12px;">Lightning Fast</h3>
        <p style="color: #666; font-size: 0.95rem; margin: 0; line-height: 1.6;">Optimized for speed with automatic performance enhancements.</p>
      </div>
      <div style="padding: 32px; background: #f8fafc; border-radius: 12px; text-align: center;">
        <div style="width: 56px; height: 56px; background: #dbeafe; border-radius: 12px; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; font-size: 24px;">🎨</div>
        <h3 style="font-size: 1.25rem; font-weight: 600; color: #111; margin: 0 0 12px;">Beautiful Design</h3>
        <p style="color: #666; font-size: 0.95rem; margin: 0; line-height: 1.6;">Professionally designed templates you can customize.</p>
      </div>
      <div style="padding: 32px; background: #f8fafc; border-radius: 12px; text-align: center;">
        <div style="width: 56px; height: 56px; background: #dcfce7; border-radius: 12px; margin: 0 auto 20px; display: flex; align-items: center; justify-content: center; font-size: 24px;">🔒</div>
        <h3 style="font-size: 1.25rem; font-weight: 600; color: #111; margin: 0 0 12px;">Secure Hosting</h3>
        <p style="color: #666; font-size: 0.95rem; margin: 0; line-height: 1.6;">Enterprise-grade security with free SSL certificates.</p>
      </div>
    </div>
  </section>`,
  
  testimonials: `<section style="padding: 80px 60px; background: #f8fafc;">
    <h2 style="font-size: 2.5rem; font-weight: 700; color: #111; text-align: center; margin: 0 0 48px;">What Our Users Say</h2>
    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 32px; max-width: 900px; margin: 0 auto;">
      <div style="background: white; padding: 32px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08);">
        <p style="color: #444; font-size: 1rem; line-height: 1.7; margin: 0 0 24px;">"This builder transformed how we create websites. What used to take weeks now takes hours. The drag-and-drop interface is incredibly intuitive."</p>
        <div style="display: flex; align-items: center; gap: 12px;">
          <div style="width: 48px; height: 48px; background: #e0e7ff; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; color: #4f46e5;">SJ</div>
          <div><div style="font-weight: 600; color: #111;">Sarah Johnson</div><div style="color: #888; font-size: 0.875rem;">Marketing Director</div></div>
        </div>
      </div>
      <div style="background: white; padding: 32px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08);">
        <p style="color: #444; font-size: 1rem; line-height: 1.7; margin: 0 0 24px;">"Finally, a website builder that doesn't require a computer science degree. I built our company site in a weekend and it looks amazing."</p>
        <div style="display: flex; align-items: center; gap: 12px;">
          <div style="width: 48px; height: 48px; background: #fce7f3; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: 600; color: #db2777;">MR</div>
          <div><div style="font-weight: 600; color: #111;">Mike Reynolds</div><div style="color: #888; font-size: 0.875rem;">Small Business Owner</div></div>
        </div>
      </div>
    </div>
  </section>`,
  
  cta: `<section style="padding: 80px 60px; background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%); text-align: center;">
    <h2 style="font-size: 2.5rem; font-weight: 700; color: white; margin: 0 0 16px;">Ready to Get Started?</h2>
    <p style="color: rgba(255,255,255,0.9); font-size: 1.1rem; margin: 0 0 32px;">Join thousands of happy customers building amazing websites.</p>
    <button style="background: white; color: #6366f1; border: none; padding: 16px 40px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer; margin-right: 12px;">Start Free Trial</button>
    <button style="background: transparent; color: white; border: 2px solid white; padding: 14px 32px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">View Pricing</button>
  </section>`,
  
  footer: `<footer style="padding: 48px 60px; background: #111; color: white;">
    <div style="display: grid; grid-template-columns: 2fr 1fr 1fr 1fr; gap: 48px; max-width: 1100px; margin: 0 auto;">
      <div>
        <div style="font-size: 1.5rem; font-weight: 700; margin-bottom: 16px;">WebBuilder</div>
        <p style="color: #888; font-size: 0.95rem; line-height: 1.6; margin: 0;">Create beautiful websites without code. Trusted by over 10,000 businesses worldwide.</p>
      </div>
      <div>
        <div style="font-weight: 600; margin-bottom: 16px;">Product</div>
        <div style="display: flex; flex-direction: column; gap: 10px;">
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Features</a>
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Templates</a>
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Pricing</a>
        </div>
      </div>
      <div>
        <div style="font-weight: 600; margin-bottom: 16px;">Company</div>
        <div style="display: flex; flex-direction: column; gap: 10px;">
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">About</a>
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Blog</a>
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Careers</a>
        </div>
      </div>
      <div>
        <div style="font-weight: 600; margin-bottom: 16px;">Support</div>
        <div style="display: flex; flex-direction: column; gap: 10px;">
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Help Center</a>
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Contact</a>
          <a href="#" style="color: #888; text-decoration: none; font-size: 0.9rem;">Status</a>
        </div>
      </div>
    </div>
  </footer>`,
  
  gallery: `<section style="padding: 80px 60px; background: white;">
    <h2 style="font-size: 2.5rem; font-weight: 700; color: #111; text-align: center; margin: 0 0 48px;">Our Work</h2>
    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; max-width: 1100px; margin: 0 auto;">
      <img src="https://images.unsplash.com/photo-1460925895917-afdab827c52f?w=400&h=300&fit=crop" style="width: 100%; height: 220px; object-fit: cover; border-radius: 12px;" alt="Project 1"/>
      <img src="https://images.unsplash.com/photo-1551434678-e076c223a692?w=400&h=300&fit=crop" style="width: 100%; height: 220px; object-fit: cover; border-radius: 12px;" alt="Project 2"/>
      <img src="https://images.unsplash.com/photo-1522071820081-009f0129c71c?w=400&h=300&fit=crop" style="width: 100%; height: 220px; object-fit: cover; border-radius: 12px;" alt="Project 3"/>
    </div>
  </section>`,
  
  pricing: `<section style="padding: 80px 60px; background: #f8fafc;">
    <h2 style="font-size: 2.5rem; font-weight: 700; color: #111; text-align: center; margin: 0 0 16px;">Simple Pricing</h2>
    <p style="text-align: center; color: #666; margin: 0 0 48px; font-size: 1.1rem;">Choose the plan that's right for you</p>
    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; max-width: 1000px; margin: 0 auto;">
      <div style="background: white; padding: 40px 32px; border-radius: 16px; text-align: center; border: 2px solid #e5e7eb;">
        <div style="font-size: 1.25rem; font-weight: 600; color: #111; margin-bottom: 8px;">Starter</div>
        <div style="font-size: 3rem; font-weight: 800; color: #111; margin-bottom: 24px;">$9<span style="font-size: 1rem; color: #888; font-weight: 400;">/mo</span></div>
        <ul style="list-style: none; padding: 0; margin: 0 0 32px; text-align: left;">
          <li style="padding: 10px 0; color: #666; border-bottom: 1px solid #f3f4f6;">✓ 1 Website</li>
          <li style="padding: 10px 0; color: #666; border-bottom: 1px solid #f3f4f6;">✓ 10GB Storage</li>
          <li style="padding: 10px 0; color: #666;">✓ Free SSL</li>
        </ul>
        <button style="width: 100%; background: #f3f4f6; color: #111; border: none; padding: 14px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">Get Started</button>
      </div>
      <div style="background: white; padding: 40px 32px; border-radius: 16px; text-align: center; border: 2px solid #6366f1; transform: scale(1.05); box-shadow: 0 20px 40px rgba(99,102,241,0.15);">
        <div style="background: #6366f1; color: white; font-size: 0.75rem; font-weight: 600; padding: 4px 12px; border-radius: 20px; display: inline-block; margin-bottom: 16px;">POPULAR</div>
        <div style="font-size: 1.25rem; font-weight: 600; color: #111; margin-bottom: 8px;">Professional</div>
        <div style="font-size: 3rem; font-weight: 800; color: #111; margin-bottom: 24px;">$29<span style="font-size: 1rem; color: #888; font-weight: 400;">/mo</span></div>
        <ul style="list-style: none; padding: 0; margin: 0 0 32px; text-align: left;">
          <li style="padding: 10px 0; color: #666; border-bottom: 1px solid #f3f4f6;">✓ 10 Websites</li>
          <li style="padding: 10px 0; color: #666; border-bottom: 1px solid #f3f4f6;">✓ 100GB Storage</li>
          <li style="padding: 10px 0; color: #666;">✓ Priority Support</li>
        </ul>
        <button style="width: 100%; background: #6366f1; color: white; border: none; padding: 14px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">Get Started</button>
      </div>
      <div style="background: white; padding: 40px 32px; border-radius: 16px; text-align: center; border: 2px solid #e5e7eb;">
        <div style="font-size: 1.25rem; font-weight: 600; color: #111; margin-bottom: 8px;">Enterprise</div>
        <div style="font-size: 3rem; font-weight: 800; color: #111; margin-bottom: 24px;">$99<span style="font-size: 1rem; color: #888; font-weight: 400;">/mo</span></div>
        <ul style="list-style: none; padding: 0; margin: 0 0 32px; text-align: left;">
          <li style="padding: 10px 0; color: #666; border-bottom: 1px solid #f3f4f6;">✓ Unlimited Sites</li>
          <li style="padding: 10px 0; color: #666; border-bottom: 1px solid #f3f4f6;">✓ 1TB Storage</li>
          <li style="padding: 10px 0; color: #666;">✓ Dedicated Support</li>
        </ul>
        <button style="width: 100%; background: #f3f4f6; color: #111; border: none; padding: 14px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">Contact Sales</button>
      </div>
    </div>
  </section>`
};

// Element templates
const ELEMENT_TEMPLATES = {
  heading: '<h2 style="font-size: 2rem; font-weight: 700; color: #111; margin: 0 0 16px;">Your Heading Here</h2>',
  paragraph: '<p style="font-size: 1rem; color: #666; line-height: 1.7; margin: 0 0 16px;">Add your text here. Click to edit this paragraph and make it your own.</p>',
  button: '<button style="background: #6366f1; color: white; border: none; padding: 14px 32px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">Click Me</button>',
  image: '<img src="https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=800&h=400&fit=crop" style="width: 100%; max-width: 600px; height: auto; border-radius: 12px;" alt="Image"/>',
  divider: '<hr style="border: none; height: 1px; background: #e5e7eb; margin: 32px 0;"/>',
  spacer: '<div style="height: 48px;"></div>',
  video: '<div style="background: #111; border-radius: 12px; padding: 60px; text-align: center; color: #888;">Video Placeholder</div>',
  form: `<form style="background: #f8fafc; padding: 32px; border-radius: 12px; max-width: 400px;">
    <input type="text" placeholder="Your Name" style="width: 100%; padding: 12px 16px; border: 1px solid #e5e7eb; border-radius: 8px; margin-bottom: 16px; font-size: 1rem;"/>
    <input type="email" placeholder="Your Email" style="width: 100%; padding: 12px 16px; border: 1px solid #e5e7eb; border-radius: 8px; margin-bottom: 16px; font-size: 1rem;"/>
    <button type="submit" style="width: 100%; background: #6366f1; color: white; border: none; padding: 14px; font-size: 1rem; font-weight: 600; border-radius: 8px; cursor: pointer;">Submit</button>
  </form>`
};

type DeviceMode = 'desktop' | 'tablet' | 'mobile';
type LeftPanelTab = 'add' | 'pages' | 'theme';

// SVG Icons
const Icons = {
  desktop: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="3" width="20" height="14" rx="2"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="17" x2="12" y2="21"/></svg>,
  tablet: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="4" y="2" width="16" height="20" rx="2"/><line x1="12" y1="18" x2="12" y2="18"/></svg>,
  mobile: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="5" y="2" width="14" height="20" rx="2"/><line x1="12" y1="18" x2="12" y2="18"/></svg>,
  undo: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 7v6h6"/><path d="M21 17a9 9 0 00-9-9 9 9 0 00-6.36 2.64L3 13"/></svg>,
  redo: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 7v6h-6"/><path d="M3 17a9 9 0 019-9 9 9 0 016.36 2.64L21 13"/></svg>,
  plus: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>,
  layers: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="12,2 2,7 12,12 22,7"/><polyline points="2,17 12,22 22,17"/><polyline points="2,12 12,17 22,12"/></svg>,
  pages: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14,2 14,8 20,8"/></svg>,
  theme: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="5"/><path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/></svg>,
  preview: <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>,
  chevronDown: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="6,9 12,15 18,9"/></svg>,
  chevronRight: <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="9,6 15,12 9,18"/></svg>,
  drag: <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="5" r="1.5"/><circle cx="15" cy="5" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/></svg>,
  text: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="4,7 4,4 20,4 20,7"/><line x1="12" y1="4" x2="12" y2="20"/><line x1="8" y1="20" x2="16" y2="20"/></svg>,
  image: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21,15 16,10 5,21"/></svg>,
  button: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="8" width="18" height="8" rx="2"/></svg>,
  video: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polygon points="5,3 19,12 5,21"/></svg>,
  form: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="7" y1="8" x2="17" y2="8"/><line x1="7" y1="12" x2="17" y2="12"/><line x1="7" y1="16" x2="12" y2="16"/></svg>,
  divider: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="3" y1="12" x2="21" y2="12"/></svg>,
  spacer: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><line x1="12" y1="3" x2="12" y2="21"/><polyline points="8,7 12,3 16,7"/><polyline points="8,17 12,21 16,17"/></svg>
};

export const VisualEditor: React.FC = () => {
  const {
    selectedElement,
    showSpacing,
    showDimensions,
    selectElement,
    deselectElement,
    applyStyle,
    canUndo,
    canRedo,
    undo,
    redo
  } = useVisualEditor();
  
  const [deviceMode, setDeviceMode] = useState<DeviceMode>('desktop');
  const [leftTab, setLeftTab] = useState<LeftPanelTab>('add');
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set(['sections', 'elements']));
  const [zoom, setZoom] = useState(100);
  const [pageName, setPageName] = useState('Home');
  const [draggedItem, setDraggedItem] = useState<string | null>(null);
  const canvasRef = useRef<{ addElement: (html: string) => void }>(null);
  
  const toggleSection = (section: string) => {
    setExpandedSections(prev => {
      const next = new Set(prev);
      if (next.has(section)) next.delete(section);
      else next.add(section);
      return next;
    });
  };
  
  const handleDragStart = (e: React.DragEvent, type: string, template: string) => {
    setDraggedItem(type);
    e.dataTransfer.setData('text/html', template);
    e.dataTransfer.effectAllowed = 'copy';
  };
  
  const handleDragEnd = () => {
    setDraggedItem(null);
  };

  // Get canvas width based on device mode
  const getCanvasWidth = () => {
    switch (deviceMode) {
      case 'tablet': return 768;
      case 'mobile': return 375;
      default: return '100%';
    }
  };

  return (
    <div style={styles.container}>
      {/* ===== TOP HEADER ===== */}
      <header style={styles.header}>
        <div style={styles.headerLeft}>
          <div style={styles.logo}>
            <div style={styles.logoIcon}>W</div>
            <span>WebBuilder</span>
          </div>
          <div style={styles.dividerV} />
          <input 
            type="text" 
            value={pageName} 
            onChange={(e) => setPageName(e.target.value)}
            style={styles.pageNameInput}
          />
        </div>
        
        <div style={styles.headerCenter}>
          <div style={styles.deviceToggle}>
            {(['desktop', 'tablet', 'mobile'] as DeviceMode[]).map(mode => (
              <button
                key={mode}
                style={{
                  ...styles.deviceBtn,
                  ...(deviceMode === mode ? styles.deviceBtnActive : {})
                }}
                onClick={() => setDeviceMode(mode)}
                title={mode.charAt(0).toUpperCase() + mode.slice(1)}
              >
                {Icons[mode]}
              </button>
            ))}
          </div>
          <div style={styles.zoomControl}>
            <button style={styles.zoomBtn} onClick={() => setZoom(z => Math.max(50, z - 10))}>−</button>
            <span style={styles.zoomValue}>{zoom}%</span>
            <button style={styles.zoomBtn} onClick={() => setZoom(z => Math.min(150, z + 10))}>+</button>
          </div>
        </div>
        
        <div style={styles.headerRight}>
          <button 
            style={{...styles.headerBtn, opacity: canUndo ? 1 : 0.4}}
            onClick={undo}
            disabled={!canUndo}
            title="Undo"
          >
            {Icons.undo}
          </button>
          <button 
            style={{...styles.headerBtn, opacity: canRedo ? 1 : 0.4}}
            onClick={redo}
            disabled={!canRedo}
            title="Redo"
          >
            {Icons.redo}
          </button>
          <div style={styles.dividerV} />
          <button style={styles.headerBtn}>
            {Icons.preview}
            <span>Preview</span>
          </button>
          <button style={styles.publishBtn}>
            Publish
          </button>
        </div>
      </header>

      {/* ===== MAIN CONTENT ===== */}
      <div style={styles.main}>
        {/* ===== LEFT PANEL ===== */}
        <aside style={styles.leftPanel}>
          <div style={styles.leftTabs}>
            <button 
              style={{...styles.leftTab, ...(leftTab === 'add' ? styles.leftTabActive : {})}}
              onClick={() => setLeftTab('add')}
            >
              {Icons.plus}
              <span>Add</span>
            </button>
            <button 
              style={{...styles.leftTab, ...(leftTab === 'pages' ? styles.leftTabActive : {})}}
              onClick={() => setLeftTab('pages')}
            >
              {Icons.pages}
              <span>Pages</span>
            </button>
            <button 
              style={{...styles.leftTab, ...(leftTab === 'theme' ? styles.leftTabActive : {})}}
              onClick={() => setLeftTab('theme')}
            >
              {Icons.theme}
              <span>Theme</span>
            </button>
          </div>
          
          <div style={styles.leftContent}>
            {leftTab === 'add' && (
              <>
                {/* Sections */}
                <div style={styles.accordion}>
                  <button 
                    style={styles.accordionHeader}
                    onClick={() => toggleSection('sections')}
                  >
                    <span>Sections</span>
                    {expandedSections.has('sections') ? Icons.chevronDown : Icons.chevronRight}
                  </button>
                  {expandedSections.has('sections') && (
                    <div style={styles.accordionBody}>
                      <div style={styles.sectionGrid}>
                        {Object.entries(SECTION_TEMPLATES).map(([key, template]) => (
                          <div
                            key={key}
                            draggable
                            onDragStart={(e) => handleDragStart(e, key, template)}
                            onDragEnd={handleDragEnd}
                            style={{
                              ...styles.sectionItem,
                              ...(draggedItem === key ? styles.sectionItemDragging : {})
                            }}
                          >
                            <div style={styles.sectionThumb}>
                              {key === 'hero' && '🏠'}
                              {key === 'features' && '⭐'}
                              {key === 'testimonials' && '💬'}
                              {key === 'cta' && '🎯'}
                              {key === 'footer' && '📍'}
                              {key === 'gallery' && '🖼️'}
                              {key === 'pricing' && '💰'}
                            </div>
                            <span style={styles.sectionLabel}>{key.charAt(0).toUpperCase() + key.slice(1)}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
                
                {/* Elements */}
                <div style={styles.accordion}>
                  <button 
                    style={styles.accordionHeader}
                    onClick={() => toggleSection('elements')}
                  >
                    <span>Elements</span>
                    {expandedSections.has('elements') ? Icons.chevronDown : Icons.chevronRight}
                  </button>
                  {expandedSections.has('elements') && (
                    <div style={styles.accordionBody}>
                      {Object.entries(ELEMENT_TEMPLATES).map(([key, template]) => (
                        <div
                          key={key}
                          draggable
                          onDragStart={(e) => handleDragStart(e, key, template)}
                          onDragEnd={handleDragEnd}
                          style={{
                            ...styles.elementItem,
                            ...(draggedItem === key ? styles.elementItemDragging : {})
                          }}
                        >
                          <span style={styles.elementIcon}>
                            {Icons[key as keyof typeof Icons] || Icons.text}
                          </span>
                          <span>{key.charAt(0).toUpperCase() + key.slice(1)}</span>
                          <span style={styles.dragHandle}>{Icons.drag}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </>
            )}
            
            {leftTab === 'pages' && (
              <div style={styles.pagesList}>
                <div style={styles.pageItem}>
                  <span>🏠</span>
                  <span>Home</span>
                </div>
                <div style={{...styles.pageItem, opacity: 0.6}}>
                  <span>📄</span>
                  <span>About</span>
                </div>
                <div style={{...styles.pageItem, opacity: 0.6}}>
                  <span>📞</span>
                  <span>Contact</span>
                </div>
                <button style={styles.addPageBtn}>
                  {Icons.plus}
                  <span>Add Page</span>
                </button>
              </div>
            )}
            
            {leftTab === 'theme' && (
              <div style={styles.themePanel}>
                <div style={styles.themeSection}>
                  <div style={styles.themeSectionTitle}>Colors</div>
                  <div style={styles.colorGrid}>
                    <div style={{...styles.colorSwatch, background: '#6366f1'}} title="Primary" />
                    <div style={{...styles.colorSwatch, background: '#111827'}} title="Text" />
                    <div style={{...styles.colorSwatch, background: '#ffffff'}} title="Background" />
                    <div style={{...styles.colorSwatch, background: '#f3f4f6'}} title="Secondary" />
                  </div>
                </div>
                <div style={styles.themeSection}>
                  <div style={styles.themeSectionTitle}>Fonts</div>
                  <select style={styles.themeSelect}>
                    <option>Inter</option>
                    <option>Poppins</option>
                    <option>Roboto</option>
                  </select>
                </div>
              </div>
            )}
          </div>
        </aside>

        {/* ===== CANVAS AREA ===== */}
        <div style={styles.canvasWrapper}>
          <div style={{
            ...styles.canvasContainer,
            width: getCanvasWidth(),
            transform: `scale(${zoom / 100})`,
            transformOrigin: 'top center'
          }}>
            <Canvas
              ref={canvasRef}
              selectedElement={selectedElement}
              onElementSelect={selectElement}
              showSpacing={showSpacing}
              showDimensions={showDimensions}
              deviceMode={deviceMode}
            />
          </div>
        </div>

        {/* ===== RIGHT PANEL (Style Panel) ===== */}
        <StylePanel
          selectedElement={selectedElement}
          onStyleChange={applyStyle}
          onDeselect={deselectElement}
        />
      </div>
    </div>
  );
};

// ===== STYLES =====
const styles: { [key: string]: React.CSSProperties } = {
  container: {
    display: 'flex',
    flexDirection: 'column',
    height: '100vh',
    width: '100vw',
    overflow: 'hidden',
    background: '#0c0c0c',
    fontFamily: "'Inter', -apple-system, BlinkMacSystemFont, sans-serif"
  },
  
  // Header
  header: {
    height: '56px',
    background: '#161616',
    borderBottom: '1px solid #2a2a2a',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'space-between',
    padding: '0 16px',
    flexShrink: 0
  },
  headerLeft: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px'
  },
  logo: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    color: '#fff',
    fontWeight: '600',
    fontSize: '15px'
  },
  logoIcon: {
    width: '28px',
    height: '28px',
    background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
    borderRadius: '8px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    fontWeight: '700',
    fontSize: '14px'
  },
  dividerV: {
    width: '1px',
    height: '24px',
    background: '#333'
  },
  pageNameInput: {
    background: '#222',
    border: '1px solid #333',
    borderRadius: '6px',
    padding: '8px 12px',
    color: '#fff',
    fontSize: '13px',
    width: '140px',
    outline: 'none'
  },
  headerCenter: {
    display: 'flex',
    alignItems: 'center',
    gap: '16px'
  },
  deviceToggle: {
    display: 'flex',
    background: '#222',
    borderRadius: '8px',
    padding: '4px'
  },
  deviceBtn: {
    background: 'none',
    border: 'none',
    color: '#666',
    padding: '8px 12px',
    borderRadius: '6px',
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    transition: 'all 0.15s'
  },
  deviceBtnActive: {
    background: '#6366f1',
    color: '#fff'
  },
  zoomControl: {
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
    background: '#222',
    borderRadius: '6px',
    padding: '4px'
  },
  zoomBtn: {
    background: 'none',
    border: 'none',
    color: '#888',
    width: '28px',
    height: '28px',
    borderRadius: '4px',
    cursor: 'pointer',
    fontSize: '16px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  },
  zoomValue: {
    color: '#888',
    fontSize: '12px',
    minWidth: '40px',
    textAlign: 'center'
  },
  headerRight: {
    display: 'flex',
    alignItems: 'center',
    gap: '8px'
  },
  headerBtn: {
    background: '#222',
    border: '1px solid #333',
    color: '#aaa',
    padding: '8px 12px',
    borderRadius: '6px',
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    gap: '6px',
    fontSize: '13px',
    transition: 'all 0.15s'
  },
  publishBtn: {
    background: 'linear-gradient(135deg, #6366f1, #8b5cf6)',
    border: 'none',
    color: '#fff',
    padding: '10px 20px',
    borderRadius: '6px',
    cursor: 'pointer',
    fontWeight: '600',
    fontSize: '13px'
  },
  
  // Main
  main: {
    display: 'flex',
    flex: 1,
    overflow: 'hidden'
  },
  
  // Left Panel
  leftPanel: {
    width: '280px',
    background: '#161616',
    borderRight: '1px solid #2a2a2a',
    display: 'flex',
    flexDirection: 'column',
    flexShrink: 0
  },
  leftTabs: {
    display: 'flex',
    borderBottom: '1px solid #2a2a2a'
  },
  leftTab: {
    flex: 1,
    background: 'none',
    border: 'none',
    color: '#666',
    padding: '14px 8px',
    cursor: 'pointer',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: '4px',
    fontSize: '11px',
    transition: 'all 0.15s'
  },
  leftTabActive: {
    color: '#fff',
    background: '#1e1e1e'
  },
  leftContent: {
    flex: 1,
    overflowY: 'auto',
    padding: '12px'
  },
  
  // Accordion
  accordion: {
    marginBottom: '8px'
  },
  accordionHeader: {
    width: '100%',
    background: '#1e1e1e',
    border: 'none',
    borderRadius: '8px',
    padding: '12px 14px',
    color: '#fff',
    fontSize: '13px',
    fontWeight: '500',
    cursor: 'pointer',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  accordionBody: {
    padding: '12px 0'
  },
  
  // Section Grid
  sectionGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(2, 1fr)',
    gap: '8px'
  },
  sectionItem: {
    background: '#1e1e1e',
    borderRadius: '8px',
    padding: '16px 8px',
    textAlign: 'center',
    cursor: 'grab',
    border: '1px solid transparent',
    transition: 'all 0.15s'
  },
  sectionItemDragging: {
    opacity: 0.5,
    border: '1px solid #6366f1'
  },
  sectionThumb: {
    fontSize: '24px',
    marginBottom: '8px'
  },
  sectionLabel: {
    color: '#888',
    fontSize: '11px'
  },
  
  // Element Item
  elementItem: {
    display: 'flex',
    alignItems: 'center',
    gap: '12px',
    padding: '12px',
    background: '#1e1e1e',
    borderRadius: '8px',
    marginBottom: '6px',
    cursor: 'grab',
    color: '#aaa',
    fontSize: '13px',
    border: '1px solid transparent',
    transition: 'all 0.15s'
  },
  elementItemDragging: {
    opacity: 0.5,
    border: '1px solid #6366f1'
  },
  elementIcon: {
    color: '#666'
  },
  dragHandle: {
    marginLeft: 'auto',
    color: '#444'
  },
  
  // Pages
  pagesList: {
    display: 'flex',
    flexDirection: 'column',
    gap: '4px'
  },
  pageItem: {
    display: 'flex',
    alignItems: 'center',
    gap: '10px',
    padding: '12px',
    background: '#1e1e1e',
    borderRadius: '8px',
    color: '#aaa',
    fontSize: '13px',
    cursor: 'pointer'
  },
  addPageBtn: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: '8px',
    padding: '12px',
    background: 'none',
    border: '1px dashed #333',
    borderRadius: '8px',
    color: '#666',
    fontSize: '13px',
    cursor: 'pointer',
    marginTop: '8px'
  },
  
  // Theme
  themePanel: {
    display: 'flex',
    flexDirection: 'column',
    gap: '20px'
  },
  themeSection: {},
  themeSectionTitle: {
    color: '#888',
    fontSize: '11px',
    fontWeight: '600',
    textTransform: 'uppercase',
    letterSpacing: '0.5px',
    marginBottom: '12px'
  },
  colorGrid: {
    display: 'grid',
    gridTemplateColumns: 'repeat(4, 1fr)',
    gap: '8px'
  },
  colorSwatch: {
    aspectRatio: '1',
    borderRadius: '8px',
    cursor: 'pointer',
    border: '2px solid transparent'
  },
  themeSelect: {
    width: '100%',
    background: '#1e1e1e',
    border: '1px solid #333',
    borderRadius: '6px',
    padding: '10px 12px',
    color: '#fff',
    fontSize: '13px',
    cursor: 'pointer'
  },
  
  // Canvas
  canvasWrapper: {
    flex: 1,
    background: '#0c0c0c',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'flex-start',
    overflow: 'auto',
    padding: '24px'
  },
  canvasContainer: {
    background: '#fff',
    borderRadius: '8px',
    overflow: 'hidden',
    boxShadow: '0 0 0 1px rgba(255,255,255,0.1), 0 30px 100px rgba(0,0,0,0.5)',
    minHeight: '100%'
  }
};

export default VisualEditor;
