// Shell без собственной шапки — Telegram предоставляет её.
// Оставляем только контент + sticky MainButton.

function TGShell({ dark = true, children, mainLabel = 'Сохранить', mainDisabled = false, onMain, scrollRef, keyboard = false, onCancelKeyboard }) {
  const t = dark ? window.TG.dark : window.TG.light;
  const footerRef = React.useRef();
  const keyboardRef = React.useRef(keyboard);
  const blurTimerRef = React.useRef();

  // useLayoutEffect — до paint: скрываем футер пока React меняет верстку (убирает кнопку
  // отмены, расширяет Save), потом плавно показываем уже обновлённый вариант
  React.useLayoutEffect(() => {
    keyboardRef.current = keyboard;
    const el = footerRef.current;
    if (!el) return;
    if (!keyboard) {
      clearTimeout(blurTimerRef.current);
      el.style.transition = 'none';
      el.style.opacity = '0';
      blurTimerRef.current = setTimeout(() => {
        el.style.transition = 'opacity 250ms ease-in';
        el.style.opacity = '1';
      }, 50);
    }
  }, [keyboard]);

  React.useEffect(() => {
    const tg = window.Telegram?.WebApp;
    const el = footerRef.current;
    if (!tg || !el) return;
    let timer;
    const onViewportChanged = () => {
      if (!keyboardRef.current) return;
      if (el.style.opacity === '0') return; // уже скрыт — последующие события игнорируем
      el.style.transition = 'none';
      el.style.opacity = '0';
      timer = setTimeout(() => {
        el.style.transition = 'opacity 250ms ease-in';
        el.style.opacity = '1';
      }, 300);
    };
    tg.onEvent('viewportChanged', onViewportChanged);
    return () => { tg.offEvent('viewportChanged', onViewportChanged); clearTimeout(timer); };
  }, []);

  return (
    <div style={{
      position: 'absolute', inset: 0,
      background: t.bg,
      display: 'flex', flexDirection: 'column',
      fontFamily: '-apple-system, "SF Pro Text", system-ui, sans-serif',
      color: t.text,
    }}>
      <div ref={scrollRef} style={{
        flex: 1, overflow: 'auto', background: t.bg,
        WebkitOverflowScrolling: 'touch',
      }}>
        {children}
      </div>

      {mainLabel && (
        <div ref={footerRef} style={{
          position: 'absolute', bottom: 0, left: 0, right: 0,
          padding: '20px 12px 10px',
          background: 'transparent',
          display: 'flex', gap: 8, alignItems: 'center',
        }}>
          <button onClick={onMain} disabled={mainDisabled} style={{
            width: keyboard ? '75%' : '100%',
            height: 48, borderRadius: 12, border: 'none',
            background: mainDisabled ? (dark ? 'rgba(51,144,236,0.35)' : 'rgba(51,144,236,0.4)') : t.accent,
            color: t.accentText, fontSize: 15, fontWeight: 590, letterSpacing: -0.2,
            cursor: mainDisabled ? 'default' : 'pointer',
            transition: 'width .22s cubic-bezier(.2,.7,.3,1), background .15s, transform .08s',
            fontFamily: 'inherit', flexShrink: 0,
          }}
          onMouseDown={(e) => !mainDisabled && (e.currentTarget.style.transform = 'scale(0.99)')}
          onMouseUp={(e) => (e.currentTarget.style.transform = '')}
          onMouseLeave={(e) => (e.currentTarget.style.transform = '')}
          >{mainLabel}</button>

          {keyboard && (
            <button
              onClick={onCancelKeyboard}
              aria-label="Закрыть клавиатуру"
              style={{
                flex: 1, height: 48, borderRadius: 12, border: 'none',
                background: t.bg3,
                color: t.text, fontSize: 15, fontWeight: 510, letterSpacing: -0.2,
                cursor: 'pointer', fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                transition: 'background .15s, transform .08s',
              }}
              onMouseDown={(e) => (e.currentTarget.style.transform = 'scale(0.97)')}
              onMouseUp={(e) => (e.currentTarget.style.transform = '')}
              onMouseLeave={(e) => (e.currentTarget.style.transform = '')}
            >
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <rect x="2" y="4" width="20" height="12" rx="2" />
                <path d="M6 8h.01M10 8h.01M14 8h.01M18 8h.01M7 12h10M8 20l4-3 4 3" />
              </svg>
            </button>
          )}
        </div>
      )}

    </div>
  );
}

function TGSearch({ dark, value, onChange, placeholder = 'Поиск тем и тегов', autoFocusVisual = false, onFocus, onBlur }) {
  const t = dark ? window.TG.dark : window.TG.light;
  const [focused, setFocused] = React.useState(autoFocusVisual);
  React.useEffect(() => { if (autoFocusVisual) setFocused(true); }, [autoFocusVisual]);
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.05)',
      borderRadius: 10, padding: '8px 12px',
      transition: 'background .15s',
    }}>
      <div style={{ color: focused ? t.accent : t.textMuted, display: 'flex' }}>
        <window.IconSVG name="search" size={18} strokeWidth={2} />
      </div>
      <input
        value={value} onChange={(e) => onChange(e.target.value)}
        onFocus={() => { setFocused(true); onFocus && onFocus(); }}
        onBlur={() => { setFocused(false); onBlur && onBlur(); }}
        placeholder={placeholder}
        style={{
          flex: 1, border: 'none', outline: 'none', background: 'transparent',
          color: t.text, fontSize: 16, fontFamily: 'inherit',
          caretColor: t.accent,
        }}
      />
      {value && (
        <button onClick={() => onChange('')} style={{
          border: 'none', background: 'transparent', padding: 0,
          color: t.textMuted, cursor: 'pointer', display: 'flex',
        }}>
          <window.IconSVG name="close" size={16} strokeWidth={2.2} />
        </button>
      )}
    </div>
  );
}

Object.assign(window, { TGShell, TGSearch });
