// Окружение редактора: топбар, сайдбар, таб-бар, статусбар, клавиши
// Global CTA target
const CTA_LINK = 'https://t.me/ai_mng';

const chromeStyles = {
  topbar: {
    position: 'sticky', top: 0, zIndex: 50,
    display: 'flex', alignItems: 'center',
    height: 42, padding: '0 14px',
    background: 'rgba(10,10,11,0.85)',
    backdropFilter: 'blur(14px)',
    borderBottom: '1px solid var(--line)',
    fontFamily: 'Manrope,sans-serif', fontSize: 12,
    color: 'var(--fg-dim)',
    gap: 16
  },
  dot: { width: 12, height: 12, borderRadius: '50%' },
  menu: { display: 'flex', gap: 18, color: 'var(--fg-dim)' },
  menuItem: { cursor: 'default', transition: 'color .15s' },
  breadcrumb: {
    display: 'flex', alignItems: 'center', gap: 8,
    padding: '4px 12px', background: 'var(--bg-2)', borderRadius: 8,
    border: '1px solid var(--line)',
    color: 'var(--fg-dim)', fontSize: 11
  }
};

// Встроенный аудио-плеер — маленькая кнопка с нотой
function MusicButton() {
  const [playing, setPlaying] = React.useState(false);
  const audioRef = React.useRef(null);

  React.useEffect(() => {
    const src = window.__AUDIO && window.__AUDIO.track || 'assets/track.mp3';
    const a = new Audio(src);
    a.loop = true;
    a.volume = 0.7;
    a.preload = 'auto';
    audioRef.current = a;
    const onEnd = () => setPlaying(false);
    a.addEventListener('pause', () => setPlaying(false));
    a.addEventListener('play', () => setPlaying(true));
    return () => {
      a.pause();
      audioRef.current = null;
    };
  }, []);

  const toggle = () => {
    const a = audioRef.current;
    if (!a) return;
    if (a.paused) {
      a.play().catch((err) => console.warn('audio play blocked:', err));
    } else {
      a.pause();
    }
  };

  return (
    <button
      onClick={toggle}
      aria-label={playing ? 'Пауза' : 'Включить музыку'}
      title={playing ? 'Пауза' : 'Включить музыку'}
      style={{
        position: 'relative',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        width: 36, height: 36, flex: '0 0 36px',
        background: 'var(--bg-2)',
        border: '1px solid var(--line-2)',
        borderRadius: 10,
        color: playing ? 'var(--yellow)' : 'var(--fg-dim)',
        cursor: 'pointer',
        padding: 0,
        transition: 'color .15s, border-color .15s, background .15s'
      }}
      onMouseEnter={(e) => {e.currentTarget.style.borderColor = 'var(--yellow)';e.currentTarget.style.color = 'var(--yellow)';}}
      onMouseLeave={(e) => {e.currentTarget.style.borderColor = 'var(--line-2)';if (!playing) e.currentTarget.style.color = 'var(--fg-dim)';}}>
      
      {/* Note icon */}
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
        <path d="M9 18V5l12-2v13" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx="6" cy="18" r="3" fill="currentColor" />
        <circle cx="18" cy="16" r="3" fill="currentColor" />
      </svg>
      {/* Pulse ring when playing */}
      {playing &&
      <span style={{
        position: 'absolute', inset: -2, borderRadius: 12,
        border: '1px solid var(--yellow)',
        opacity: 0.5,
        animation: 'music-pulse 1.4s ease-out infinite',
        pointerEvents: 'none'
      }} />
      }
      <style>{`
        @keyframes music-pulse {
          0% { transform: scale(0.95); opacity: 0.7; }
          100% { transform: scale(1.15); opacity: 0; }
        }
      `}</style>
    </button>);

}

// Навигация в стиле референса: логотип + меню + CTA (+ бургер на мобилке)
function NavBar() {
  const [open, setOpen] = React.useState(false);
  const menu = [
  ['Программа', 'modules'],
  ['Отзывы', 'testimonials'],
  ['Тарифы', 'pricing'],
  ['FAQ', 'faq']];

  return (
    <>
      <nav style={{
        position: 'sticky', top: 0, zIndex: 50,
        display: 'flex', alignItems: 'center',
        padding: '14px 20px',
        background: 'rgba(10,10,11,0.85)',
        backdropFilter: 'blur(16px)',
        borderBottom: '1px solid rgba(255,255,255,0.04)',
        gap: 16
      }} className="nav-root">
        {/* Logo */}
        <a href="#top" style={{
          display: 'flex', alignItems: 'baseline', gap: 8,
          textDecoration: 'none', color: 'var(--yellow)',
          fontFamily: 'Manrope,sans-serif', fontWeight: 700, fontSize: 20,
          letterSpacing: '-0.01em',
          flex: '0 0 auto',
          lineHeight: 1
        }}>
          <span style={{ color: 'var(--fg)' }}>INTGRTR&nbsp;<span style={{ color: 'var(--yellow)' }}>2.0</span></span>
          <span style={{
            color: 'var(--fg-mute)',
            fontFamily: 'JetBrains Mono, ui-monospace, monospace',
            fontSize: 10,
            fontWeight: 600,
            letterSpacing: '0.12em',
            textTransform: 'lowercase'
          }}>new level</span>
        </a>
        {/* Music toggle */}
        <MusicButton />
        {/* Desktop menu */}
        <div className="nav-desktop" style={{ display: 'flex', gap: 32, alignItems: 'center', flex: 1, paddingLeft: 28 }}>
          {menu.map(([m, id], i) =>
          <a key={i} href={'#' + id} style={{
            color: 'var(--fg-dim)', textDecoration: 'none',
            fontFamily: 'Manrope,sans-serif', fontSize: 18, fontWeight: 500,
            transition: 'color .15s'
          }} onMouseEnter={(e) => e.currentTarget.style.color = 'var(--fg)'} onMouseLeave={(e) => e.currentTarget.style.color = 'var(--fg-dim)'}>
              {m}
            </a>
          )}
          <span style={{ width: 1, height: 18, background: 'var(--line-2)' }} />
          <button style={{
            display: 'flex', alignItems: 'center', gap: 4,
            background: 'transparent', border: 'none',
            color: 'var(--fg-dim)', cursor: 'pointer',
            fontFamily: 'Manrope,sans-serif', fontSize: 18
          }}>
            RU <span style={{ fontSize: 10 }}>▾</span>
          </button>
        </div>
        <div style={{ flex: 1 }} className="nav-mobile-spacer" />
        {/* Desktop CTA */}
        <div className="nav-desktop"><NavCTA /></div>
        {/* Mobile burger */}
        <button
          className="nav-mobile"
          onClick={() => setOpen((o) => !o)}
          aria-label="Меню"
          style={{
            display: 'none', alignItems: 'center', justifyContent: 'center',
            width: 42, height: 42, flex: '0 0 42px',
            background: 'var(--bg-2)',
            border: '1px solid var(--line-2)', borderRadius: 10,
            color: 'var(--fg)', cursor: 'pointer', padding: 0
          }}>
          
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            <span style={{
              width: 18, height: 2, background: 'var(--fg)', borderRadius: 1,
              transform: open ? 'translateY(6px) rotate(45deg)' : 'none',
              transition: 'transform .2s'
            }} />
            <span style={{
              width: 18, height: 2, background: 'var(--fg)', borderRadius: 1,
              opacity: open ? 0 : 1,
              transition: 'opacity .15s'
            }} />
            <span style={{
              width: 18, height: 2, background: 'var(--fg)', borderRadius: 1,
              transform: open ? 'translateY(-6px) rotate(-45deg)' : 'none',
              transition: 'transform .2s'
            }} />
          </div>
        </button>
      </nav>
      {/* Mobile menu overlay */}
      {open &&
      <div style={{
        position: 'fixed', top: 70, left: 0, right: 0, bottom: 0, zIndex: 49,
        background: 'rgba(10,10,11,0.97)',
        backdropFilter: 'blur(20px)',
        padding: '24px 20px 40px',
        display: 'flex', flexDirection: 'column', gap: 4,
        overflowY: 'auto'
      }} className="nav-mobile-menu">
          {menu.map(([m, id], i) =>
        <a key={i} href={'#' + id}
        onClick={() => setOpen(false)}
        style={{
          padding: '18px 4px',
          borderBottom: '1px solid var(--line)',
          color: 'var(--fg)', textDecoration: 'none',
          fontFamily: 'Manrope,sans-serif', fontSize: 22, fontWeight: 600,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between'
        }}>
          
              <span>{m}</span>
              <span style={{ color: 'var(--yellow)', fontSize: 18 }}>→</span>
            </a>
        )}
          <div style={{ marginTop: 28 }}>
            <NavCTA />
          </div>
        </div>
      }
    </>);

}

function TopBar() {
  return (
    <div style={chromeStyles.topbar}>
      <div style={{ display: 'flex', gap: 8 }}>
        <div style={{ ...chromeStyles.dot, background: '#ff5f57' }} />
        <div style={{ ...chromeStyles.dot, background: '#febc2e' }} />
        <div style={{ ...chromeStyles.dot, background: '#28c840' }} />
      </div>
      <div style={chromeStyles.menu}>
        <span>Файл</span><span>Правка</span><span>Вид</span>
        <span>Агент</span><span>Терминал</span><span>Помощь</span>
      </div>
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
        <div style={chromeStyles.breadcrumb}>
          <Kbd small>⌘</Kbd><Kbd small>K</Kbd>
          <span style={{ marginLeft: 8 }}>Найти обучение автоматизациям…</span>
          <span style={{ marginLeft: 'auto', color: 'var(--fg-mute)' }}>vibecode://new-level</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10, alignItems: 'center', color: '#8dffbb' }}>
        <span>●</span><span>agent: online</span>
      </div>
    </div>);

}

// 3D клавиша — pillow-keycap style (зеркалит клавиатуру в финальном CTA)
function Kbd({ children, small, size = 'md', wide, tone = 'default', onClick, href, style = {}, pressed = false, interactive = false }) {
  const [hov, setHov] = React.useState(false);
  const [prs, setPrs] = React.useState(false);
  const dims = small ? { h: 22, px: 9, fs: 11, r: 7 } :
  size === 'lg' ? { h: 44, px: 18, fs: 17, r: 12 } :
  size === 'xl' ? { h: 58, px: 24, fs: 20, r: 16 } :
  { h: 32, px: 12, fs: 13, r: 9 };

  const palettes = {
    yellow: {
      faceGrad: 'linear-gradient(180deg, #a08bff 0%, #7c5cff 55%, #6d4aff 100%)',
      fg: '#ffffff',
      shadow: 'rgba(40, 24, 110, 0.55)',
      hi: 'rgba(255,255,210,0.7)',
      innerBot: 'rgba(80,60,0,0.35)'
    },
    orange: {
      faceGrad: 'linear-gradient(180deg, #a08bff 0%, #7c5cff 55%, #6d4aff 100%)',
      fg: '#ffffff',
      shadow: 'rgba(40, 24, 110, 0.55)',
      hi: 'rgba(255,255,210,0.7)',
      innerBot: 'rgba(80,60,0,0.35)'
    },
    blue: {
      faceGrad: 'linear-gradient(180deg, #7be0a9 0%, #3ee08a 55%, #22c46d 100%)',
      fg: '#0a1a10',
      shadow: 'rgba(0,80,40,0.55)',
      hi: 'rgba(190,210,255,0.55)',
      innerBot: 'rgba(15,42,102,0.45)'
    },
    ghost: {
      faceGrad: 'transparent',
      fg: 'var(--fg)',
      shadow: 'transparent',
      hi: 'transparent',
      innerBot: 'transparent',
      border: '1px solid var(--line-2)'
    },
    default: {
      faceGrad: 'linear-gradient(180deg, #2a2a32 0%, #1e1e23 55%, #141418 100%)',
      fg: 'var(--fg)',
      shadow: 'rgba(0,0,0,0.55)',
      hi: 'rgba(255,255,255,0.08)',
      innerBot: 'rgba(0,0,0,0.4)'
    }
  };
  const pal = palettes[tone] || palettes.default;

  const isInteractive = !!onClick || !!href || interactive;
  const isPressed = pressed || prs;
  const translate = isPressed ? 2 : 0;

  const wrapStyle = {
    position: 'relative',
    display: 'inline-flex',
    verticalAlign: 'middle',
    height: dims.h,
    minWidth: wide ? dims.h * 2.6 : dims.h,
    cursor: isInteractive ? 'pointer' : 'default',
    userSelect: 'none',
    textDecoration: 'none',
    ...style
  };

  const shadowStyle = {
    position: 'absolute',
    left: '6%', right: '6%',
    top: '55%', bottom: -dims.h * 0.22,
    borderRadius: dims.r,
    background: `radial-gradient(50% 60% at 50% 40%, ${pal.shadow} 0%, transparent 70%)`,
    filter: 'blur(4px)',
    opacity: isPressed ? 0.5 : hov ? 0.95 : 0.8,
    transition: 'opacity .15s',
    zIndex: 0,
    pointerEvents: 'none'
  };

  const faceStyle = {
    position: 'relative',
    flex: 1,
    height: dims.h,
    padding: `0 ${dims.px}px`,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 6,
    background: pal.faceGrad,
    border: pal.border,
    borderRadius: dims.r,
    boxShadow: pal.faceGrad === 'transparent' ? undefined : `
      inset 0 1.5px 0 ${pal.hi},
      inset 0 -2px 0 ${pal.innerBot},
      inset 0 -6px 10px -4px ${pal.innerBot},
      0 1px 0 rgba(255,255,255,0.12)
    `,
    color: pal.fg,
    fontFamily: 'Manrope,sans-serif',
    fontWeight: 600,
    fontSize: dims.fs,
    letterSpacing: '-0.005em',
    whiteSpace: 'nowrap',
    transform: `translateY(${translate}px)`,
    transition: 'transform .12s',
    zIndex: 2
  };

  const handlers = isInteractive ? {
    onMouseEnter: () => setHov(true),
    onMouseLeave: () => {setHov(false);setPrs(false);},
    onMouseDown: () => setPrs(true),
    onMouseUp: () => setPrs(false),
    onClick
  } : {};

  const inner =
  <>
      {pal.faceGrad !== 'transparent' && <span style={shadowStyle} aria-hidden="true" />}
      <span style={faceStyle}>{children}</span>
    </>;


  if (href) return <a href={href} style={wrapStyle} {...handlers}>{inner}</a>;
  return <span style={wrapStyle} {...handlers}>{inner}</span>;
}

// CTA кнопка — pillow keycap (зеркалит клавиши клавиатуры)
function CTAButton({ children, tone = 'yellow', size = 'lg', icon = '', block = false, small = false, href = CTA_LINK, onClick, target = '_blank' }) {
  const [h, sH] = React.useState(false);
  const [p, sP] = React.useState(false);
  const height = size === 'xl' ? 64 : size === 'lg' ? 54 : 42;
  const radius = Math.round(height * 0.28);
  const fontSize = size === 'xl' ? 20 : size === 'lg' ? 18 : 18;
  const padding = size === 'xl' ? '0 44px' : size === 'lg' ? '0 36px' : '0 24px';

  // pillow palettes
  const palettes = {
    yellow: {
      faceGrad: 'linear-gradient(180deg, #a08bff 0%, #7c5cff 45%, #6d4aff 100%)',
      fg: '#ffffff',
      shadow: 'rgba(40, 24, 110, 0.6)',
      glow: 'rgba(124, 92, 255, 0.55)',
      hi: 'rgba(220,210,255,0.7)',
      innerBot: 'rgba(40,24,110,0.35)'
    },
    blue: {
      faceGrad: 'linear-gradient(180deg, #7be0a9 0%, #3ee08a 45%, #22c46d 100%)',
      fg: '#0a1a10',
      shadow: 'rgba(0,80,40,0.6)',
      glow: 'rgba(59,130,246,0.4)',
      hi: 'rgba(190,210,255,0.55)',
      innerBot: 'rgba(15,42,102,0.45)'
    },
    light: {
      faceGrad: 'linear-gradient(180deg, #ffffff 0%, #f6f4ee 55%, #ebe8df 100%)',
      fg: '#1a1a1b',
      shadow: 'rgba(80,75,65,0.35)',
      glow: 'rgba(255,255,255,0.15)',
      hi: 'rgba(255,255,255,0.95)',
      innerBot: 'rgba(180,175,160,0.45)'
    },
    dark: {
      faceGrad: 'linear-gradient(180deg, #2a2a32 0%, #1e1e23 55%, #141418 100%)',
      fg: '#ededee',
      shadow: 'rgba(0,0,0,0.55)',
      glow: 'rgba(124, 92, 255,0.2)',
      hi: 'rgba(255,255,255,0.08)',
      innerBot: 'rgba(0,0,0,0.4)'
    }
  };
  const pal = palettes[tone] || palettes.yellow;

  const translate = p ? 3 : h ? -2 : 0;

  const wrapperStyle = {
    position: 'relative',
    display: block ? 'block' : 'inline-block',
    width: block ? '100%' : 'auto',
    height,
    cursor: 'pointer',
    textDecoration: 'none',
    userSelect: 'none',
    verticalAlign: 'top'
  };

  // soft pillow shadow under the key
  const shadowStyle = {
    position: 'absolute',
    left: height * 0.06,
    right: height * 0.06,
    top: height * 0.55,
    bottom: -height * 0.22,
    borderRadius: radius,
    background: `radial-gradient(50% 60% at 50% 40%, ${pal.shadow} 0%, transparent 70%)`,
    filter: h && !p ? 'blur(12px)' : 'blur(8px)',
    opacity: p ? 0.4 : h ? 1 : 0.85,
    transform: h && !p ? 'translateY(3px) scale(1.04)' : p ? 'translateY(-2px) scale(0.94)' : 'none',
    transition: 'opacity .15s, transform .15s, filter .15s',
    zIndex: 0,
    pointerEvents: 'none'
  };

  // ambient glow behind (for accent tones)
  const glowStyle = {
    position: 'absolute',
    inset: -8,
    borderRadius: radius + 10,
    boxShadow: `0 10px 40px ${pal.glow}`,
    opacity: h || p ? 1 : 0.5,
    pointerEvents: 'none',
    zIndex: 0,
    transition: 'opacity .25s'
  };

  // key face
  const faceStyle = {
    position: 'relative',
    height,
    width: block ? '100%' : 'auto',
    borderRadius: radius,
    background: pal.faceGrad,
    boxShadow: `
      inset 0 1.5px 0 ${pal.hi},
      inset 0 -3px 0 ${pal.innerBot},
      inset 0 -10px 14px -6px ${pal.innerBot},
      0 1px 0 rgba(255,255,255,0.18)
    `,
    display: 'inline-flex',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 12,
    padding,
    fontFamily: 'Manrope,sans-serif',
    fontWeight: 600,
    fontSize,
    color: pal.fg,
    letterSpacing: '-0.005em',
    transform: `translateY(${translate}px)`,
    transition: 'transform .12s',
    zIndex: 2,
    whiteSpace: 'nowrap'
  };

  const handlers = {
    onMouseEnter: () => sH(true),
    onMouseLeave: () => {sH(false);sP(false);},
    onMouseDown: () => sP(true),
    onMouseUp: () => sP(false),
    onTouchStart: () => sP(true),
    onTouchEnd: () => sP(false)
  };

  const inner =
  <>
      <span style={glowStyle} aria-hidden="true" />
      <span style={shadowStyle} aria-hidden="true" />
      <span style={faceStyle}>
        {icon ? <span style={{ fontSize: '0.82em', opacity: .8, fontWeight: 700 }}>{icon}</span> : null}
        <span style={{ display: 'inline-flex', alignItems: 'center' }}>{children}</span>
      </span>
    </>;


  if (href && !onClick) {
    return (
      <a href={href} target={target} rel={target === '_blank' ? 'noopener noreferrer' : undefined} style={wrapperStyle} {...handlers}>
        {inner}
      </a>);

  }
  return (
    <button onClick={onClick} style={{ ...wrapperStyle, border: 'none', background: 'transparent', padding: 0 }} {...handlers}>
      {inner}
    </button>);

}

// NavBar CTA — compact keycap
function NavCTA() {
  return (
    <CTAButton tone="yellow" size="sm" small>
      Записаться
    </CTAButton>);

}

// Окно редактора (карточка с tabs)
function EditorWindow({ tabs = ['index.vibe'], active = 0, children, style = {}, right = null }) {
  return (
    <div style={{
      background: 'var(--bg-1)',
      border: '1px solid var(--line)',
      borderRadius: 14,
      overflow: 'hidden',
      ...style
    }}>
      <div style={{
        display: 'flex', alignItems: 'center',
        background: 'var(--bg-2)',
        borderBottom: '1px solid var(--line)',
        fontFamily: 'Manrope,sans-serif', fontSize: 12,
        color: 'var(--fg-mute)',
        paddingRight: 10
      }}>
        {tabs.map((t, i) =>
        <div key={i} style={{
          padding: '9px 14px',
          background: i === active ? 'var(--bg-1)' : 'transparent',
          color: i === active ? 'var(--fg)' : 'var(--fg-mute)',
          borderRight: '1px solid var(--line)',
          borderTop: i === active ? `2px solid var(--accent)` : '2px solid transparent',
          marginTop: -1,
          display: 'flex', alignItems: 'center', gap: 8
        }}>
            <svg width="12" height="12" viewBox="0 0 12 12"><rect x="1" y="1" width="10" height="10" rx="2" fill="none" stroke="currentColor" opacity=".5" /></svg>
            {t}
            {i === active && <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--accent)', marginLeft: 6 }} />}
          </div>
        )}
        <div style={{ flex: 1 }} />
        {right}
      </div>
      {children}
    </div>);

}

// Номера строк
function LineNumbers({ count = 20, start = 1, highlight = [] }) {
  return (
    <div style={{
      fontFamily: 'Manrope,sans-serif',
      fontSize: 12, lineHeight: '22px',
      color: 'var(--fg-mute)',
      textAlign: 'right',
      padding: '14px 10px 14px 14px',
      borderRight: '1px solid var(--line)',
      userSelect: 'none',
      minWidth: 46
    }}>
      {Array.from({ length: count }).map((_, i) =>
      <div key={i} style={{ color: highlight.includes(start + i) ? 'var(--accent)' : 'var(--fg-mute)' }}>
          {String(start + i).padStart(2, '0')}
        </div>
      )}
    </div>);

}

// Секционный разделитель
function SectionLabel({ id, title, right }) {
  return (
    <div className="section-label" style={{
      display: 'flex', alignItems: 'center', gap: 20,
      padding: '48px 40px 28px',
      borderTop: '1px solid var(--line)',
      background: 'linear-gradient(180deg, var(--bg-1) 0%, transparent 100%)'
    }}>
      <span className="title" style={{
        fontFamily: 'Manrope,sans-serif', fontSize: 12,
        color: 'var(--fg-mute)', padding: '4px 10px',
        background: 'var(--bg-2)', border: '1px solid var(--line)',
        borderRadius: 6
      }}>// {id}</span>
      <span style={{
        fontFamily: 'Manrope,sans-serif',
        fontSize: '53.94px',
        fontWeight: 600,
        lineHeight: 1.05,

        letterSpacing: '-0.02em', color: "rgb(237, 237, 238)"
      }}>
        {title}
      </span>
      <div style={{ flex: 1, height: 1, background: 'var(--line)' }} />
      <span className="right">{right}</span>
    </div>);

}

Object.assign(window, { TopBar, NavBar, Kbd, CTAButton, EditorWindow, LineNumbers, SectionLabel });