import { useEffect, useRef, useState } from 'react'
import grapesjs from 'grapesjs'
import 'grapesjs/dist/css/grapes.min.css'
import newsletter from 'grapesjs-preset-newsletter'
import {
  Plus,
  Palette,
  Monitor,
  Smartphone,
  Tablet,
  Layers,
  Image as ImageIcon,
  Save,
  Loader2,
  Undo2,
  Redo2,
  Maximize,
  Eye,
  Trash2,
  PanelLeftClose,
  PanelLeftOpen,
  ArrowLeft,
  Search,
  Layout,
  Mail,
  Code
} from 'lucide-react'
import { GhostButton, AdminButton, SecondaryButton, SettingInput } from '../ui/settings-ui'
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '../ui/tooltip'
import { registerPremiumBlocks } from './EditorBlocks'

interface LocalBlock {
  get: (key: string) => unknown;
}

interface GrapesEditorProps {
  initialContentJson?: string;
  initialContentHtml?: string;
  onSave: (json: string, html: string) => void;
  saving?: boolean;
  height?: string;
  templateName?: string;
  onNameChange?: (name: string) => void;
  showNameInput?: boolean;
  onBack?: () => void;
  onSendTest?: (html: string, email: string) => void;
  sendingTest?: boolean;
}

export default function GrapesEditor({
  initialContentJson,
  initialContentHtml,
  onSave,
  saving = false,
  height = 'calc(100vh - 180px)',
  templateName: initialTemplateName = '',
  onNameChange,
  showNameInput = false,
  onBack,
  onSendTest,
  sendingTest = false
}: GrapesEditorProps) {
  const [editor, setEditor] = useState<import('grapesjs').Editor | null>(null)
  const gjsContainerRef = useRef<HTMLDivElement>(null)
  const mainWrapperRef = useRef<HTMLDivElement>(null)
  const [activePanel, setActivePanel] = useState('blocks')
  const [currentDevice, setCurrentDevice] = useState('Desktop')
  const [sidebarOpen, setSidebarOpen] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [templateName, setTemplateName] = useState(initialTemplateName)
  const [testEmail, setTestEmail] = useState('')
  const [blockCounts, setBlockCounts] = useState({ elements: 0, templates: 0 })

  useEffect(() => {
    if (!gjsContainerRef.current) return

    const gjs = grapesjs.init({
      container: gjsContainerRef.current,
      fromElement: false,
      height: '100%',
      width: 'auto',
      storageManager: false,
      plugins: [newsletter],
      pluginsOpts: {
        [newsletter as unknown as string]: {}
      },
      blockManager: { appendTo: '#gjs-blocks' },
      layerManager: { appendTo: '#gjs-layers' },
      selectorManager: { appendTo: '#gjs-styles' },
      styleManager: { appendTo: '#gjs-styles' },
      traitManager: { appendTo: '#gjs-styles' },
      panels: { defaults: [] },
      deviceManager: {
        devices: [
          { name: 'Desktop', width: '' },
          { name: 'Tablet', width: '768px', widthMedia: '768px' },
          { name: 'Mobile', width: '320px', widthMedia: '480px' }
        ]
      },
      canvas: {
        styles: [
          'https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap'
        ]
      },
      log: []
    })

    registerPremiumBlocks(gjs)

    if (initialContentJson) {
      try {
        const projectData = JSON.parse(initialContentJson);
        if (projectData && (projectData.pages || projectData.styles || projectData.assets)) {
          gjs.loadProjectData(projectData);
        } else {
          gjs.setComponents(projectData);
        }
      } catch {
        console.error('Failed to parse initial JSON');
      }
    } else if (initialContentHtml) {
      gjs.setComponents(initialContentHtml);
    }

    setEditor(gjs)

    gjs.on('component:selected', () => {
      setSidebarOpen(true)
    })

    return () => {
      if (gjs) gjs.destroy()
    }
  }, [initialContentJson, initialContentHtml, onSave]);

  useEffect(() => {
    if (!editor) return;
    const bm = editor.BlockManager;
    const allBlocks = bm.getAll();
    
    const isBlocksPanel = activePanel === 'blocks';
    const isTemplatesPanel = activePanel === 'templates';
    
    // Category labels for "Templates"
    const templateCats = ['Top Bars', 'Elite Headers', 'Conversion Hero', 'Welcome & Greet', 'WhatsApp & Social', 'Articles & Blog', 'WooCommerce Hub', 'Cart Recovery', 'Marketing Assets', 'Coupons & Gifts', 'Auth & Security', 'Signature & Info', 'Quick Support', 'Pricing Plans', 'Trust & Proof', 'Elite Footers'];
    
    const filtered = allBlocks.filter((item: unknown) => {
      const block = item as LocalBlock;
      const category = block.get('category');
      const catLabel = typeof category === 'string' ? category : (String((category as LocalBlock)?.get?.('label') || '') || (category as { id?: string })?.id || '');
      const isTemplate = templateCats.includes(String(catLabel));
      
      if (isBlocksPanel && isTemplate) return false;
      if (isTemplatesPanel && !isTemplate) return false;
      if (!isBlocksPanel && !isTemplatesPanel) return false;

      // Search logic
      if (searchTerm.trim()) {
        const name = String(block.get('name') || '').toLowerCase();
        const label = String(block.get('label') || '').toLowerCase();
        const search = searchTerm.toLowerCase();
        // Check if item has a label that's not just an SVG
        const hasText = !label.startsWith('<svg') || label.includes('font-size');
        return name.includes(search) || (hasText && label.includes(search)) || String(catLabel).toLowerCase().includes(search);
      }
      return true;
    });

    // Calculate counts for the badges
    const templateCounts = allBlocks.filter((item: unknown) => {
        const block = item as LocalBlock;
        const category = block.get('category');
        const catLabel = typeof category === 'string' ? category : (String((category as LocalBlock)?.get?.('label') || '') || (category as { id?: string })?.id || '');
        return templateCats.includes(String(catLabel));
    }).length;
    
    setTimeout(() => {
      setBlockCounts({
          templates: templateCounts,
          elements: allBlocks.length - templateCounts
      });
    }, 0);

    bm.render(filtered);
  }, [searchTerm, editor, activePanel]);

  const handleSave = () => {
    if (!editor) return;
    
    // Force inlining by getting HTML (which is now inlined due to inlineCss: true)
    const html = editor.getHtml();
    const css = editor.getCss();
    const fullHtml = `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style type="text/css">${css}</style></head><body style="margin:0;padding:0;">${html}</body></html>`;
    
    const json = JSON.stringify(editor.getProjectData());
    onSave(json, fullHtml);
  }

  const handleDeviceChange = (device: string) => {
    if (!editor) return
    setCurrentDevice(device)
    editor.setDevice(device)
  }

  const handlePanelChange = (panel: string) => {
    setActivePanel(panel)
    if (!editor) return
    if (panel === 'images') editor.runCommand('open-assets')
  }

  const handleUndo = () => editor?.UndoManager.undo()
  const handleRedo = () => editor?.UndoManager.redo()
  const handleClear = () => {
    if (confirm('Are you sure you want to clear the canvas?')) {
      editor?.setComponents('')
    }
  }

  const handleViewCode = () => {
    if (!editor) return;
    editor.runCommand('export-template');
  }

  const toggleFullscreen = () => {
    if (!mainWrapperRef.current) return
    const el = mainWrapperRef.current
    if (!document.fullscreenElement) {
      el.requestFullscreen().catch(err => {
        alert(`Error escaping fullscreen mode: ${err.message}`)
      })
    } else {
      document.exitFullscreen()
    }
  }

  return (
    <TooltipProvider>
      <div
        ref={mainWrapperRef}
        className="flex flex-col w-full bg-white font-['Plus_Jakarta_Sans',sans-serif]"
        style={{ height: height, overflow: 'hidden' }}
      >
        <style>{`
          div:fullscreen { width: 100vw !important; height: 100vh !important; border-radius: 0 !important; background: white !important; z-index: 9999999 !important; }

          /* ── Canvas ──────────────────────────────────────────────── */
          .gjs-pn-panels, .gjs-pn-commands, .gjs-pn-options { display: none !important; }
          .gjs-cv-canvas { background-color: #f0f0f1 !important; top: 0 !important; width: 100% !important; height: 100% !important; border: none !important; }
          .gjs-frame { max-width: 860px !important; margin: 40px auto !important; box-shadow: 0 4px 24px rgba(0,0,0,0.07) !important; background: white !important; border: none !important; border-radius: 0 !important; }

          /* ── Panels shared ───────────────────────────────────────── */
          #gjs-blocks, #gjs-layers, #gjs-styles, #gjs-traits { width: 100%; min-height: 0; background: #ffffff; font-family: 'Bricolage Grotesque', sans-serif; }
          
          /* Custom Scrollbar for sidebar */
          .overflow-y-auto::-webkit-scrollbar { width: 4px; }
          .overflow-y-auto::-webkit-scrollbar-track { background: transparent; }
          .overflow-y-auto::-webkit-scrollbar-thumb { background: #e2e8f0; border-radius: 10px; }
          .overflow-y-auto::-webkit-scrollbar-thumb:hover { background: #cbd5e1; }

          /* ── Blocks panel ────────────────────────────────────────── */
          .gjs-blocks-c { padding: 10px 14px 20px !important; display: grid !important; grid-template-columns: repeat(2, 1fr) !important; gap: 8px !important; background: #ffffff !important; }
          .gjs-block { background: #ffffff !important; border: 1px solid #e8ecf0 !important; border-radius: 10px !important; color: #334155 !important; width: 100% !important; height: 75px !important; padding: 0 !important; margin: 0 !important; display: flex !important; flex-direction: column !important; align-items: center !important; justify-content: center !important; transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1) !important; cursor: grab !important; box-shadow: 0 1px 2px rgba(0,0,0,0.02) !important; overflow: hidden !important; }
          .gjs-block:hover { border-color: #22c55e !important; background: #ffffff !important; transform: translateY(-2px) !important; box-shadow: 0 8px 16px rgba(34,197,94,0.08) !important; }
          .gjs-block svg { fill: none !important; transition: all 0.2s ease !important; stroke-width: 1.2px !important; }
          .gjs-block:hover svg { stroke: #22c55e !important; transform: scale(1.05); }
          .gjs-block__media { display: none !important; }
          .gjs-block-label { margin: 0 !important; padding: 0 !important; width: 100% !important; }

          /* Category titles */
          .gjs-block-category { border-bottom: none !important; margin-bottom: 4px !important; }
          .gjs-block-category .gjs-title, .gjs-title.gjs-category-title, .gjs-category-title {
            background: #ffffff !important; color: #0f172a !important; border: none !important;
            font-weight: 600 !important; font-size: 11px !important; padding: 16px 14px 8px !important;
            letter-spacing: 0.6px !important; text-transform: uppercase !important;
            display: flex !important; align-items: center !important; gap: 8px !important;
            cursor: default !important;
          }
          .gjs-title.gjs-category-title::before, .gjs-category-title::before { display: none !important; }

          /* ── Layers ──────────────────────────────────────────────── */
          .gjs-layer { background: #ffffff !important; color: #334155 !important; border-bottom: 1px solid #f1f5f9 !important; font-size: 12px !important; }
          .gjs-layer.gjs-hovered { background: #f8fafc !important; }
          .gjs-layer.gjs-selected { background: #f0fdf4 !important; color: #15803d !important; border-left: 2px solid #22c55e !important; }
          .gjs-layer-name { font-weight: 500 !important; }
          .gjs-layer-count { background: #f1f5f9 !important; color: #64748b !important; border-radius: 4px !important; font-size: 10px !important; padding: 1px 5px !important; }
          .gjs-layer__icon { color: #94a3b8 !important; }

          /* ── Style Manager ───────────────────────────────────────── */
          .gjs-sm-sector { background: #ffffff !important; border-bottom: 1px solid #f1f5f9 !important; color: #334155 !important; }
          .gjs-sm-sector-title, .gjs-sm-title {
            background: #f8fafc !important; color: #0f172a !important; font-weight: 600 !important;
            padding: 11px 16px !important; border-bottom: 1px solid #f1f5f9 !important;
            font-size: 11px !important; letter-spacing: 0.5px !important; text-transform: uppercase !important;
            display: flex !important; align-items: center !important; cursor: pointer !important;
          }
          .gjs-sm-sector-title:hover, .gjs-sm-title:hover { background: #f1f5f9 !important; }
          .gjs-sm-properties { padding: 14px 16px !important; background: #ffffff !important; }
          .gjs-sm-property { display: flex !important; flex-direction: column !important; margin-bottom: 14px !important; width: 100% !important; padding: 0 !important; }
          .gjs-sm-property.gjs-sm-composite { flex-wrap: wrap !important; flex-direction: row !important; }
          .gjs-sm-label, .gjs-trt-trait .gjs-label { color: #64748b !important; font-size: 11px !important; margin-bottom: 5px !important; font-weight: 500 !important; display: block !important; width: 100% !important; letter-spacing: 0.2px !important; text-transform: uppercase !important; }

          /* ── Trait Manager ───────────────────────────────────────── */
          .gjs-trt-traits { background: #ffffff !important; padding: 14px 16px !important; border-bottom: 1px solid #f1f5f9 !important; color: #334155 !important; }
          .gjs-trt-trait { display: flex; flex-direction: column; margin-bottom: 14px !important; width: 100% !important; }
          .gjs-trt-traits .gjs-label { margin-bottom: 5px !important; padding: 0 !important; line-height: 1 !important; }
          .gjs-trt-traits .gjs-field-checkbox { width: auto !important; margin-top: 4px !important; display: inline-block !important; }

          /* Selector Manager (classes input above styles) */
          .gjs-clm-tags { background: #f8fafc !important; border-bottom: 1px solid #f1f5f9 !important; padding: 10px 16px !important; }
          .gjs-clm-tags .gjs-label { color: #64748b !important; font-size: 11px !important; font-weight: 500 !important; text-transform: uppercase !important; letter-spacing: 0.4px !important; margin-bottom: 8px !important; display: block !important; }
          .gjs-clm-tag { background: #e0fce9 !important; border: 1px solid #bbf7d0 !important; color: #15803d !important; border-radius: 6px !important; padding: 3px 8px !important; font-size: 11px !important; font-weight: 500 !important; display: inline-flex !important; align-items: center !important; gap: 4px !important; }
          .gjs-clm-tag-del { color: #84cc16 !important; cursor: pointer !important; font-weight: 700 !important; }
          .gjs-clm-sel { background: #ffffff !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; padding: 6px 10px !important; color: #334155 !important; font-size: 12px !important; min-width: 90px !important; }

          /* ── Input Fields (shared) ───────────────────────────────── */
          .gjs-fields { width: 100% !important; margin: 0 !important; }
          .gjs-field, .gjs-field-color, .gjs-field-select {
            background-color: #ffffff !important; border: 1px solid #e2e8f0 !important;
            border-radius: 8px !important; color: #0f172a !important;
            box-shadow: 0 1px 2px rgba(0,0,0,0.03) !important; width: 100% !important; overflow: hidden !important;
          }
          .gjs-field:hover, .gjs-field-color:hover, .gjs-field-select:hover { border-color: #cbd5e1 !important; }
          .gjs-field:focus-within { border-color: #22c55e !important; box-shadow: 0 0 0 3px rgba(34,197,94,0.12) !important; }
          .gjs-field input, .gjs-field select, .gjs-field textarea {
            color: #0f172a !important; background-color: transparent !important; border: none !important;
            padding: 8px 10px !important; font-size: 12px !important; width: 100% !important;
            outline: none !important;
          }
          .gjs-field option { color: #0f172a !important; background: #ffffff !important; }
          
          /* Color Picker */
          .gjs-field-color { display: flex !important; align-items: center !important; padding-right: 8px !important; }
          .gjs-field-color-picker { background-color: transparent !important; }
          .gjs-field-colorp-c { height: 18px !important; width: 18px !important; border-radius: 4px !important; border: 1px solid #e2e8f0 !important; margin: 0 !important; }

          /* Select Arrow */
          .gjs-sel-arrow { color: #94a3b8 !important; right: 10px !important; opacity: 0.8 !important; }

          /* Radio Items / Display / Align / Typo Toggles */
          .gjs-radio-items { display: flex !important; gap: 3px !important; flex-wrap: wrap !important; background: #f8fafc !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; padding: 3px !important; }
          .gjs-radio-item { background: transparent !important; color: #64748b !important; border: none !important; border-radius: 6px !important; padding: 5px 8px !important; cursor: pointer !important; text-align: center !important; flex: 1 !important; justify-content: center !important; transition: all 0.15s ease !important; font-size: 11px !important; }
          .gjs-radio-item:hover { background: #e2e8f0 !important; color: #334155 !important; }
          .gjs-radio-item.gjs-radio-item-checked { background: #22c55e !important; color: white !important; box-shadow: 0 1px 3px rgba(34,197,94,0.25) !important; }

          /* ── Modal / Dialog ──────────────────────────────────────── */
          .gjs-mdl-dialog {
            background: #ffffff !important; border-radius: 16px !important;
            box-shadow: 0 20px 60px rgba(0,0,0,0.15), 0 0 0 1px rgba(0,0,0,0.05) !important;
            border: none !important; max-width: 540px !important; width: 90% !important;
            padding: 0 !important; overflow: hidden !important;
          }
          .gjs-mdl-header {
            background: #f8fafc !important; color: #0f172a !important;
            padding: 18px 24px !important; border-bottom: 1px solid #f1f5f9 !important;
            font-weight: 600 !important; font-size: 15px !important; display: flex !important;
            align-items: center !important; justify-content: space-between !important;
          }
          .gjs-mdl-btn-close {
            color: #64748b !important; background: #f1f5f9 !important; border: none !important;
            border-radius: 8px !important; width: 32px !important; height: 32px !important;
            cursor: pointer !important; display: flex !important; align-items: center !important;
            justify-content: center !important; font-size: 18px !important; line-height: 1 !important;
            transition: all 0.15s !important;
          }
          .gjs-mdl-btn-close:hover { background: #e2e8f0 !important; color: #334155 !important; }
          .gjs-mdl-content { padding: 24px !important; background: #ffffff !important; }
          .gjs-mdl-backdrop { background: rgba(15,23,42,0.4) !important; backdrop-filter: blur(4px) !important; }

          /* Asset Manager inside modal */
          .gjs-am-preview-cont { background: #f8fafc !important; border: 2px dashed #cbd5e1 !important; border-radius: 12px !important; }
          .gjs-am-preview-cont:hover { border-color: #22c55e !important; background: #f0fdf4 !important; }
          .gjs-am-add-field { background: #f8fafc !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; color: #334155 !important; padding: 8px 12px !important; width: 100% !important; font-size: 13px !important; }
          .gjs-am-add-field:focus { border-color: #22c55e !important; outline: none !important; box-shadow: 0 0 0 3px rgba(34,197,94,0.12) !important; }
          .gjs-btn-prim, .gjs-am-add { background: #22c55e !important; color: white !important; border: none !important; border-radius: 8px !important; padding: 8px 16px !important; font-size: 13px !important; font-weight: 600 !important; cursor: pointer !important; transition: background 0.15s !important; }
          .gjs-btn-prim:hover, .gjs-am-add:hover { background: #16a34a !important; }
          .gjs-am-file-uploader { background: #f0fdf4 !important; border: 2px dashed #86efac !important; border-radius: 12px !important; color: #15803d !important; padding: 32px !important; text-align: center !important; }
          .gjs-am-file-uploader input { display: none !important; }

          /* ── CRITICAL: Override GrapesJS dark theme base classes ──── */
          .gjs-one-bg { background-color: #ffffff !important; }
          .gjs-two-color { color: #334155 !important; }
          .gjs-three-bg { background-color: #f8fafc !important; }
          .gjs-four-color, .gjs-four-color-h:hover { color: #22c55e !important; }

          /* ── Layer items full override ───────────────────────────── */
          .gjs-layer-item { background: transparent !important; color: #334155 !important; display: flex !important; align-items: center !important; justify-content: space-between !important; padding: 6px 10px !important; min-height: 36px !important; }
          .gjs-layer-item:hover { background: #f8fafc !important; }
          .gjs-layer.gjs-selected > .gjs-layer-item { background: #f0fdf4 !important; color: #15803d !important; border-left: 3px solid #22c55e !important; }
          .gjs-layer-item-left { display: flex !important; align-items: center !important; gap: 4px !important; flex: 1 !important; min-width: 0 !important; }
          .gjs-layer-item-right { display: flex !important; align-items: center !important; gap: 4px !important; flex-shrink: 0 !important; }
          .gjs-layer-vis { color: #94a3b8 !important; cursor: pointer !important; display: flex !important; align-items: center !important; width: 18px !important; height: 18px !important; flex-shrink: 0 !important; }
          .gjs-layer-vis:hover { color: #22c55e !important; }
          .gjs-layer-vis svg { width: 14px !important; height: 14px !important; fill: currentColor !important; }
          .gjs-layer-title-c { flex: 1 !important; min-width: 0 !important; }
          .gjs-layer-title { display: flex !important; align-items: center !important; }
          .gjs-layer-title-inn { display: flex !important; align-items: center !important; gap: 4px !important; min-width: 0 !important; }
          .gjs-layer-name { font-size: 12px !important; font-weight: 500 !important; color: #334155 !important; white-space: nowrap !important; overflow: hidden !important; text-overflow: ellipsis !important; }
          .gjs-layer.gjs-selected .gjs-layer-name { color: #15803d !important; }
          .gjs-layer-caret { color: #94a3b8 !important; display: flex !important; align-items: center !important; width: 14px !important; height: 14px !important; flex-shrink: 0 !important; cursor: pointer !important; }
          .gjs-layer-caret svg { width: 14px !important; height: 14px !important; fill: currentColor !important; }
          .gjs-layer-move { color: #cbd5e1 !important; cursor: grab !important; display: flex !important; align-items: center !important; }
          .gjs-layer-move svg { width: 14px !important; height: 14px !important; fill: currentColor !important; }
          .gjs-layers { background: #ffffff !important; }
          .gjs-layer-children { border-left: 2px solid #f1f5f9 !important; margin-left: 14px !important; }

          /* ── Trait label wrapper ─────────────────────────────────── */
          .gjs-label-wrp { margin-bottom: 5px !important; }
          .gjs-label-wrp .gjs-label { color: #64748b !important; font-size: 11px !important; font-weight: 500 !important; text-transform: uppercase !important; letter-spacing: 0.3px !important; }
          .gjs-field-wrp { width: 100% !important; }
          .gjs-trt-trait__wrp { margin-bottom: 14px !important; }

          /* ── Selector Manager complete ───────────────────────────── */
          .gjs-clm-tags { background: #f8fafc !important; border-bottom: 1px solid #f1f5f9 !important; padding: 12px 16px !important; }
          .gjs-clm-label { color: #64748b !important; font-size: 11px !important; font-weight: 600 !important; text-transform: uppercase !important; letter-spacing: 0.4px !important; margin-bottom: 8px !important; display: block !important; }
          .gjs-clm-selected { color: #64748b !important; font-size: 11px !important; margin-top: 8px !important; display: flex !important; align-items: center !important; gap: 4px !important; flex-wrap: wrap !important; }
          .gjs-clm-select { display: flex !important; align-items: center !important; gap: 8px !important; margin-bottom: 8px !important; }
          .gjs-clm-sel { background: #ffffff !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; padding: 6px 10px !important; color: #334155 !important; font-size: 12px !important; min-width: 90px !important; appearance: auto !important; }
          .gjs-clm-close { color: #94a3b8 !important; cursor: pointer !important; font-weight: 700 !important; }
          .gjs-clm-close:hover { color: #ef4444 !important; }
          .gjs-clm-add { background: #22c55e !important; color: white !important; border: none !important; border-radius: 8px !important; padding: 6px 12px !important; font-size: 12px !important; font-weight: 600 !important; cursor: pointer !important; display: flex !important; align-items: center !important; justify-content: center !important; width: 32px !important; height: 32px !important; flex-shrink: 0 !important; }
          .gjs-clm-add:hover { background: #16a34a !important; }
          .gjs-clm-tag { background: #e0fce9 !important; border: 1px solid #bbf7d0 !important; color: #15803d !important; border-radius: 6px !important; padding: 3px 8px !important; font-size: 11px !important; font-weight: 500 !important; display: inline-flex !important; align-items: center !important; gap: 4px !important; }
          .gjs-clm-tag-del { color: #84cc16 !important; cursor: pointer !important; font-weight: 700 !important; margin-left: 2px !important; }
          .gjs-clm-tag-del:hover { color: #ef4444 !important; }
          .gjs-clm-tags-sel { color: #64748b !important; font-size: 11px !important; }

          /* ── Asset Manager full overhaul ─────────────────────────── */
          .gjs-am-assets-cont { background: #ffffff !important; padding: 16px !important; }
          .gjs-am-assets-header { background: #f8fafc !important; border-bottom: 1px solid #f1f5f9 !important; padding: 12px 16px !important; display: flex !important; align-items: center !important; gap: 8px !important; }
          .gjs-am-assets { display: grid !important; grid-template-columns: repeat(3, 1fr) !important; gap: 10px !important; padding: 8px 0 !important; }
          .gjs-am-asset { background: #f8fafc !important; border: 1px solid #e2e8f0 !important; border-radius: 10px !important; overflow: hidden !important; cursor: pointer !important; transition: all 0.15s !important; }
          .gjs-am-asset:hover { border-color: #22c55e !important; }
          .gjs-am-asset.gjs-am-asset-selected { border-color: #22c55e !important; background: #f0fdf4 !important; box-shadow: 0 0 0 2px rgba(34,197,94,0.2) !important; }
          .gjs-am-preview-cont { background: #f8fafc !important; border: 2px dashed #cbd5e1 !important; border-radius: 10px !important; aspect-ratio: 1 !important; display: flex !important; align-items: center !important; justify-content: center !important; overflow: hidden !important; }
          .gjs-am-preview-cont:hover { border-color: #22c55e !important; background: #f0fdf4 !important; }
          .gjs-am-dimensions { font-size: 10px !important; color: #94a3b8 !important; padding: 4px 6px !important; text-align: center !important; }
          .gjs-am-add-field { background: #ffffff !important; border: 1px solid #e2e8f0 !important; border-radius: 8px !important; color: #334155 !important; padding: 8px 12px !important; flex: 1 !important; font-size: 13px !important; outline: none !important; }
          .gjs-am-add-field:focus { border-color: #22c55e !important; box-shadow: 0 0 0 3px rgba(34,197,94,0.12) !important; }
          .gjs-am-file-uploader { background: #f0fdf4 !important; border: 2px dashed #86efac !important; border-radius: 12px !important; color: #15803d !important; padding: 24px 16px !important; text-align: center !important; font-size: 13px !important; font-weight: 500 !important; cursor: pointer !important; transition: all 0.15s !important; }
          .gjs-am-file-uploader:hover { border-color: #22c55e !important; background: #dcfce7 !important; }
          .gjs-am-file-uploader input { display: none !important; }
          .gjs-am-close { color: #64748b !important; }

          /* ── Misc ────────────────────────────────────────────────── */
          .gjs-caret-icon { display: none !important; }
          .gjs-selected { outline: 2px solid #22c55e !important; outline-offset: 1px !important; }
          .gjs-resizer-h { border: 1px solid #22c55e !important; background: #22c55e !important; border-radius: 3px !important; }
          .gjs-toolbar { background: #0f172a !important; border-radius: 8px !important; box-shadow: 0 4px 16px rgba(0,0,0,0.2) !important; padding: 2px !important; }
          .gjs-toolbar-item { color: #94a3b8 !important; border-radius: 6px !important; transition: all 0.15s !important; }
          .gjs-toolbar-item:hover { color: white !important; background: #1e293b !important; }
          .gjs-badge { background: #22c55e !important; color: white !important; border-radius: 4px !important; font-size: 10px !important; font-weight: 600 !important; padding: 2px 6px !important; }
          ::-webkit-scrollbar { width: 4px; border-radius: 10px; }
          ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
          ::-webkit-scrollbar-track { background: transparent; }
        `}</style>

        {/* Toolbar */}
        <div className="flex h-[72px] items-center justify-between px-6 border-b border-slate-100/80 bg-white shrink-0 z-40">
          <div className="flex items-center gap-2">
            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={() => setSidebarOpen(!sidebarOpen)} className="text-slate-500 hover:text-[#22c55e] hover:bg-slate-50">
                  {sidebarOpen ? <PanelLeftClose className="w-5 h-5" /> : <PanelLeftOpen className="w-5 h-5" />}
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>{sidebarOpen ? 'Collapse Sidebar' : 'Expand Sidebar'}</p></TooltipContent>
            </Tooltip>
            
            <div className="h-6 w-px bg-slate-100 mx-2" />
            
            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={handleUndo} className="text-slate-400 hover:text-[#22c55e] hover:bg-slate-50">
                  <Undo2 className="w-4.5 h-4.5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Undo</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={handleRedo} className="text-slate-400 hover:text-[#22c55e] hover:bg-slate-50">
                  <Redo2 className="w-4.5 h-4.5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Redo</p></TooltipContent>
            </Tooltip>

            <div className="h-6 w-px bg-slate-100 mx-2" />

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={toggleFullscreen} className="text-slate-400 hover:text-[#22c55e] hover:bg-slate-50">
                  <Maximize className="w-4.5 h-4.5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Fullscreen</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={() => editor?.runCommand('preview')} className="text-slate-400 hover:text-[#22c55e] hover:bg-slate-50">
                  <Eye className="w-4.5 h-4.5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Toggle Preview</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={handleViewCode} className="text-slate-400 hover:text-[#22c55e] hover:bg-slate-50">
                  <Code className="w-4.5 h-4.5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>View Code</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={handleClear} className="text-slate-400 hover:text-rose-600 hover:bg-rose-50">
                  <Trash2 className="w-4.5 h-4.5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Clear All</p></TooltipContent>
            </Tooltip>
          </div>

          <div className="flex items-center gap-1.5 p-1.5 bg-slate-100/50 rounded-xl border border-slate-200/50">
            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={() => handleDeviceChange('Desktop')} className={`rounded-[10px] w-9 h-9 ${currentDevice === 'Desktop' ? 'bg-white text-[#22c55e] shadow-sm' : 'text-slate-400 hover:text-slate-600 hover:bg-white/50'}`}>
                  <Monitor className="w-4 h-4" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Desktop</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={() => handleDeviceChange('Tablet')} className={`rounded-[10px] w-9 h-9 ${currentDevice === 'Tablet' ? 'bg-white text-[#22c55e] shadow-sm' : 'text-slate-400 hover:text-slate-600 hover:bg-white/50'}`}>
                  <Tablet className="w-4 h-4" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Tablet</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" onClick={() => handleDeviceChange('Mobile')} className={`rounded-[10px] w-9 h-9 ${currentDevice === 'Mobile' ? 'bg-white text-[#22c55e] shadow-sm' : 'text-slate-400 hover:text-slate-600 hover:bg-white/50'}`}>
                  <Smartphone className="w-4 h-4" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent><p>Mobile</p></TooltipContent>
            </Tooltip>
          </div>

          <div className="flex items-center gap-4">
            {showNameInput && (
              <SettingInput 
                label="Template Name"
                type="text" 
                value={templateName} 
                onChange={(val) => {
                  setTemplateName(val);
                  onNameChange?.(val);
                }} 
                placeholder="Name your template..." 
                className="w-64 max-w-[250px]"
                labelHidden
              />
            )}
            <AdminButton onClick={handleSave} disabled={saving} className="h-10 px-6 font-semibold bg-[#22c55e] hover:bg-[#16a34a] text-white shadow-lg shadow-[#22c55e]/20 transition-all active:scale-95">
              {saving ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Save className="w-4 h-4 mr-2" />}
              Save Template
            </AdminButton>

            <div className="flex items-center gap-2 border-l border-slate-100 pl-4 ml-2">
              <SettingInput 
                label="Test Email"
                type="email" 
                placeholder="Test email..." 
                className="w-48"
                value={testEmail}
                onChange={setTestEmail}
                labelHidden
                icon={Mail}
              />
              <SecondaryButton 
                onClick={() => {
                  if (!editor) return;
                  const html = editor.getHtml();
                  const css = editor.getCss();
                  const fullHtml = `<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><style type="text/css">${css}</style></head><body style="margin:0;padding:0;">${html}</body></html>`;
                  onSendTest?.(fullHtml, testEmail);
                }} 
                disabled={sendingTest || !testEmail} 
                className="h-10 px-4 font-semibold border-blue-200 text-blue-600 hover:bg-blue-50 transition-all active:scale-95"
              >
                {sendingTest ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Mail className="w-4 h-4 mr-2" />}
                Send Test
              </SecondaryButton>
            </div>
          </div>
        </div>

        <div className="flex flex-1 min-h-0 relative bg-white overflow-hidden">
          <div className="w-[72px] h-full border-r border-slate-100 bg-white flex flex-col items-center py-6 gap-3 z-20 shrink-0 shadow-[4px_0_24px_rgba(0,0,0,0.02)]">
            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" className={`w-11 h-11 rounded-[12px] relative ${activePanel === 'blocks' ? 'bg-[#22c55e] text-white hover:bg-[#16a34a] shadow-md shadow-[#22c55e]/20' : 'text-slate-400 hover:text-[#22c55e] hover:bg-slate-50'}`} onClick={() => handlePanelChange('blocks')}>
                  <Plus className="w-5 h-5" />
                  {blockCounts.elements > 0 && (
                    <span className="absolute -top-1 -right-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-slate-100 px-1 text-[9px] font-bold text-slate-600 border border-white shadow-sm">
                      {blockCounts.elements}
                    </span>
                  )}
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent side="right"><p>Elements ({blockCounts.elements})</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" className={`w-11 h-11 rounded-[12px] relative ${activePanel === 'templates' ? 'bg-[#22c55e] text-white hover:bg-[#16a34a] shadow-md shadow-[#22c55e]/20' : 'text-slate-400 hover:text-[#22c55e] hover:bg-slate-50'}`} onClick={() => handlePanelChange('templates')}>
                  <Layout className="w-5 h-5" />
                  {blockCounts.templates > 0 && (
                    <span className="absolute -top-1 -right-1 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-[#22c55e] px-1 text-[9px] font-bold text-white border border-white shadow-sm">
                      {blockCounts.templates}
                    </span>
                  )}
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent side="right"><p>Templates ({blockCounts.templates})</p></TooltipContent>
            </Tooltip>
            
            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" className={`w-11 h-11 rounded-[12px] ${activePanel === 'layers' ? 'bg-[#22c55e] text-white hover:bg-[#16a34a] shadow-md shadow-[#22c55e]/20' : 'text-slate-400 hover:text-[#22c55e] hover:bg-slate-50'}`} onClick={() => handlePanelChange('layers')}>
                  <Layers className="w-5 h-5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent side="right"><p>Layers</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" className={`w-11 h-11 rounded-[12px] ${activePanel === 'styles' ? 'bg-[#22c55e] text-white hover:bg-[#16a34a] shadow-md shadow-[#22c55e]/20' : 'text-slate-400 hover:text-[#22c55e] hover:bg-slate-50'}`} onClick={() => handlePanelChange('styles')}>
                  <Palette className="w-5 h-5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent side="right"><p>Styles</p></TooltipContent>
            </Tooltip>

            <Tooltip>
              <TooltipTrigger asChild>
                <GhostButton size="icon-sm" className={`w-11 h-11 rounded-[12px] ${activePanel === 'images' ? 'bg-[#22c55e] text-white hover:bg-[#16a34a] shadow-md shadow-[#22c55e]/20' : 'text-slate-400 hover:text-[#22c55e] hover:bg-slate-50'}`} onClick={() => handlePanelChange('images')}>
                  <ImageIcon className="w-5 h-5" />
                </GhostButton>
              </TooltipTrigger>
              <TooltipContent side="right"><p>Images</p></TooltipContent>
            </Tooltip>

            {onBack && (
              <>
                <div className="flex-1" />
                <Tooltip>
                  <TooltipTrigger asChild>
                    <GhostButton 
                      size="icon-sm" 
                      className="w-11 h-11 rounded-[12px] text-slate-400 hover:text-rose-600 hover:bg-rose-50 mb-2" 
                      onClick={onBack}
                    >
                      <ArrowLeft className="w-5 h-5" />
                    </GhostButton>
                  </TooltipTrigger>
                  <TooltipContent side="right"><p>Back to List</p></TooltipContent>
                </Tooltip>
              </>
            )}
          </div>

        {/* ── Sidebar panel ───────────────────────────────── */}
          <div
            className={`bg-white border-r border-slate-200/50 transition-all duration-300 flex flex-col overflow-hidden shadow-sm ${
              sidebarOpen ? 'w-[320px]' : 'w-0 border-none opacity-0'
            }`}
          >
            {/* Fixed search header */}
            {(activePanel === 'blocks' || activePanel === 'templates') && (
              <div className="p-3 border-b border-slate-100 bg-white shrink-0">
                <div className="relative">
                  <SettingInput 
                    label="Search"
                    placeholder={activePanel === 'templates' ? "Search templates..." : "Search elements..."}
                    value={searchTerm}
                    onChange={setSearchTerm}
                    icon={Search}
                    className="h-8 text-[11px] bg-slate-50 border-none"
                    labelHidden
                  />
                </div>
                <div className="flex items-center justify-between mt-2.5 px-1">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    {activePanel === 'templates' ? 'Templates Library' : 'Basic Elements'}
                  </span>
                  <span className="bg-slate-100 text-slate-500 text-[9px] font-bold px-1.5 py-0.5 rounded-full border border-slate-200/50">
                    {activePanel === 'templates' ? blockCounts.templates : blockCounts.elements} Blocks
                  </span>
                </div>
              </div>
            )}
            {/*
              position:relative wrapper → children use position:absolute.
              This breaks out of the document flow so blocks can NEVER
              push the page height, yet scroll freely inside.
            */}
            <div className="relative flex-1" style={{ minHeight: 0 }}>
              <div
                id="gjs-blocks"
                style={{ position: 'absolute', inset: 0, overflowY: 'auto' }}
                className={activePanel === 'blocks' || activePanel === 'templates' ? '' : 'hidden'}
              />
              <div
                id="gjs-layers"
                style={{ position: 'absolute', inset: 0, overflowY: 'auto' }}
                className={activePanel === 'layers' ? '' : 'hidden'}
              />
              <div
                id="gjs-styles"
                style={{ position: 'absolute', inset: 0, overflowY: 'auto' }}
                className={activePanel === 'styles' ? '' : 'hidden'}
              />
            </div>
          </div>

          <div className="flex-1 overflow-hidden relative">
            <div ref={gjsContainerRef} className="w-full h-full bg-white" />
          </div>
        </div>
      </div>
    </TooltipProvider>
  )
}


