// Dev Portal: Apps+CMS, Products CRUD, Payouts, Webhooks, Billing
const { useState: uS_d3, useMemo: uM_d3 } = React;

// Helper — section card
function DCard({ title, action, children, dense, style }) {
  return (
    <section className="card" style={{padding: dense ? 16 : 20, marginBottom: 16, ...style}}>
      {(title || action) && (
        <header style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: dense ? 12 : 16}}>
          {title && <h3 className="display" style={{fontSize: 15, fontWeight: 700, margin: 0, letterSpacing:'-0.01em'}}>{title}</h3>}
          {action}
        </header>
      )}
      {children}
    </section>
  );
}

// ============== 11. DEV APPS + CMS (PROTO-12) ==============
function ScreenDevApps({ goto, mobile }) {
  const [tab, setTab] = uS_d3('content');
  const [contentTab, setContentTab] = uS_d3('media');
  const game = MOCK_GAMES[0]; // Astral Chronicles

  const guides = [
    { t: 'Гайд по системе крафта в патче 2.4', author: 'Команда AC', date: '01 мая', views: 18420, status: 'live' },
    { t: 'Лучшие билды для нового рейда', author: 'Команда AC', date: '28 апр', views: 12180, status: 'live' },
    { t: 'Как получить первого героя 5★', author: 'Команда AC', date: '24 апр', views: 41020, status: 'live' },
    { t: 'Туториал: новый режим Битвы Триад', author: 'Команда AC', date: '—', views: 0, status: 'draft' },
  ];
  const news = [
    { t: 'Патч 2.4 «Звёздный поход» — что нового', date: '02 мая', status: 'live', img: '#6366F1' },
    { t: 'Розыгрыш 1М кристаллов в честь годовщины', date: '15 мая', status: 'scheduled', img: '#A855F7' },
    { t: 'Технические работы 5 мая', date: '—', status: 'draft', img: '#6B7280' },
  ];
  const forumPosts = [
    { user: 'NebulaPlayer42', txt: 'Как получить новый эпик-меч из ивента?', likes: 24, replies: 8, time: '2 ч назад', status: 'open' },
    { user: 'StarHunter99',   txt: 'Баг: пропадает анимация удара в рейде', likes: 12, replies: 3, time: '4 ч назад', status: 'flagged' },
    { user: 'CrystalMage',    txt: 'Сколько стоит топ-уп в России теперь?', likes: 67, replies: 19, time: '6 ч назад', status: 'pinned' },
    { user: 'DragonRider',    txt: 'Когда добавите кросс-платформу с iOS?', likes: 41, replies: 12, time: '1 д назад', status: 'open' },
  ];

  return (
    <DevShell goto={goto} mobile={mobile} currentScreen="devApps" title="Приложения">
      {/* App switcher row */}
      <div style={{display:'flex', alignItems:'center', gap:16, marginBottom:20, flexWrap:'wrap'}}>
        <div style={{display:'flex', alignItems:'center', gap:12}}>
          <div style={{width:48, height:48, borderRadius:12, background:'linear-gradient(135deg, #6366F1, #A855F7)', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:700, fontFamily:'var(--font-display)', fontSize:18}}>AC</div>
          <div>
            <div style={{fontSize:18, fontWeight:700, fontFamily:'var(--font-display)', letterSpacing:'-0.01em'}}>{game.title}</div>
            <div style={{fontSize:12, color:'var(--text-muted)', display:'flex', gap:8, alignItems:'center'}}>
              <span className="badge badge-success">live</span>
              <span>iOS · Android · RuStore</span>
              <span>·</span>
              <span>app_id: app_ac_{game.slug}</span>
            </div>
          </div>
        </div>
        <div style={{flex:1}}/>
        <select className="input" style={{maxWidth:200, fontSize:13}}>
          <option>Astral Chronicles</option>
          <option>FitCoach Pro</option>
          <option>Lingomate</option>
          <option>Kingdom Rise</option>
          <option>Race Arena</option>
        </select>
        <div style={{display:'flex', gap:6, padding:3, background:'var(--n-100)', borderRadius:'var(--r-4)'}}>
          <button style={{padding:'5px 12px', fontSize:12, fontWeight:600, background:'var(--surface)', borderRadius:'var(--r-3)', color:'var(--text)'}}>test</button>
          <button style={{padding:'5px 12px', fontSize:12, fontWeight:600, color:'var(--text-muted)'}}>live</button>
        </div>
      </div>

      {/* Tabs */}
      <div className="tabs" style={{marginBottom:20}}>
        {[['overview','Обзор'], ['content','Контент'], ['settings','Настройки']].map(([id, l]) => (
          <button key={id} className={'tab' + (tab===id ? ' active' : '')} onClick={()=>setTab(id)}>{l}</button>
        ))}
      </div>

      {tab === 'overview' && (
        <>
          <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(4, 1fr)', gap:12, marginBottom:20}}>
            {[['MRR этого приложения', '1,82 М ₽', '+14,2%'], ['GMV (30 дн)', '3,18 М ₽', '+11,8%'], ['Active subs', '5 240', '+8,1%'], ['Active users', '142К', '+6,4%']].map(([l,v,d]) => (
              <div key={l} className="card" style={{padding:16}}>
                <div className="kpi-label">{l}</div>
                <div className="kpi-value tnum" style={{margin:'6px 0 4px'}}>{v}</div>
                <div style={{fontSize:11, color:'var(--success)', fontWeight:600}}>{d}</div>
              </div>
            ))}
          </div>
          <DCard title="О приложении" action={<button className="btn btn-secondary btn-sm">Редактировать</button>}>
            <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'200px 1fr', gap:24, alignItems:'start'}}>
              <div style={{aspectRatio:'1/1', borderRadius:12, background:'linear-gradient(135deg, #6366F1, #A855F7)', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:800, fontFamily:'var(--font-display)', fontSize:48}}>AC</div>
              <div>
                <div style={{display:'grid', gridTemplateColumns:'140px 1fr', rowGap:10, columnGap:16, fontSize:13}}>
                  <span style={{color:'var(--text-muted)'}}>Название</span><span style={{fontWeight:600}}>Astral Chronicles</span>
                  <span style={{color:'var(--text-muted)'}}>Жанр</span><span>RPG / Фэнтези</span>
                  <span style={{color:'var(--text-muted)'}}>Платформы</span><span>iOS · Android · RuStore</span>
                  <span style={{color:'var(--text-muted)'}}>App Store</span><span style={{color:'var(--info)'}}>apps.apple.com/app/id6478…</span>
                  <span style={{color:'var(--text-muted)'}}>Google Play</span><span style={{color:'var(--info)'}}>play.google.com/store/apps/details?id=studio.nebula…</span>
                  <span style={{color:'var(--text-muted)'}}>RuStore</span><span style={{color:'var(--info)'}}>rustore.ru/catalog/app/studio.nebula…</span>
                  <span style={{color:'var(--text-muted)'}}>Описание</span><span style={{lineHeight:1.5, color:'var(--text-soft)'}}>Эпическая RPG в открытом мире — 30+ героев, рейды на 12, PvP-арена и масштабные сезонные ивенты.</span>
                </div>
              </div>
            </div>
          </DCard>
        </>
      )}

      {tab === 'content' && (
        <>
          {/* Content sub-tabs */}
          <div style={{display:'flex', gap:4, marginBottom:16, borderRadius:'var(--r-5)', padding:4, background:'var(--n-100)', width:'fit-content', flexWrap:'wrap'}}>
            {[['media','Медиа'],['desc','Описание'],['guides','Гайды'],['news','Новости'],['forum','Обсуждения']].map(([id,l]) => (
              <button key={id} onClick={()=>setContentTab(id)} style={{
                padding:'6px 14px', fontSize:13, fontWeight:600, borderRadius:'var(--r-4)',
                background: contentTab===id ? 'var(--surface)' : 'transparent',
                color: contentTab===id ? 'var(--text)' : 'var(--text-muted)',
                boxShadow: contentTab===id ? 'var(--shadow-sm)' : 'none',
              }}>{l}</button>
            ))}
          </div>

          {contentTab === 'media' && (
            <DCard title="Обложки и скриншоты" action={<button className="btn btn-primary btn-sm"><IconUpload size={14}/> Загрузить</button>}>
              <div style={{border:'2px dashed var(--border-strong)', borderRadius:'var(--r-6)', padding:36, textAlign:'center', marginBottom:16, background:'var(--n-25)'}}>
                <IconUpload size={28} style={{color:'var(--text-muted)', margin:'0 auto 8px'}}/>
                <div style={{fontSize:14, fontWeight:600}}>Перетащите файлы сюда</div>
                <div style={{fontSize:12, color:'var(--text-muted)', marginTop:4}}>JPG, PNG, MP4 · до 8 МБ · 16:9 для обложек</div>
              </div>
              <div style={{display:'grid', gridTemplateColumns:`repeat(${mobile?2:4}, 1fr)`, gap:10}}>
                {Array.from({length:8}, (_,i) => (
                  <div key={i} style={{aspectRatio:'16/9', borderRadius:'var(--r-5)', overflow:'hidden', position:'relative'}}>
                    <GameCover slug={['astral-chronicles','pixel-quest','race-arena','kingdom-rise'][i%4]} accent={['#6366F1','#10B981','#EF4444','#0EA5E9'][i%4]} accent2={['#A855F7','#14B8A6','#F97316','#22D3EE'][i%4]}/>
                    {i===0 && <div style={{position:'absolute', top:6, left:6, background:'var(--n-900)', color:'#fff', fontSize:10, fontWeight:700, padding:'3px 8px', borderRadius:'var(--r-2)'}}>ОСНОВНАЯ</div>}
                    <button style={{position:'absolute', top:6, right:6, width:24, height:24, borderRadius:'50%', background:'rgba(0,0,0,0.6)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center'}}><IconX size={12}/></button>
                  </div>
                ))}
              </div>
            </DCard>
          )}

          {contentTab === 'desc' && (
            <DCard title="Описание игры" action={<><button className="btn btn-ghost btn-sm">Превью</button><button className="btn btn-primary btn-sm">Сохранить</button></>}>
              <div style={{display:'flex', gap:6, padding:'4px 6px', background:'var(--n-50)', borderRadius:'var(--r-3)', marginBottom:8, border:'1px solid var(--border)'}}>
                {['B','I','U','H1','H2','•','1.','—','{}','🔗'].map((b,i)=>(<button key={i} style={{padding:'4px 8px', fontSize:12, fontWeight:600, color:'var(--text-soft)', borderRadius:'var(--r-2)'}}>{b}</button>))}
              </div>
              <textarea
                defaultValue={`# Астральные хроники\n\n**Astral Chronicles** — эпическая RPG в открытом мире со звёздной механикой. Соберите команду из 30+ героев, прокачайте их в сюжетной кампании на 80+ часов и отправляйтесь на рейды против древних драконов.\n\n## Особенности\n\n- 30+ героев с уникальными способностями\n- Рейды на 12 игроков с боссами трёх стихий\n- Сезонный PvP-режим «Битвы Триад»\n- Кросс-серверные альянсы и войны гильдий\n\n## Что нового в патче 2.4\n\nДобавлены 4 новых героя 5★, переработана система крафта, новый ивент «Звёздный поход» с эксклюзивными наградами.`}
                style={{width:'100%', minHeight:280, padding:14, fontSize:13, lineHeight:1.6, fontFamily:'var(--font-mono)', border:'1px solid var(--border)', borderRadius:'var(--r-4)', resize:'vertical'}}
              />
              <div style={{fontSize:11, color:'var(--text-muted)', marginTop:8}}>Поддерживается Markdown · Автосохранение каждые 30 секунд</div>
            </DCard>
          )}

          {contentTab === 'guides' && (
            <DCard title={`Гайды и видео · ${guides.length}`} action={<button className="btn btn-primary btn-sm"><IconPlus size={14}/> Новый гайд</button>}>
              <div style={{display:'grid', gap:8}}>
                {guides.map((g, i) => (
                  <div key={i} className="lift" style={{display:'flex', alignItems:'center', gap:14, padding:14, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-5)'}}>
                    <div style={{width:64, height:40, borderRadius:'var(--r-3)', background:`linear-gradient(135deg, ${['#6366F1','#10B981','#F59E0B','#6B7280'][i%4]}, #A855F7)`, flexShrink:0, display:'flex', alignItems:'center', justifyContent:'center'}}><IconBook size={18} style={{color:'#fff', opacity:0.9}}/></div>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontWeight:600, fontSize:14}}>{g.t}</div>
                      <div style={{fontSize:11, color:'var(--text-muted)', marginTop:2}}>{g.author} · {g.date} {g.status==='live' && `· ${fmtNum(g.views)} просмотров`}</div>
                    </div>
                    <span className={'badge ' + (g.status==='live'?'badge-success':'badge-warning')}>{g.status==='live'?'live':'draft'}</span>
                    <button className="btn btn-ghost btn-sm">Редактировать</button>
                  </div>
                ))}
              </div>
            </DCard>
          )}

          {contentTab === 'news' && (
            <DCard title={`Новости и блог · ${news.length}`} action={<button className="btn btn-primary btn-sm"><IconPlus size={14}/> Новый пост</button>}>
              <div style={{display:'grid', gap:10}}>
                {news.map((n,i) => (
                  <div key={i} className="lift" style={{display:'flex', gap:14, padding:14, background:'var(--surface)', border:'1px solid var(--border)', borderRadius:'var(--r-5)'}}>
                    <div style={{width:80, height:60, borderRadius:'var(--r-4)', background:n.img, flexShrink:0}}/>
                    <div style={{flex:1, minWidth:0}}>
                      <div style={{fontWeight:600, fontSize:14}}>{n.t}</div>
                      <div style={{fontSize:11, color:'var(--text-muted)', marginTop:4}}>Дата публикации: {n.date}</div>
                    </div>
                    <div style={{display:'flex', flexDirection:'column', alignItems:'flex-end', gap:6}}>
                      <span className={'badge ' + (n.status==='live'?'badge-success':n.status==='scheduled'?'badge-info':'badge-warning')}>
                        {n.status==='live'?'опубликовано':n.status==='scheduled'?'запланировано':'черновик'}
                      </span>
                      <button className="btn btn-ghost btn-sm">Редактировать</button>
                    </div>
                  </div>
                ))}
              </div>
            </DCard>
          )}

          {contentTab === 'forum' && (
            <DCard title={`Обсуждения · модерация`} action={<>
              <span className="badge" style={{background:'var(--warning-bg)', color:'#B45309'}}>2 на проверке</span>
              <button className="btn btn-secondary btn-sm">Правила сообщества</button>
            </>}>
              <div style={{display:'grid', gap:8}}>
                {forumPosts.map((p, i) => (
                  <div key={i} style={{padding:14, border:'1px solid var(--border)', borderRadius:'var(--r-5)', background: p.status==='flagged'?'var(--warning-bg)':'var(--surface)'}}>
                    <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:8}}>
                      <Avatar name={p.user} size={28} accent="var(--n-700)"/>
                      <div style={{flex:1}}>
                        <div style={{fontSize:13, fontWeight:600}}>{p.user}</div>
                        <div style={{fontSize:11, color:'var(--text-muted)'}}>{p.time}</div>
                      </div>
                      {p.status==='pinned' && <span className="badge badge-info">📌 закреплено</span>}
                      {p.status==='flagged' && <span className="badge badge-warning">⚠ жалоба</span>}
                    </div>
                    <div style={{fontSize:14, marginBottom:10}}>{p.txt}</div>
                    <div style={{display:'flex', alignItems:'center', gap:14, fontSize:12, color:'var(--text-muted)'}}>
                      <span>♥ {p.likes}</span>
                      <span>💬 {p.replies}</span>
                      <div style={{flex:1}}/>
                      <button className="btn btn-ghost btn-sm">Ответить от лица студии</button>
                      <button className="btn btn-ghost btn-sm">Закрепить</button>
                      <button className="btn btn-ghost btn-sm" style={{color:'var(--danger)'}}>Удалить</button>
                    </div>
                  </div>
                ))}
              </div>
            </DCard>
          )}
        </>
      )}

      {tab === 'settings' && (
        <>
          <DCard title="API-ключи" dense>
            <div style={{display:'grid', gap:10}}>
              {[['Test key', 'rev_test_8f4a92c1d6b3e7…', 'var(--warning-bg)', '#B45309'], ['Live key', 'rev_live_••••••••••••••', 'var(--success-bg)', '#047857']].map(([l,k,bg,c]) => (
                <div key={l} style={{display:'flex', alignItems:'center', gap:12, padding:12, background:bg, borderRadius:'var(--r-4)'}}>
                  <span className="badge" style={{background:'#fff', color:c, fontWeight:700}}>{l}</span>
                  <code style={{flex:1, fontFamily:'var(--font-mono)', fontSize:12, color:c}}>{k}</code>
                  <button className="btn btn-ghost btn-sm"><IconCopy size={14}/> Копировать</button>
                  <button className="btn btn-ghost btn-sm"><IconRefresh size={14}/> Перевыпустить</button>
                </div>
              ))}
            </div>
          </DCard>

          <DCard title="Webhook endpoint" dense action={<button className="btn btn-secondary btn-sm"><IconBolt size={14}/> Тестовый запрос</button>}>
            <div style={{display:'grid', gap:12}}>
              <div>
                <label style={{fontSize:12, fontWeight:600, color:'var(--text-soft)', display:'block', marginBottom:4}}>URL</label>
                <input className="input" defaultValue="https://api.nebulastudio.ru/revcut/webhook" style={{fontFamily:'var(--font-mono)', fontSize:12}}/>
              </div>
              <div>
                <label style={{fontSize:12, fontWeight:600, color:'var(--text-soft)', display:'block', marginBottom:4}}>Signing secret (HMAC-SHA256)</label>
                <div style={{display:'flex', gap:8}}>
                  <input className="input" defaultValue="whsec_••••••••••••••••••" style={{fontFamily:'var(--font-mono)', fontSize:12}}/>
                  <button className="btn btn-secondary btn-sm" style={{flexShrink:0}}><IconCopy size={14}/></button>
                  <button className="btn btn-secondary btn-sm" style={{flexShrink:0}}><IconRefresh size={14}/></button>
                </div>
              </div>
              <div>
                <label style={{fontSize:12, fontWeight:600, color:'var(--text-soft)', display:'block', marginBottom:8}}>События</label>
                <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                  {['purchase.completed','purchase.refunded','subscription.created','subscription.renewed','subscription.cancelled','subscription.grace','webhook.failed'].map(e => (
                    <label key={e} style={{display:'flex', alignItems:'center', gap:6, padding:'6px 10px', border:'1px solid var(--border)', borderRadius:'var(--r-full)', fontSize:12, cursor:'pointer'}}>
                      <input type="checkbox" defaultChecked={!e.includes('failed')} style={{accentColor:'var(--n-900)'}}/>
                      <code style={{fontFamily:'var(--font-mono)', fontSize:11}}>{e}</code>
                    </label>
                  ))}
                </div>
              </div>
            </div>
          </DCard>

          <DCard title="Опасная зона" dense style={{borderColor:'var(--danger-bg)'}}>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:12}}>
              <div>
                <div style={{fontSize:14, fontWeight:600}}>Удалить приложение</div>
                <div style={{fontSize:12, color:'var(--text-muted)', marginTop:2}}>Все продукты, транзакции и контент будут заархивированы. Активные подписки продолжат биллинг до конца периода.</div>
              </div>
              <button className="btn btn-destructive btn-sm">Архивировать</button>
            </div>
          </DCard>
        </>
      )}
    </DevShell>
  );
}

// ============== 12. DEV PRODUCTS (PROTO-13) ==============
function ScreenDevProducts({ goto, mobile }) {
  const [filter, setFilter] = uS_d3('all');
  const [editing, setEditing] = uS_d3(null);

  // Build flat product list across all games
  const products = uM_d3(()=>{
    const out = [];
    MOCK_GAMES.forEach(g => g.products.forEach(p => {
      const sales30d = Math.round(50 + Math.random()*1200);
      const rev30d = sales30d * p.price;
      out.push({
        sku: g.slug + '/' + p.id,
        game: g.title, gameSlug: g.slug, gameAccent: g.accent,
        name: p.name,
        type: p.type === 'sub' ? 'subscription' : 'consumable',
        price: p.price,
        period: p.period,
        status: 'active',
        sales30d, rev30d,
        badge: p.badge,
      });
    }));
    return out.sort((a,b) => b.rev30d - a.rev30d);
  }, []);

  const filtered = filter==='all' ? products : products.filter(p => p.type===filter);
  const stats = {
    total: products.length,
    consumable: products.filter(p=>p.type==='consumable').length,
    subscription: products.filter(p=>p.type==='subscription').length,
    activeSubs: 12_840,
  };

  return (
    <DevShell goto={goto} mobile={mobile} currentScreen="devProducts" title="Продукты">
      {/* Stat cards */}
      <div style={{display:'grid', gridTemplateColumns: mobile?'repeat(2,1fr)':'repeat(4,1fr)', gap:12, marginBottom:20}}>
        {[
          ['Всего продуктов', stats.total, ''],
          ['Топ-апы', stats.consumable, '+2 за неделю'],
          ['Подписки', stats.subscription, ''],
          ['Активных подписок', fmtNum(stats.activeSubs), '+412 за неделю'],
        ].map(([l,v,d]) => (
          <div key={l} className="card" style={{padding:14}}>
            <div className="kpi-label">{l}</div>
            <div className="kpi-value tnum" style={{margin:'4px 0', fontSize:22}}>{v}</div>
            {d && <div style={{fontSize:11, color:'var(--success)', fontWeight:600}}>{d}</div>}
          </div>
        ))}
      </div>

      {/* Toolbar */}
      <div style={{display:'flex', alignItems:'center', gap:10, marginBottom:14, flexWrap:'wrap'}}>
        <div style={{display:'flex', gap:4, padding:3, background:'var(--n-100)', borderRadius:'var(--r-4)'}}>
          {[['all','Все'],['consumable','Топ-апы'],['subscription','Подписки']].map(([id,l]) => (
            <button key={id} onClick={()=>setFilter(id)} style={{
              padding:'6px 14px', fontSize:13, fontWeight:600, borderRadius:'var(--r-3)',
              background: filter===id ? 'var(--surface)' : 'transparent',
              color: filter===id ? 'var(--text)' : 'var(--text-muted)',
              boxShadow: filter===id ? 'var(--shadow-sm)' : 'none',
            }}>{l}</button>
          ))}
        </div>
        <div style={{position:'relative', flex:'0 0 240px'}}>
          <IconSearch size={14} style={{position:'absolute', left:10, top:'50%', transform:'translateY(-50%)', color:'var(--text-muted)'}}/>
          <input className="input" placeholder="Поиск по SKU или названию" style={{paddingLeft:32, fontSize:13}}/>
        </div>
        <select className="input" style={{maxWidth:160, fontSize:13}}>
          <option>Все приложения</option>
          {MOCK_GAMES.slice(0,5).map(g => <option key={g.slug}>{g.title}</option>)}
        </select>
        <div style={{flex:1}}/>
        <button className="btn btn-secondary btn-sm"><IconUpload size={14}/> Импорт CSV</button>
        <button className="btn btn-primary btn-sm" onClick={()=>setEditing({})}><IconPlus size={14}/> Новый продукт</button>
      </div>

      {/* Products table */}
      <div className="card" style={{overflow:'hidden', padding:0}}>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead>
            <tr style={{background:'var(--n-50)', borderBottom:'1px solid var(--border)'}}>
              {['SKU','Продукт','Тип','Цена','Продажи (30д)','Выручка (30д)','Статус',''].map(h => (
                <th key={h} style={{padding:'10px 14px', textAlign:'left', fontSize:11, fontWeight:600, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {filtered.slice(0, 14).map((p, i) => (
              <tr key={p.sku} style={{borderBottom: i<filtered.length-1?'1px solid var(--border)':'none', cursor:'pointer'}} onClick={()=>setEditing(p)} className="lift">
                <td style={{padding:'12px 14px', fontFamily:'var(--font-mono)', fontSize:11, color:'var(--text-soft)'}}>{p.sku}</td>
                <td style={{padding:'12px 14px'}}>
                  <div style={{display:'flex', alignItems:'center', gap:10}}>
                    <div style={{width:28, height:28, borderRadius:6, background: p.gameAccent, color:'#fff', fontSize:10, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>
                      {p.game.split(' ').map(s=>s[0]).slice(0,2).join('')}
                    </div>
                    <div>
                      <div style={{fontWeight:600}}>{p.name}</div>
                      <div style={{fontSize:11, color:'var(--text-muted)'}}>{p.game}</div>
                    </div>
                  </div>
                </td>
                <td style={{padding:'12px 14px'}}>
                  <span className={'badge ' + (p.type==='subscription'?'badge-info':'')}>
                    {p.type==='subscription' ? `подписка · ${p.period}` : 'топ-ап'}
                  </span>
                </td>
                <td style={{padding:'12px 14px', fontWeight:600}} className="tnum">{fmt(p.price)}</td>
                <td style={{padding:'12px 14px'}} className="tnum">{fmtNum(p.sales30d)}</td>
                <td style={{padding:'12px 14px', fontWeight:600}} className="tnum">{fmt(p.rev30d)}</td>
                <td style={{padding:'12px 14px'}}><span className="badge badge-success">{p.status}</span></td>
                <td style={{padding:'12px 14px'}}><IconChevR size={14} style={{color:'var(--text-muted)'}}/></td>
              </tr>
            ))}
          </tbody>
        </table>
        <div style={{padding:'10px 14px', borderTop:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between', fontSize:12, color:'var(--text-muted)'}}>
          <span>Показано 14 из {filtered.length}</span>
          <div style={{display:'flex', gap:4}}>
            <button className="btn btn-ghost btn-sm" disabled style={{opacity:0.4}}><IconChevL size={12}/></button>
            <button className="btn btn-secondary btn-sm">1</button>
            <button className="btn btn-ghost btn-sm">2</button>
            <button className="btn btn-ghost btn-sm">3</button>
            <button className="btn btn-ghost btn-sm"><IconChevR size={12}/></button>
          </div>
        </div>
      </div>

      {/* Entitlements section */}
      <div style={{marginTop:24}}>
        <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:12}}>
          <h3 className="display" style={{fontSize:16, fontWeight:700, margin:0}}>Entitlements</h3>
          <button className="btn btn-secondary btn-sm"><IconPlus size={14}/> Новый entitlement</button>
        </div>
        <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(3,1fr)', gap:12}}>
          {[
            { id:'premium', label:'Premium', desc:'Полный доступ к контенту', plans: ['Premium 1 мес', 'Premium 1 год'] },
            { id:'no-ads', label:'No Ads', desc:'Отключение рекламы', plans: ['Без рекламы', 'Premium 1 год'] },
            { id:'season-pass', label:'Season Pass', desc:'Сезонная награда', plans: ['Боевой пропуск'] },
          ].map(e => (
            <div key={e.id} className="card" style={{padding:14}}>
              <code style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--info)'}}>{e.id}</code>
              <div style={{fontSize:14, fontWeight:600, margin:'4px 0'}}>{e.label}</div>
              <div style={{fontSize:12, color:'var(--text-muted)', marginBottom:10}}>{e.desc}</div>
              <div style={{display:'flex', flexWrap:'wrap', gap:4}}>
                {e.plans.map(p => <span key={p} className="badge" style={{fontSize:10}}>{p}</span>)}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Edit drawer */}
      {editing && (
        <div onClick={()=>setEditing(null)} style={{position:'fixed', inset:0, background:'rgba(15, 23, 42, 0.4)', zIndex:50}}>
          <div onClick={e=>e.stopPropagation()} style={{position:'absolute', right:0, top:0, bottom:0, width:mobile?'100%':480, background:'var(--surface)', boxShadow:'var(--shadow-xl)', overflowY:'auto'}}>
            <header style={{padding:'18px 20px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between', position:'sticky', top:0, background:'var(--surface)', zIndex:1}}>
              <div>
                <div style={{fontSize:11, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em', fontWeight:600}}>{editing.sku ? 'Редактирование' : 'Новый продукт'}</div>
                <h3 className="display" style={{fontSize:18, fontWeight:700, margin:'2px 0 0'}}>{editing.name || 'Продукт без названия'}</h3>
              </div>
              <button className="btn btn-ghost btn-sm" onClick={()=>setEditing(null)}><IconX size={16}/></button>
            </header>
            <div style={{padding:20, display:'grid', gap:16}}>
              <div>
                <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>SKU</label>
                <input className="input" defaultValue={editing.sku} style={{fontFamily:'var(--font-mono)'}}/>
              </div>
              <div>
                <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>Название</label>
                <input className="input" defaultValue={editing.name}/>
              </div>
              <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
                <div>
                  <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>Тип</label>
                  <select className="input" defaultValue={editing.type}>
                    <option value="consumable">Расходуемый</option>
                    <option value="non-consumable">Постоянный</option>
                    <option value="subscription">Подписка</option>
                  </select>
                </div>
                <div>
                  <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>Цена ₽</label>
                  <input className="input" defaultValue={editing.price} type="number"/>
                </div>
              </div>
              {editing.type==='subscription' && (
                <div style={{padding:14, background:'var(--info-bg)', borderRadius:'var(--r-4)', display:'grid', gap:12}}>
                  <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:12}}>
                    <div>
                      <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6, color:'#1D4ED8'}}>Период</label>
                      <select className="input"><option>Неделя</option><option>Месяц</option><option>3 месяца</option><option>Год</option></select>
                    </div>
                    <div>
                      <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6, color:'#1D4ED8'}}>Trial</label>
                      <select className="input"><option>Нет</option><option>3 дня</option><option>7 дней</option><option>14 дней</option><option>30 дней</option></select>
                    </div>
                  </div>
                  <div>
                    <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6, color:'#1D4ED8'}}>Grace period</label>
                    <select className="input"><option>3 дня</option><option>7 дней</option><option>16 дней</option></select>
                  </div>
                </div>
              )}
              <div>
                <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>Описание</label>
                <textarea className="input" rows={3} placeholder="Описание для покупателя…"/>
              </div>
              <div>
                <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>Локализация</label>
                <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
                  {['🇷🇺 ru','🇬🇧 en','🇰🇿 kk','🇧🇾 be'].map(l => (
                    <button key={l} className="btn btn-secondary btn-sm">{l}</button>
                  ))}
                  <button className="btn btn-ghost btn-sm"><IconPlus size={12}/> Добавить</button>
                </div>
              </div>
              <div>
                <label style={{fontSize:12, fontWeight:600, display:'block', marginBottom:6}}>A/B-тест цены <span className="badge badge-warning" style={{marginLeft:8, fontSize:10}}>скоро</span></label>
                <div style={{padding:12, background:'var(--n-50)', border:'1px dashed var(--border-strong)', borderRadius:'var(--r-4)', fontSize:12, color:'var(--text-muted)', textAlign:'center'}}>
                  Запустите эксперимент — мы покажем цены {fmt(editing.price||0)} и {fmt((editing.price||0)*1.15)} разным сегментам и посчитаем uplift.
                </div>
              </div>
            </div>
            <footer style={{padding:'16px 20px', borderTop:'1px solid var(--border)', display:'flex', gap:8, justifyContent:'flex-end', position:'sticky', bottom:0, background:'var(--surface)'}}>
              <button className="btn btn-ghost btn-sm" onClick={()=>setEditing(null)}>Отмена</button>
              <button className="btn btn-primary btn-sm">Сохранить</button>
            </footer>
          </div>
        </div>
      )}
    </DevShell>
  );
}

// ============== 13. DEV PAYMENTS / SETTLEMENTS (PROTO-14a, split-acquiring model) ==============
// Split-эквайринг: ЮKassa делит платёж — 95% сразу на счёт разработчика, 5% нам как комиссия.
// Никаких hold-back, никакого баланса у нас. Этот экран — сводка по поступлениям и комиссиям.
function ScreenDevPayouts({ goto, mobile }) {
  // 30-day rollup — based on MOCK_ANALYTICS (8.14M ₽ GMV)
  const period = {
    gmv:           8_142_000,
    yuKassaFee:    8_142_000 * 0.029,   // 2.9% эквайринг ЮKassa
    revcutFee:     8_142_000 * 0.025,   // 2.5% наша
    toDeveloper:   8_142_000 * (1 - 0.029 - 0.025),   // 94.6%
  };
  const yesterdayPayout = 268_400;     // последнее поступление от ЮKassa T+1
  const inTransit       = 312_500;     // авторизовано вчера, дойдёт сегодня

  // Daily settlement breakdown (last 7 days)
  const settlements = [
    { date: '03 мая', gmv: 312_500,  toDev: 295_625,  ours: 7_812,  acquirer: 9_063,  status: 'in_transit' },
    { date: '02 мая', gmv: 268_400,  toDev: 253_906,  ours: 6_710,  acquirer: 7_784,  status: 'settled',   bankRef: 'OP-87234' },
    { date: '01 мая', gmv: 294_180,  toDev: 278_294,  ours: 7_354,  acquirer: 8_531,  status: 'settled',   bankRef: 'OP-86952' },
    { date: '30 апр', gmv: 281_900,  toDev: 266_677,  ours: 7_047,  acquirer: 8_175,  status: 'settled',   bankRef: 'OP-86741' },
    { date: '29 апр', gmv: 256_320,  toDev: 242_478,  ours: 6_408,  acquirer: 7_433,  status: 'settled',   bankRef: 'OP-86508' },
    { date: '28 апр', gmv: 312_440,  toDev: 295_584,  ours: 7_811,  acquirer: 9_060,  status: 'settled',   bankRef: 'OP-86291' },
    { date: '27 апр', gmv: 287_650,  toDev: 272_115,  ours: 7_191,  acquirer: 8_341,  status: 'settled',   bankRef: 'OP-85968' },
  ];

  return (
    <DevShell goto={goto} mobile={mobile} currentScreen="devPayouts" title="Поступления">
      {/* Top banner — explains split model */}
      <div className="card" style={{padding:18, marginBottom:20, background:'linear-gradient(135deg, #ECFDF5, #F0FDF4)', border:'1px solid #BBF7D0'}}>
        <div style={{display:'flex', alignItems:'flex-start', gap:14}}>
          <div style={{width:36, height:36, borderRadius:'50%', background:'var(--success)', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}><IconCheck size={20}/></div>
          <div style={{flex:1}}>
            <div style={{fontWeight:700, fontSize:15, color:'#065F46', marginBottom:4}}>Деньги поступают вам напрямую</div>
            <div style={{fontSize:13, color:'#047857', lineHeight:1.5}}>
              ЮKassa автоматически делит каждый платёж: <b>94,6% мгновенно идёт на ваш счёт</b>, 2,5% — наша комиссия,
              2,9% — эквайринг. Срок зачисления — T+1 рабочий день. Мы не удерживаем ваши средства и не делаем hold-back —
              он не нужен в split-модели, риск чарджбэков делится пропорционально.
            </div>
          </div>
        </div>
      </div>

      {/* Period summary cards */}
      <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(4, 1fr)', gap:12, marginBottom:24}}>
        <div className="card" style={{padding:20, background:'linear-gradient(135deg, var(--n-900), var(--n-800))', color:'#fff', border:'none'}}>
          <div style={{fontSize:12, color:'rgba(255,255,255,0.7)', fontWeight:500}}>На ваш счёт за 30 дней</div>
          <div className="display tnum" style={{fontSize:30, fontWeight:700, margin:'8px 0', letterSpacing:'-0.02em'}}>{fmt(period.toDeveloper)}</div>
          <div style={{fontSize:11, color:'rgba(255,255,255,0.6)'}}>94,6% от GMV · напрямую от ЮKassa</div>
        </div>
        <div className="card" style={{padding:20}}>
          <div className="kpi-label">Наша комиссия</div>
          <div className="kpi-value tnum" style={{margin:'8px 0', fontSize:26}}>{fmt(period.revcutFee)}</div>
          <div style={{fontSize:11, color:'var(--text-muted)'}}>2,5% · по тарифу Pro</div>
        </div>
        <div className="card" style={{padding:20}}>
          <div className="kpi-label">Эквайринг ЮKassa</div>
          <div className="kpi-value tnum" style={{margin:'8px 0', fontSize:26}}>{fmt(period.yuKassaFee)}</div>
          <div style={{fontSize:11, color:'var(--text-muted)'}}>2,9% · по договору с банком</div>
        </div>
        <div className="card" style={{padding:20}}>
          <div className="kpi-label" style={{display:'flex', alignItems:'center', gap:6}}>В пути <IconClock size={12}/></div>
          <div className="kpi-value tnum" style={{margin:'8px 0', fontSize:26}}>{fmt(inTransit)}</div>
          <div style={{fontSize:11, color:'var(--text-muted)'}}>Авторизовано · зачислится сегодня к 18:00</div>
        </div>
      </div>

      {/* Visual split breakdown */}
      <DCard title="Как делится каждый рубль" dense>
        <div style={{display:'flex', height:48, borderRadius:'var(--r-5)', overflow:'hidden', marginBottom:14}}>
          <div style={{flex:94.6, background:'var(--success)', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:700, fontSize:14}}>94,6% → вам</div>
          <div style={{flex:2.5, background:'var(--brand-500)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--n-900)', fontWeight:700, fontSize:11}}>2,5%</div>
          <div style={{flex:2.9, background:'var(--n-700)', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:700, fontSize:11}}>2,9%</div>
        </div>
        <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(3,1fr)', gap:12, fontSize:12}}>
          <div style={{display:'flex', gap:8, alignItems:'center'}}><span style={{width:10, height:10, background:'var(--success)', borderRadius:2}}/><span><b>94,6%</b> — на ваш расчётный счёт мгновенно</span></div>
          <div style={{display:'flex', gap:8, alignItems:'center'}}><span style={{width:10, height:10, background:'var(--brand-500)', borderRadius:2}}/><span><b>2,5%</b> — комиссия revCUT (тариф Pro)</span></div>
          <div style={{display:'flex', gap:8, alignItems:'center'}}><span style={{width:10, height:10, background:'var(--n-700)', borderRadius:2}}/><span><b>2,9%</b> — эквайринг ЮKassa</span></div>
        </div>
      </DCard>

      {/* Bank details (reference) */}
      <DCard title="Куда поступают деньги" dense action={<button className="btn btn-secondary btn-sm">Изменить в ЮKassa</button>}>
        <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr', gap:16, fontSize:13}}>
          <div><div style={{fontSize:12, color:'var(--text-muted)', marginBottom:4}}>Получатель</div><div style={{fontWeight:600}}>ООО «Небьюла Студио»</div></div>
          <div><div style={{fontSize:12, color:'var(--text-muted)', marginBottom:4}}>ИНН</div><div style={{fontFamily:'var(--font-mono)'}}>7707083893</div></div>
          <div><div style={{fontSize:12, color:'var(--text-muted)', marginBottom:4}}>Банк</div><div style={{fontWeight:600}}>АО «Тинькофф Банк»</div></div>
          <div><div style={{fontSize:12, color:'var(--text-muted)', marginBottom:4}}>Расчётный счёт</div><div style={{fontFamily:'var(--font-mono)'}}>40702 ••• ••• ••• 4221</div></div>
        </div>
        <div style={{marginTop:12, padding:10, background:'var(--n-50)', borderRadius:'var(--r-3)', fontSize:11, color:'var(--text-muted)'}}>
          Реквизиты управляются в личном кабинете ЮKassa. Мы только показываем их для справки.
        </div>
      </DCard>

      {/* Daily settlements table */}
      <div className="card" style={{overflow:'hidden', padding:0}}>
        <header style={{padding:'14px 20px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between', flexWrap:'wrap', gap:8}}>
          <div>
            <h3 className="display" style={{fontSize:15, fontWeight:700, margin:0}}>Сводка по дням</h3>
            <div style={{fontSize:12, color:'var(--text-muted)', marginTop:2}}>Каждая строка — выписка от ЮKassa, что было разделено и зачислено</div>
          </div>
          <button className="btn btn-secondary btn-sm"><IconDownload size={14}/> CSV для бухгалтерии</button>
        </header>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead>
            <tr style={{background:'var(--n-50)', borderBottom:'1px solid var(--border)'}}>
              {['Дата','GMV','На ваш счёт (94,6%)','Наша комиссия (2,5%)','Эквайринг (2,9%)','Статус','Платёжка'].map(h => (
                <th key={h} style={{padding:'10px 14px', textAlign:'left', fontSize:11, fontWeight:600, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {settlements.map((s,i) => (
              <tr key={s.date} style={{borderBottom: i<settlements.length-1?'1px solid var(--border)':'none'}}>
                <td style={{padding:'12px 14px', fontWeight:600}}>{s.date}</td>
                <td style={{padding:'12px 14px'}} className="tnum">{fmt(s.gmv)}</td>
                <td style={{padding:'12px 14px', fontWeight:700, color:'var(--success)'}} className="tnum">{fmt(s.toDev)}</td>
                <td style={{padding:'12px 14px'}} className="tnum">{fmt(s.ours)}</td>
                <td style={{padding:'12px 14px', color:'var(--text-soft)'}} className="tnum">{fmt(s.acquirer)}</td>
                <td style={{padding:'12px 14px'}}>
                  <span className={'badge ' + (s.status==='settled'?'badge-success':'badge-warning')}>
                    {s.status==='settled'?'зачислено T+1':'в пути'}
                  </span>
                </td>
                <td style={{padding:'12px 14px', fontFamily:'var(--font-mono)', fontSize:11, color:'var(--text-soft)'}}>{s.bankRef || '—'}</td>
              </tr>
            ))}
          </tbody>
        </table>
        <div style={{padding:'10px 14px', background:'var(--n-50)', borderTop:'1px solid var(--border)', display:'flex', justifyContent:'space-between', fontSize:12}}>
          <span style={{color:'var(--text-muted)'}}>Сумма за 7 дней</span>
          <div style={{display:'flex', gap:24}}>
            <span><span style={{color:'var(--text-muted)'}}>GMV: </span><b className="tnum">{fmt(settlements.reduce((a,s)=>a+s.gmv,0))}</b></span>
            <span><span style={{color:'var(--text-muted)'}}>Вам: </span><b className="tnum" style={{color:'var(--success)'}}>{fmt(settlements.reduce((a,s)=>a+s.toDev,0))}</b></span>
            <span><span style={{color:'var(--text-muted)'}}>Нам: </span><b className="tnum">{fmt(settlements.reduce((a,s)=>a+s.ours,0))}</b></span>
          </div>
        </div>
      </div>

      {/* Refunds note */}
      <DCard dense title="А что с возвратами и чарджбэками?" style={{marginTop:16, background:'var(--info-bg)', border:'1px solid #BFDBFE'}}>
        <div style={{fontSize:13, lineHeight:1.6, color:'#1E3A8A'}}>
          При возврате или chargeback ЮKassa автоматически списывает средства <b>пропорционально с обоих счетов</b>:
          с вашего счёта возвращается 94,6% суммы, с нашего — 2,5%, эквайринг возвращает свои 2,9%. Поэтому hold-back
          не нужен — риск размазан по сторонам сделки. Возвраты отражаются в <a href="#" style={{color:'inherit', textDecoration:'underline'}}>истории транзакций</a>.
        </div>
      </DCard>
    </DevShell>
  );
}

// ============== 14. DEV WEBHOOKS (PROTO-14b) ==============
function ScreenDevWebhooks({ goto, mobile }) {
  const stats = MOCK_ANALYTICS.webhooks;
  const events = ['purchase.completed','subscription.renewed','subscription.created','purchase.refunded','subscription.cancelled','subscription.grace'];
  const deliveries = Array.from({length:14}, (_,i) => {
    const s = Math.random();
    return {
      id: 'evt_' + Math.random().toString(36).slice(2,10),
      ts: `12:${String(57-i*2).padStart(2,'0')}:${String(Math.floor(Math.random()*60)).padStart(2,'0')}`,
      event: events[Math.floor(Math.random()*events.length)],
      status: s > 0.92 ? 'failed' : s > 0.85 ? 'retrying' : 'delivered',
      latency: Math.floor(50 + Math.random()*350),
      attempts: s > 0.92 ? 3 : s > 0.85 ? 2 : 1,
      response: s > 0.92 ? '500 Internal Error' : '200 OK',
    };
  });

  return (
    <DevShell goto={goto} mobile={mobile} currentScreen="devWebhooks" title="Webhooks">
      <div style={{display:'grid', gridTemplateColumns: mobile?'repeat(2,1fr)':'repeat(4,1fr)', gap:12, marginBottom:24}}>
        <div className="card" style={{padding:16}}>
          <div className="kpi-label">Доставлено успешно</div>
          <div className="kpi-value tnum" style={{margin:'4px 0', fontSize:24, color:'var(--success)'}}>{stats.delivered}%</div>
          <div style={{fontSize:11, color:'var(--text-muted)'}}>За 24 ч · 47 320 событий</div>
        </div>
        <div className="card" style={{padding:16}}>
          <div className="kpi-label">P95 latency</div>
          <div className="kpi-value tnum" style={{margin:'4px 0', fontSize:24}}>{stats.p95} мс</div>
          <div style={{fontSize:11, color:'var(--success)', fontWeight:600}}>−18 мс</div>
        </div>
        <div className="card" style={{padding:16}}>
          <div className="kpi-label">Retry rate</div>
          <div className="kpi-value tnum" style={{margin:'4px 0', fontSize:24}}>{stats.retryRate}%</div>
          <div style={{fontSize:11, color:'var(--text-muted)'}}>Норма &lt; 3%</div>
        </div>
        <div className="card" style={{padding:16}}>
          <div className="kpi-label">Failed (24 ч)</div>
          <div className="kpi-value tnum" style={{margin:'4px 0', fontSize:24, color:'var(--danger)'}}>76</div>
          <div style={{fontSize:11, color:'var(--text-muted)'}}>76 будут перезапущены</div>
        </div>
      </div>

      <DCard title="Endpoint" action={<button className="btn btn-secondary btn-sm"><IconBolt size={14}/> Тестовый запрос</button>}>
        <div style={{display:'flex', alignItems:'center', gap:12, padding:14, background:'var(--n-50)', borderRadius:'var(--r-4)', marginBottom:12}}>
          <span className="badge badge-success" style={{fontWeight:700}}>POST</span>
          <code style={{flex:1, fontFamily:'var(--font-mono)', fontSize:13, fontWeight:600}}>https://api.nebulastudio.ru/revcut/webhook</code>
          <button className="btn btn-ghost btn-sm"><IconCopy size={14}/></button>
          <button className="btn btn-ghost btn-sm">Изменить</button>
        </div>
        <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(2,1fr)', gap:16}}>
          <div>
            <div style={{fontSize:12, color:'var(--text-muted)', marginBottom:6}}>Подписи</div>
            <div style={{fontSize:13, fontFamily:'var(--font-mono)'}}>HMAC-SHA256, header <code>X-RevCut-Signature</code></div>
          </div>
          <div>
            <div style={{fontSize:12, color:'var(--text-muted)', marginBottom:6}}>Retry policy</div>
            <div style={{fontSize:13}}>Exponential backoff: 1s → 4s → 16s → 1m → 5m → 30m → 2h (7 попыток)</div>
          </div>
        </div>
      </DCard>

      <DCard title="Подписанные события" dense>
        <div style={{display:'flex', flexWrap:'wrap', gap:6}}>
          {events.concat(['webhook.failed','user.churned']).map(e => (
            <span key={e} style={{padding:'5px 10px', background: e.includes('failed')?'var(--n-100)':'var(--success-bg)', color:e.includes('failed')?'var(--text-muted)':'#047857', fontSize:12, fontFamily:'var(--font-mono)', fontWeight:600, borderRadius:'var(--r-full)'}}>{e}</span>
          ))}
        </div>
      </DCard>

      {/* Test panel */}
      <DCard title="Тестовый webhook" dense style={{background:'var(--info-bg)', border:'1px solid #BFDBFE'}}>
        <div style={{display:'flex', gap:12, alignItems:'center', flexWrap:'wrap'}}>
          <span style={{fontSize:13, color:'#1E3A8A'}}>Отправить событие</span>
          <select className="input" style={{maxWidth:240, fontSize:13}}>{events.map(e=> <option key={e}>{e}</option>)}</select>
          <button className="btn btn-primary btn-sm"><IconBolt size={14}/> Отправить</button>
          <div style={{flex:1}}/>
          <span className="badge badge-success">200 OK · 84 мс</span>
        </div>
      </DCard>

      {/* Recent deliveries */}
      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <header style={{padding:'14px 20px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <h3 className="display" style={{fontSize:15, fontWeight:700, margin:0}}>Последние доставки</h3>
          <div style={{display:'flex', gap:6}}>
            <select className="input" style={{maxWidth:160, fontSize:12}}>
              <option>Все события</option>
              {events.map(e => <option key={e}>{e}</option>)}
            </select>
            <select className="input" style={{maxWidth:140, fontSize:12}}>
              <option>Все статусы</option>
              <option>delivered</option>
              <option>retrying</option>
              <option>failed</option>
            </select>
          </div>
        </header>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:12}}>
          <thead>
            <tr style={{background:'var(--n-50)', borderBottom:'1px solid var(--border)'}}>
              {['Время','Event ID','Тип','Статус','Latency','Попытки','Response',''].map(h => (
                <th key={h} style={{padding:'10px 14px', textAlign:'left', fontSize:11, fontWeight:600, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {deliveries.map((d,i) => (
              <tr key={d.id} style={{borderBottom: i<deliveries.length-1?'1px solid var(--border)':'none'}}>
                <td style={{padding:'10px 14px', fontFamily:'var(--font-mono)'}}>{d.ts}</td>
                <td style={{padding:'10px 14px', fontFamily:'var(--font-mono)', color:'var(--info)'}}>{d.id}</td>
                <td style={{padding:'10px 14px', fontFamily:'var(--font-mono)'}}>{d.event}</td>
                <td style={{padding:'10px 14px'}}>
                  <span className={'badge ' + (d.status==='delivered'?'badge-success':d.status==='retrying'?'badge-warning':'badge-danger')}>{d.status}</span>
                </td>
                <td style={{padding:'10px 14px'}} className="tnum">{d.latency} мс</td>
                <td style={{padding:'10px 14px'}} className="tnum">{d.attempts}</td>
                <td style={{padding:'10px 14px', fontFamily:'var(--font-mono)', color: d.response.startsWith('200')?'var(--success)':'var(--danger)'}}>{d.response}</td>
                <td style={{padding:'10px 14px', display:'flex', gap:4}}>
                  <button className="btn btn-ghost btn-sm" title="Replay"><IconRefresh size={14}/></button>
                  <button className="btn btn-ghost btn-sm" title="Подробнее"><IconChevR size={14}/></button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </DevShell>
  );
}

// ============== 15. DEV BILLING (PROTO-14c) ==============
function ScreenDevBilling({ goto, mobile }) {
  const usage = { gmvThisMonth: 8_142_000, included: 1_000_000 };
  const usagePct = Math.min(100, (usage.gmvThisMonth / 50_000_000) * 100);

  const plans = [
    { id:'free',  name:'Free',       price:'0 ₽', fee:'2,5–7%', desc:'Для проб и индивидуальных разработчиков',  active: false, features:['До 1 М ₽ GMV/мес', 'Все базовые фичи', 'Базовые webhooks', 'Email-поддержка'] },
    { id:'pro',   name:'Pro',        price:'9 900 ₽', fee:'2,5%', desc:'Для растущих студий — текущий план', active: true,  features:['Безлимитный GMV', 'Все базовые фичи', 'Расширенная аналитика', 'Slack/Telegram-поддержка'], badge:'текущий'},
    { id:'scale', name:'Scale',      price:'49 000 ₽', fee:'1,8%', desc:'Для студий с MAU 100К+', active: false, features:['Безлимитный GMV', 'A/B-эксперименты ценой', 'Cohort retention', 'Dedicated CSM', 'SLA 99.95%'] },
    { id:'ent',   name:'Enterprise', price:'от 200 К ₽', fee:'flat', desc:'Custom условия для крупных издателей', active: false, features:['White-label', 'On-prem опционально', 'Custom integrations', '24/7 поддержка', 'SLA 99.99%'] },
  ];

  const invoices = [
    { id:'inv_2026_05', date:'01 мая', amount: 9_900,  status:'paid' },
    { id:'inv_2026_04', date:'01 апр', amount: 9_900,  status:'paid' },
    { id:'inv_2026_03', date:'01 мар', amount: 9_900,  status:'paid' },
    { id:'inv_2026_02', date:'01 фев', amount: 9_900,  status:'paid' },
  ];

  return (
    <DevShell goto={goto} mobile={mobile} currentScreen="devBilling" title="Тариф и биллинг">
      {/* Current plan */}
      <DCard title="Текущий тариф" action={<button className="btn btn-primary btn-sm">Перейти на Scale</button>}>
        <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr', gap:24, alignItems:'start'}}>
          <div>
            <div style={{display:'flex', alignItems:'center', gap:12, marginBottom:8}}>
              <span className="display" style={{fontSize:32, fontWeight:800, letterSpacing:'-0.02em'}}>Pro</span>
              <span className="badge badge-brand" style={{fontSize:11}}>активен</span>
            </div>
            <div style={{fontSize:14, color:'var(--text-soft)', marginBottom:16}}>9 900 ₽/мес + 2,5% комиссия с GMV</div>
            <div style={{display:'grid', gap:8, fontSize:13}}>
              {['Безлимитный объём GMV', 'Все базовые фичи и SDK', 'Расширенная аналитика (cohort, funnel, MRR Movement)', 'Slack/Telegram-поддержка от 6 минут'].map((f,i) => (
                <div key={i} style={{display:'flex', alignItems:'center', gap:8}}>
                  <IconCheck size={14} style={{color:'var(--success)', flexShrink:0}}/>
                  {f}
                </div>
              ))}
            </div>
          </div>
          <div>
            <div style={{fontSize:13, color:'var(--text-muted)', marginBottom:6}}>GMV за май (текущий месяц)</div>
            <div className="display tnum" style={{fontSize:28, fontWeight:700, marginBottom:10}}>{fmt(usage.gmvThisMonth)}</div>
            <div style={{height:8, background:'var(--n-100)', borderRadius:'var(--r-full)', overflow:'hidden', marginBottom:6}}>
              <div style={{height:'100%', width:`${usagePct}%`, background:'linear-gradient(90deg, var(--brand-500), var(--brand-600))', borderRadius:'var(--r-full)'}}/>
            </div>
            <div style={{fontSize:11, color:'var(--text-muted)', display:'flex', justifyContent:'space-between'}}>
              <span>0 ₽</span><span>50 М ₽ — следующий тир</span>
            </div>
            <div style={{marginTop:18, padding:12, background:'var(--n-50)', borderRadius:'var(--r-4)', fontSize:12}}>
              <div style={{fontWeight:600, marginBottom:4}}>Прогноз счёта на июнь</div>
              <div style={{display:'flex', justifyContent:'space-between'}}><span>Подписка</span><span className="tnum">9 900 ₽</span></div>
              <div style={{display:'flex', justifyContent:'space-between'}}><span>Комиссия с GMV (2,5% × 8,1М)</span><span className="tnum">203 550 ₽</span></div>
              <div style={{display:'flex', justifyContent:'space-between', fontWeight:700, paddingTop:6, marginTop:6, borderTop:'1px dashed var(--border)'}}><span>Итого</span><span className="tnum">213 450 ₽</span></div>
            </div>
          </div>
        </div>
      </DCard>

      {/* Plan comparison */}
      <h3 className="display" style={{fontSize:18, fontWeight:700, margin:'24px 0 12px', letterSpacing:'-0.01em'}}>Все тарифы</h3>
      <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(4,1fr)', gap:12, marginBottom:24}}>
        {plans.map(p => (
          <div key={p.id} className="card" style={{padding:20, position:'relative', border: p.active ? '2px solid var(--n-900)' : '1px solid var(--border)'}}>
            {p.active && <span style={{position:'absolute', top:-8, right:14, background:'var(--n-900)', color:'#fff', fontSize:10, fontWeight:700, padding:'3px 9px', borderRadius:'var(--r-full)', textTransform:'uppercase', letterSpacing:'0.05em'}}>текущий</span>}
            <div className="display" style={{fontSize:20, fontWeight:800, letterSpacing:'-0.02em'}}>{p.name}</div>
            <div style={{fontSize:12, color:'var(--text-muted)', marginTop:6, minHeight:32}}>{p.desc}</div>
            <div style={{margin:'14px 0 6px', display:'flex', alignItems:'baseline', gap:6}}>
              <span className="display tnum" style={{fontSize:24, fontWeight:700}}>{p.price}</span>
              <span style={{fontSize:11, color:'var(--text-muted)'}}>/мес</span>
            </div>
            <div style={{fontSize:13, fontWeight:600, color:'var(--brand-700)', marginBottom:14}}>+ {p.fee} с GMV</div>
            <button className={'btn btn-sm ' + (p.active ? 'btn-secondary' : 'btn-primary')} style={{width:'100%', marginBottom:14}} disabled={p.active}>
              {p.active ? 'Активный' : (p.id==='ent'?'Связаться':p.id==='free'?'Понизить':'Обновить')}
            </button>
            <div style={{display:'grid', gap:6, fontSize:12}}>
              {p.features.map((f,i) => (
                <div key={i} style={{display:'flex', alignItems:'flex-start', gap:6}}>
                  <IconCheck size={12} style={{color:'var(--success)', flexShrink:0, marginTop:2}}/>
                  <span>{f}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      {/* Invoices */}
      <div className="card" style={{padding:0, overflow:'hidden'}}>
        <header style={{padding:'14px 20px', borderBottom:'1px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
          <h3 className="display" style={{fontSize:15, fontWeight:700, margin:0}}>История счетов от revCUT</h3>
          <button className="btn btn-secondary btn-sm"><IconDownload size={14}/> Все PDF</button>
        </header>
        <table style={{width:'100%', borderCollapse:'collapse', fontSize:13}}>
          <thead>
            <tr style={{background:'var(--n-50)', borderBottom:'1px solid var(--border)'}}>
              {['№','Дата','Сумма','Статус',''].map(h => (
                <th key={h} style={{padding:'10px 14px', textAlign:'left', fontSize:11, fontWeight:600, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {invoices.map((inv, i) => (
              <tr key={inv.id} style={{borderBottom: i<invoices.length-1?'1px solid var(--border)':'none'}}>
                <td style={{padding:'12px 14px', fontFamily:'var(--font-mono)', fontSize:11, color:'var(--text-soft)'}}>{inv.id}</td>
                <td style={{padding:'12px 14px'}}>{inv.date}</td>
                <td style={{padding:'12px 14px', fontWeight:600}} className="tnum">{fmt(inv.amount)}</td>
                <td style={{padding:'12px 14px'}}><span className="badge badge-success">оплачено</span></td>
                <td style={{padding:'12px 14px'}}>
                  <button className="btn btn-ghost btn-sm"><IconDownload size={14}/> PDF</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </DevShell>
  );
}

// Settings shortcut: redirect to Apps→Settings (just for sidebar completeness)
function ScreenDevSettings(props) {
  return <ScreenDevApps {...props} />;
}

Object.assign(window, {
  ScreenDevApps, ScreenDevProducts, ScreenDevPayouts, ScreenDevWebhooks, ScreenDevBilling, ScreenDevSettings
});
