// SG App — main shell

const DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 78,
  "layout": "right-inspector",
  "density": "comfortable",
  "showOnboarding": false
}/*EDITMODE-END*/;

const initialState = {
  bg: { type: 'gradient', value: 'amber' },
  frame: 'browser',
  frameTheme: 'dark',
  url: 'app.example.com/dashboard',
  padding: 64,
  radius: 10,
  tilt: 0,
  shadow: 'medium',
  border: true,
  aspect: '16:9',
  caption: '',
  watermark: false,
  watermarkText: '@you',
  annotations: [],
  image: null,
};

function App() {
  const [tweaks, setTweak] = useTweaks(DEFAULTS);
  const [showOnb, setShowOnb] = React.useState(true);
  const [step, setStep] = React.useState(0);
  const [s, setS] = React.useState(initialState);
  const [zoom, setZoom] = React.useState(100);
  const [tab, setTab] = React.useState('design');
  const [showCmd, setShowCmd] = React.useState(false);
  const [activeTool, setActiveTool] = React.useState('cursor');
  const stageRef = React.useRef(null);
  
  // History for Undo/Redo
  const [history, setHistory] = React.useState([initialState]);
  const [hIndex, setHIndex] = React.useState(0);

  const updateS = (newS) => {
    let nextS = typeof newS === 'function' ? newS(s) : newS;
    setS(nextS);
    const newHistory = history.slice(0, hIndex + 1);
    newHistory.push(nextS);
    setHistory(newHistory);
    setHIndex(newHistory.length - 1);
  };

  const handleUndo = () => {
    if (hIndex > 0) {
      setHIndex(hIndex - 1);
      setS(history[hIndex - 1]);
    }
  };

  const handleRedo = () => {
    if (hIndex < history.length - 1) {
      setHIndex(hIndex + 1);
      setS(history[hIndex + 1]);
    }
  };

  // Drag, drop, paste logic
  React.useEffect(() => {
    const handleFile = (file) => {
      if (file && file.type.startsWith('image/')) {
        const url = URL.createObjectURL(file);
        updateS(prev => ({ ...prev, image: url, aspect: 'auto' }));
      }
    };
    
    const onDrop = (e) => {
      e.preventDefault();
      handleFile(e.dataTransfer.files[0]);
    };
    const onDragOver = (e) => e.preventDefault();
    
    const onPaste = (e) => {
      const items = e.clipboardData.items;
      for (let i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          handleFile(items[i].getAsFile());
        }
      }
    };

    window.addEventListener('drop', onDrop);
    window.addEventListener('dragover', onDragOver);
    window.addEventListener('paste', onPaste);
    return () => {
      window.removeEventListener('drop', onDrop);
      window.removeEventListener('dragover', onDragOver);
      window.removeEventListener('paste', onPaste);
    };
  }, []);

  const handleExport = async () => {
    if (!stageRef.current || !window.htmlToImage) {
      if (!window.htmlToImage) console.error("htmlToImage is not loaded!");
      return;
    }
    try {
      const dataUrl = await window.htmlToImage.toPng(stageRef.current, { pixelRatio: 2 });
      const link = document.createElement('a');
      link.download = `screengod-${Date.now()}.png`;
      link.href = dataUrl;
      link.click();
    } catch (err) {
      console.error('Export failed', err);
    }
  };

  const handleCopy = async () => {
    if (!stageRef.current || !window.htmlToImage) return;
    try {
      const blob = await window.htmlToImage.toBlob(stageRef.current, { pixelRatio: 2 });
      if (blob) {
        await navigator.clipboard.write([new window.ClipboardItem({ 'image/png': blob })]);
        alert('Скопировано в буфер обмена!');
      }
    } catch (e) {
      console.error('Copy failed', e);
    }
  };

  React.useEffect(() => {
    const onTool = e => setActiveTool(e.detail);
    window.addEventListener('sg-export', handleExport);
    window.addEventListener('sg-copy', handleCopy);
    window.addEventListener('sg-tool', onTool);
    return () => {
      window.removeEventListener('sg-export', handleExport);
      window.removeEventListener('sg-copy', handleCopy);
      window.removeEventListener('sg-tool', onTool);
    };
  }, []);

  // Apply accent hue from tweaks
  React.useEffect(() => {
    document.documentElement.style.setProperty('--accent', `oklch(0.82 0.14 ${tweaks.accentHue})`);
    document.documentElement.style.setProperty('--accent-deep', `oklch(0.65 0.16 ${tweaks.accentHue - 18})`);
    document.documentElement.style.setProperty('--accent-soft', `oklch(0.82 0.14 ${tweaks.accentHue} / 0.14)`);
  }, [tweaks.accentHue]);

  // Cmd+K
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') { e.preventDefault(); setShowCmd(v => !v); }
      if (e.key === 'Escape') setShowCmd(false);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const layout = tweaks.layout;

  return (
    <div style={{ width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column', background: 'var(--bg-0)' }}>
      {/* Onboarding */}
      {showOnb && <SGOnboarding step={step} setStep={setStep} onFinish={() => setShowOnb(false)} />}

      {/* Top bar */}
      <header style={{
        height: 52, borderBottom: '1px solid var(--line-soft)',
        display: 'flex', alignItems: 'center', padding: '0 14px',
        background: 'var(--bg-0)', flexShrink: 0,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginRight: 24 }}>
          <SGLogoMark size={22} />
          <div>
            <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1 }}>ScreenGod</div>
            <div style={{ fontFamily: 'Geist Mono, monospace', fontSize: 9, color: 'var(--fg-3)', letterSpacing: 0.5, marginTop: 1 }}>v2.0</div>
          </div>
        </div>

        <div style={{ width: 1, height: 22, background: 'var(--line-soft)', marginRight: 14 }} />

        {/* File tabs */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <button style={{
            padding: '6px 12px', borderRadius: 6, fontSize: 12, color: 'var(--fg-1)',
            background: 'var(--bg-2)', border: '1px solid var(--line-soft)',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)' }} />
            untitled.png
            <span style={{ color: 'var(--fg-3)' }}>×</span>
          </button>
          <label style={{ padding: '6px 8px', color: 'var(--fg-3)', cursor: 'pointer', display: 'flex', alignItems: 'center' }}>
            <input type="file" accept="image/*" style={{ display: 'none' }} onChange={e => {
              const file = e.target.files[0];
              if (file) {
                const url = URL.createObjectURL(file);
                updateS(prev => ({ ...prev, image: url, aspect: 'auto' }));
              }
            }} />
            <IconPlus size={13} />
          </label>
        </div>

        <div style={{ flex: 1 }} />

        {/* Centre nav tabs */}
        <div style={{ display: 'flex', gap: 2, padding: 3, background: 'var(--bg-1)', borderRadius: 7, border: '1px solid var(--line-soft)' }}>
          {[
            { id: 'design', label: 'Дизайн' },
            { id: 'annotate', label: 'Аннотации' },
            { id: 'export', label: 'Экспорт' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              padding: '5px 12px', fontSize: 12, fontWeight: 500,
              background: tab === t.id ? 'var(--bg-3)' : 'transparent',
              color: tab === t.id ? 'var(--fg-0)' : 'var(--fg-2)',
              borderRadius: 5, transition: 'all 0.15s'
            }}>{t.label}</button>
          ))}
        </div>

        <div style={{ flex: 1 }} />

        {/* Right cluster */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <button onClick={handleUndo} style={{ ...iconBtnStyle(), opacity: hIndex > 0 ? 1 : 0.5 }}><IconUndo size={14} /></button>
          <button onClick={handleRedo} style={{ ...iconBtnStyle(), opacity: hIndex < history.length - 1 ? 1 : 0.5 }}><IconRedo size={14} /></button>
          <div style={{ width: 1, height: 20, background: 'var(--line-soft)', margin: '0 4px' }} />
          <button onClick={() => setShowCmd(true)} style={{
            padding: '6px 10px 6px 10px', borderRadius: 6, fontSize: 12, color: 'var(--fg-2)',
            background: 'var(--bg-1)', border: '1px solid var(--line-soft)',
            display: 'flex', alignItems: 'center', gap: 8, minWidth: 200,
          }}>
            <IconSearch size={12} />
            <span style={{ flex: 1, textAlign: 'left' }}>Найти команду…</span>
            <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10, color: 'var(--fg-3)' }}>⌘K</span>
          </button>
          <div style={{ width: 1, height: 20, background: 'var(--line-soft)', margin: '0 4px' }} />
          <button onClick={handleExport} style={{
            padding: '6px 12px', borderRadius: 6, fontSize: 12, fontWeight: 600,
            background: 'var(--accent)', color: 'var(--bg-0)',
            display: 'flex', alignItems: 'center', gap: 6,
            boxShadow: '0 1px 0 rgba(255,255,255,0.18) inset, 0 6px 16px -8px var(--accent)'
          }}>
            <IconDownload size={12} strokeWidth={2.2} />
            Экспорт
          </button>
          <div style={{ width: 1, height: 20, background: 'var(--line-soft)', margin: '0 4px' }} />
          <button style={{
            width: 28, height: 28, borderRadius: '50%',
            background: 'linear-gradient(135deg, oklch(0.78 0.14 78) 0%, oklch(0.55 0.16 60) 100%)',
            fontSize: 11, fontWeight: 600, color: 'var(--bg-0)',
            display: 'flex', alignItems: 'center', justifyContent: 'center'
          }}>SG</button>
        </div>
      </header>

      {/* Main area */}
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {/* Left sidebar - tools */}
        <aside style={{
          width: 56, borderRight: '1px solid var(--line-soft)',
          background: 'var(--bg-0)', flexShrink: 0,
          display: 'flex', flexDirection: 'column', alignItems: 'center', padding: '10px 0', gap: 4,
        }}>
          {[
            { id: 'cursor', i: <IconCursor size={15} />, label: 'Выбор' },
            { id: 'image', i: <IconImage size={15} />, label: 'Изображение' },
            { id: 'text', i: <IconText size={15} />, label: 'Текст' },
            { id: 'arrow', i: <IconArrow size={15} />, label: 'Стрелка' },
            { id: 'blur', i: <IconBlur size={15} />, label: 'Блюр' },
            { id: 'sparkle', i: <IconSparkle size={15} />, label: 'AI улучш.' },
          ].map((t) => {
            const isActive = activeTool === t.id;
            return (
              <label key={t.id} title={t.label} onClick={(e) => {
                if (t.id === 'sparkle') {
                  e.preventDefault();
                  updateS(prev => ({ ...prev, enhance: !prev.enhance }));
                  return;
                }
                if (t.id !== 'image') { e.preventDefault(); setActiveTool(t.id); }
              }} style={{
                width: 36, height: 36, borderRadius: 8, cursor: 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                color: isActive ? 'var(--accent)' : 'var(--fg-2)',
                background: isActive ? 'var(--accent-soft)' : 'transparent',
                border: isActive ? '1px solid oklch(0.82 0.14 78 / 0.3)' : '1px solid transparent',
              }}>
                {t.id === 'image' && (
                  <input type="file" accept="image/*" style={{ display: 'none' }} onChange={e => {
                    const file = e.target.files[0];
                    if (file) {
                      const url = URL.createObjectURL(file);
                      updateS(prev => ({ ...prev, image: url, aspect: 'auto' }));
                    }
                  }} />
                )}
                {t.i}
              </label>
            );
          })}
          <div style={{ flex: 1 }} />
          <button title="Слои" onClick={() => setTab('annotate')} style={{ width: 36, height: 36, borderRadius: 8, color: 'var(--fg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <IconLayers size={15} />
          </button>
          <button title="Настройки" style={{ width: 36, height: 36, borderRadius: 8, color: 'var(--fg-2)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <IconGear size={15} />
          </button>
        </aside>

        {/* Presets strip */}
        <aside style={{
          width: 96, borderRight: '1px solid var(--line-soft)',
          background: 'var(--bg-0)', flexShrink: 0, overflowY: 'auto', padding: '12px 10px'
        }}>
          <div style={{
            fontFamily: 'Geist Mono, monospace', fontSize: 9, letterSpacing: 1.5,
            textTransform: 'uppercase', color: 'var(--fg-3)', marginBottom: 10, paddingLeft: 2
          }}>Пресеты</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { name: 'Twitter', g: PRESET_GRADIENTS[0], frame: 'browser' },
              { name: 'Product Hunt', g: PRESET_GRADIENTS[6], frame: 'browser' },
              { name: 'Mobile', g: PRESET_GRADIENTS[1], frame: 'device' },
              { name: 'Чистый', g: PRESET_GRADIENTS[5], frame: 'window' },
              { name: 'Презент.', g: PRESET_GRADIENTS[7], frame: 'browser' },
              { name: 'Лендинг', g: PRESET_GRADIENTS[2], frame: 'window' },
            ].map((p, i) => (
              <button key={i} onClick={() => updateS({ ...s, bg: { type: 'gradient', value: p.g.id }, frame: p.frame })}
                style={{
                  borderRadius: 8, padding: 6,
                  border: '1px solid var(--line-soft)',
                  background: 'var(--bg-1)',
                }}>
                <div style={{
                  width: '100%', aspectRatio: '4/3', borderRadius: 4,
                  background: p.g.css, display: 'flex', alignItems: 'center', justifyContent: 'center'
                }}>
                  <div style={{ width: '70%', height: '60%', background: '#0c0a09', borderRadius: 2 }} />
                </div>
                <div style={{ fontSize: 10, color: 'var(--fg-2)', marginTop: 5, textAlign: 'center' }}>{p.name}</div>
              </button>
            ))}
            <label style={{
              padding: '12px 6px', borderRadius: 8, border: '1px dashed var(--line)',
              color: 'var(--fg-3)', fontSize: 10, cursor: 'pointer',
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4
            }}>
              <input type="file" accept="image/*" style={{ display: 'none' }} onChange={e => {
                const file = e.target.files[0];
                if (file) {
                  const url = URL.createObjectURL(file);
                  updateS(prev => ({ ...prev, image: url }));
                }
              }} />
              <IconPlus size={12} />
              <span>Новый</span>
            </label>
          </div>
        </aside>

        {/* Canvas */}
        <main style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0 }}>
          <SGCanvas s={s} onUpdate={updateS} zoom={zoom} activeTool={activeTool} setActiveTool={setActiveTool} registerStageRef={ref => stageRef.current = ref.current} />
          {/* Bottom statusbar */}
          <div style={{
            height: 30, borderTop: '1px solid var(--line-soft)',
            background: 'var(--bg-0)', display: 'flex', alignItems: 'center', padding: '0 14px',
            fontFamily: 'Geist Mono, monospace', fontSize: 10, color: 'var(--fg-3)', gap: 18
          }}>
            <span>Размер: 1920 × 1080 px</span>
            <span>Фон: {s.bg.type === 'gradient' ? 'Градиент' : s.bg.type === 'solid' ? 'Цвет' : 'Паттерн'}</span>
            <span>Рамка: {s.frame === 'browser' ? 'Браузер' : s.frame === 'window' ? 'Окно' : s.frame === 'device' ? 'Телефон' : 'Без'}</span>
            <span>Тень: {s.shadow === 'none' ? 'Нет' : s.shadow === 'soft' ? 'Мягкая' : s.shadow === 'medium' ? 'Средняя' : s.shadow === 'hard' ? 'Жесткая' : 'Свечение'}</span>
            <div style={{ flex: 1 }} />
            <button onClick={() => setZoom(Math.max(25, zoom - 10))}>−</button>
            <span style={{ minWidth: 36, textAlign: 'center', color: 'var(--fg-1)' }}>{zoom}%</span>
            <button onClick={() => setZoom(Math.min(200, zoom + 10))}>+</button>
            <span style={{ width: 1, height: 14, background: 'var(--line-soft)' }} />
            <span style={{ color: 'var(--good)' }}>● автосохранение</span>
          </div>
        </main>

        {/* Right inspector */}
        {layout === 'right-inspector' && (
          <>
            {tab === 'design' && <SGInspector s={s} onUpdate={updateS} />}
            {tab === 'annotate' && (
              <aside style={{ width: 280, borderLeft: '1px solid var(--line-soft)', background: 'var(--bg-0)', display: 'flex', flexDirection: 'column', padding: 16 }}>
                <div style={{ fontSize: 12, fontWeight: 600, marginBottom: 16, textTransform: 'uppercase', letterSpacing: 1.5, color: 'var(--fg-3)', fontFamily: 'Geist Mono, monospace' }}>Слои аннотаций</div>
                {!s.annotations || s.annotations.length === 0 ? (
                  <div style={{ fontSize: 13, color: 'var(--fg-2)', textAlign: 'center', marginTop: 40 }}>
                    <IconArrow size={32} style={{ opacity: 0.3, marginBottom: 12 }} />
                    <br />
                    Выберите инструмент (Текст, Стрелка) на левой панели и кликните по холсту, чтобы добавить аннотации.
                  </div>
                ) : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: 1, overflowY: 'auto' }}>
                    {s.annotations.map((a, i) => (
                      <div key={a.id} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 12px', background: 'var(--bg-1)', borderRadius: 8, border: '1px solid var(--line-soft)' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--fg-1)', overflow: 'hidden' }}>
                          <span style={{ color: 'var(--fg-3)', flexShrink: 0 }}>
                            {a.type === 'label' ? <IconText size={14} /> : a.type === 'arrow' ? <IconArrow size={14} /> : <IconBlur size={14} />}
                          </span>
                          <span style={{ whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>
                            {a.type === 'label' ? `Текст: ${a.text}` : a.type === 'arrow' ? `Стрелка ${i+1}` : `Блюр ${i+1}`}
                          </span>
                        </div>
                        <button onClick={() => updateS(p => ({ ...p, annotations: p.annotations.filter(an => an.id !== a.id) }))} style={{ color: 'var(--fg-3)', cursor: 'pointer', padding: 4, flexShrink: 0 }}>
                          ✕
                        </button>
                      </div>
                    ))}
                    <button onClick={() => updateS(p => ({ ...p, annotations: [] }))} style={{ marginTop: 'auto', padding: '8px', fontSize: 12, color: '#ef4444', background: 'transparent', border: '1px dashed var(--line)', borderRadius: 6, cursor: 'pointer' }}>Удалить все</button>
                  </div>
                )}
              </aside>
            )}
            {tab === 'export' && (
              <aside style={{ width: 280, borderLeft: '1px solid var(--line-soft)', background: 'var(--bg-0)', display: 'flex', flexDirection: 'column', padding: 20, gap: 16 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>Экспорт</div>
                <div style={{ fontSize: 12, color: 'var(--fg-2)' }}>Сохраните ваш холст в высоком качестве. Включите автосохранение для синхронизации.</div>
                
                <button onClick={handleExport} style={{
                  padding: '12px 14px', borderRadius: 8, fontSize: 13, fontWeight: 600,
                  background: 'var(--accent)', color: 'var(--bg-0)', textAlign: 'center',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  boxShadow: '0 1px 0 rgba(255,255,255,0.18) inset, 0 6px 16px -8px var(--accent)'
                }}>
                  <IconDownload size={14} strokeWidth={2.2} />
                  Скачать PNG
                </button>
                <button onClick={async () => {
                  if (!stageRef.current || !window.htmlToImage) return;
                  try {
                    const blob = await window.htmlToImage.toBlob(stageRef.current, { pixelRatio: 2 });
                    if (blob) {
                      await navigator.clipboard.write([new window.ClipboardItem({ 'image/png': blob })]);
                      alert('Скопировано в буфер обмена!');
                    }
                  } catch (e) {
                    console.error('Copy failed', e);
                  }
                }} style={{
                  padding: '10px 14px', borderRadius: 8, fontSize: 13, fontWeight: 500,
                  background: 'var(--bg-1)', color: 'var(--fg-1)', border: '1px solid var(--line-soft)',
                  textAlign: 'center', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}>
                  <IconCopy size={14} />
                  Копировать в буфер
                </button>
              </aside>
            )}
          </>
        )}
      </div>

      {/* Floating dock variant */}
      {layout === 'floating' && (
        <div style={{
          position: 'fixed', bottom: 50, left: '50%', transform: 'translateX(-50%)',
          background: 'var(--bg-1)', border: '1px solid var(--line)',
          borderRadius: 14, padding: 8, display: 'flex', gap: 6,
          boxShadow: '0 30px 60px -15px rgba(0,0,0,0.5)', zIndex: 50
        }}>
          {PRESET_GRADIENTS.slice(0, 8).map(g => (
            <button key={g.id} onClick={() => updateS({ ...s, bg: { type: 'gradient', value: g.id } })}
              style={{
                width: 40, height: 40, borderRadius: 8, background: g.css,
                border: s.bg.value === g.id ? '2px solid var(--accent)' : '1px solid var(--line-soft)'
              }} />
          ))}
        </div>
      )}

      {/* Command palette */}
      {showCmd && <CommandPalette onClose={() => setShowCmd(false)} s={s} updateS={updateS} handleExport={handleExport} />}

      {/* Tweaks panel */}
      <TweaksPanel>
        <TweakSection title="Раскладка">
          <TweakRadio label="Положение инспектора" value={tweaks.layout} onChange={v => setTweak('layout', v)}
            options={[
              { value: 'right-inspector', label: 'Справа' },
              { value: 'floating', label: 'Плавающий' },
            ]} />
        </TweakSection>
        <TweakSection title="Цвета">
          <TweakSlider label="Акцентный оттенок" value={tweaks.accentHue} min={0} max={360} step={1}
            onChange={v => setTweak('accentHue', v)} />
          <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
            {[78, 25, 200, 280, 145, 340].map(h => (
              <button key={h} onClick={() => setTweak('accentHue', h)} style={{
                flex: 1, height: 22, borderRadius: 5,
                background: `oklch(0.82 0.14 ${h})`,
                border: tweaks.accentHue === h ? '2px solid white' : '1px solid var(--line)'
              }} />
            ))}
          </div>
        </TweakSection>
        <TweakSection title="Онбординг">
          <TweakButton onClick={() => { setShowOnb(true); setStep(0); }} label="Показать онбординг снова" />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

function iconBtnStyle() {
  return {
    width: 28, height: 28, borderRadius: 6,
    color: 'var(--fg-2)',
    display: 'flex', alignItems: 'center', justifyContent: 'center',
  };
}

function CommandPalette({ onClose, s, updateS, handleExport }) {
  const [q, setQ] = React.useState('');
  const items = [
    { icon: <IconWand size={14} />, label: 'Применить пресет: Twitter', kbd: '1', action: () => updateS({ ...s, bg: { type: 'gradient', value: 'amber' }, frame: 'browser' }) },
    { icon: <IconFrame size={14} />, label: 'Сменить рамку на «Браузер»', kbd: 'F', action: () => updateS({ ...s, frame: 'browser' }) },
    { icon: <IconFrame size={14} />, label: 'Убрать рамку', action: () => updateS({ ...s, frame: 'none' }) },
    { icon: <IconDownload size={14} />, label: 'Экспорт PNG', kbd: '⌘E', action: handleExport },
    { icon: <IconCopy size={14} />, label: 'Копировать в буфер', kbd: '⌘⇧C' },
    { icon: <IconShare size={14} />, label: 'Получить ссылку', kbd: '⌘L' },
    { icon: <IconSparkle size={14} />, label: 'Сохранить как пресет' },
    { icon: <IconBlur size={14} />, label: 'Блюр чувствительных областей' },
  ].filter(i => i.label.toLowerCase().includes(q.toLowerCase()));

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 90,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: 120,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 540, background: 'var(--bg-1)', borderRadius: 12,
        border: '1px solid var(--line)', overflow: 'hidden',
        boxShadow: '0 40px 80px -20px rgba(0,0,0,0.7)'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid var(--line-soft)' }}>
          <IconSearch size={14} style={{ color: 'var(--fg-3)' }} />
          <input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder="Поиск команды…"
            style={{ flex: 1, background: 'transparent', border: 0, outline: 'none', fontSize: 14, color: 'var(--fg-0)' }} />
          <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10, color: 'var(--fg-3)', padding: '3px 6px', border: '1px solid var(--line)', borderRadius: 4 }}>esc</span>
        </div>
        <div style={{ maxHeight: 360, overflowY: 'auto', padding: 6 }}>
          {items.map((it, i) => (
            <button key={i} onClick={() => { it.action && it.action(); onClose(); }} style={{
              width: '100%', display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 12px', borderRadius: 6, color: 'var(--fg-1)',
              background: i === 0 ? 'var(--bg-2)' : 'transparent', textAlign: 'left'
            }}>
              <span style={{ color: 'var(--fg-2)' }}>{it.icon}</span>
              <span style={{ flex: 1, fontSize: 13 }}>{it.label}</span>
              {it.kbd && <span style={{ fontFamily: 'Geist Mono, monospace', fontSize: 10, color: 'var(--fg-3)', padding: '3px 6px', border: '1px solid var(--line-soft)', borderRadius: 4 }}>{it.kbd}</span>}
            </button>
          ))}
          {items.length === 0 && (
            <div style={{ padding: 32, textAlign: 'center', color: 'var(--fg-3)', fontSize: 13 }}>
              Ничего не нашлось
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
