// Dev Portal screens: Landing, Onboarding, Dashboard, Transactions
const { useState: uS_d, useEffect: uE_d, useMemo: uM_d, useRef: uR_d } = React;

// ============== DEV SHELL ==============
function DevShell({ goto, mobile, currentScreen, children, title }) {
  const items = [
    { id: 'devDashboard', label: 'Dashboard',  icon:<IconChart size={16}/> },
    { id: 'devApps',      label: 'Приложения', icon:<IconBox size={16}/>, count: 5 },
    { id: 'devTx',        label: 'Транзакции', icon:<IconReceipt size={16}/> },
    { id: 'devPayouts',   label: 'Поступления',icon:<IconCash size={16}/> },
    { id: 'devProducts',  label: 'Продукты',   icon:<IconPackage size={16}/> },
    { id: 'devWebhooks',  label: 'Webhooks',   icon:<IconWebhook size={16}/> },
    { id: 'devBilling',   label: 'Тариф',      icon:<IconCard size={16}/> },
    { id: 'devSettings',  label: 'Настройки',  icon:<IconSettings size={16}/> },
  ];
  return (
    <div style={{display:'flex', minHeight:'100%', background:'var(--bg)'}}>
      {!mobile && (
        <aside style={{width: 232, background:'var(--surface)', borderRight:'1px solid var(--border)', display:'flex', flexDirection:'column', flexShrink:0}}>
          <div style={{padding:'16px 16px 12px'}}>
            <button onClick={()=>goto('devLanding')} style={{display:'flex', alignItems:'center', gap:6}}>
              <Wordmark size={18}/>
              <span style={{fontSize:10, fontWeight:700, padding:'2px 5px', background:'var(--n-100)', color:'var(--text-soft)', borderRadius:4, textTransform:'uppercase', letterSpacing:'0.05em'}}>dev</span>
            </button>
          </div>
          <div style={{padding:'4px 8px'}}>
            <button className="card" style={{width:'100%', padding:'8px 10px', display:'flex', alignItems:'center', gap:8, fontSize:13, textAlign:'left', background:'var(--n-25)'}}>
              <div style={{width:20, height:20, borderRadius:4, background:'linear-gradient(135deg, #6366F1, #A855F7)', display:'flex', alignItems:'center', justifyContent:'center', color:'#fff', fontWeight:700, fontSize:10}}>NS</div>
              <div style={{flex:1, minWidth:0, overflow:'hidden'}}>
                <div style={{fontWeight:600, fontSize:12, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>Nebula Studio</div>
                <div style={{fontSize:10, color:'var(--text-muted)'}}>5 приложений</div>
              </div>
              <IconChevD size={12} style={{color:'var(--text-muted)'}}/>
            </button>
          </div>
          <nav style={{padding:'8px', flex:1}}>
            {items.map(it => (
              <button key={it.id} onClick={()=>goto(it.id)} style={{
                display:'flex', alignItems:'center', gap:10,
                width:'100%', padding:'8px 10px', borderRadius:'var(--r-3)',
                background: currentScreen===it.id ? 'var(--n-100)' : 'transparent',
                color: currentScreen===it.id ? 'var(--text)' : 'var(--text-soft)',
                fontWeight: currentScreen===it.id ? 600 : 500,
                fontSize:13, marginBottom:1, textAlign:'left',
              }}>
                {it.icon}
                <span style={{flex:1}}>{it.label}</span>
                {it.count && <span style={{fontSize:10, color:'var(--text-muted)', fontWeight:500}}>{it.count}</span>}
                {it.badge && <span className="badge badge-success" style={{fontSize:10}}>{it.badge}</span>}
              </button>
            ))}
          </nav>
          <div style={{padding:8, borderTop:'1px solid var(--border)'}}>
            <button style={{display:'flex', alignItems:'center', gap:10, width:'100%', padding:'8px 10px', borderRadius:'var(--r-3)', fontSize:13, color:'var(--text-soft)', fontWeight:500}}>
              <IconBook size={16}/>Документация<IconExternal size={11} style={{marginLeft:'auto'}}/>
            </button>
          </div>
          <div style={{padding:'8px', borderTop:'1px solid var(--border)', display:'flex', alignItems:'center', gap:10}}>
            <Avatar name="Илья К" size={28} accent="var(--n-700)"/>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:12, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>Илья Корнев</div>
              <div style={{fontSize:10, color:'var(--text-muted)'}}>Owner</div>
            </div>
            <button className="btn btn-ghost btn-sm" style={{padding:6}}><IconChevD size={12}/></button>
          </div>
        </aside>
      )}
      <main style={{flex:1, minWidth:0, display:'flex', flexDirection:'column'}}>
        <header style={{padding: mobile?'12px 16px':'14px 24px', borderBottom:'1px solid var(--border)', background:'var(--surface)', display:'flex', alignItems:'center', gap:12, position:'sticky', top:0, zIndex:20}}>
          {mobile && <button onClick={()=>goto('devLanding')}><Wordmark size={16}/></button>}
          <div style={{flex:1}}>
            <h1 className="display" style={{fontSize: mobile?16:18, fontWeight:700, margin:0, letterSpacing:'-0.02em'}}>{title}</h1>
          </div>
          {!mobile && <>
            <button className="btn btn-ghost btn-sm"><IconBell size={16}/></button>
            <button className="btn btn-secondary btn-sm">test mode <IconChevD size={12}/></button>
            <button className="btn btn-primary btn-sm">Перейти на Pro</button>
          </>}
        </header>
        <div style={{flex:1, padding: mobile?'16px':'24px'}}>{children}</div>
      </main>
    </div>
  );
}

// ============== 7. DEV LANDING ==============
function ScreenDevLanding({ goto, mobile }) {
  return (
    <div style={{background:'var(--bg)', minHeight:'100%'}}>
      <header style={{padding: mobile?'14px 16px':'16px 32px', display:'flex', alignItems:'center', borderBottom:'1px solid var(--border)', background:'var(--surface)'}}>
        <Wordmark size={20}/>
        <div style={{marginLeft:8, padding:'2px 6px', background:'var(--n-100)', borderRadius:4, fontSize:10, fontWeight:700, color:'var(--text-soft)', textTransform:'uppercase', letterSpacing:'0.05em'}}>dev</div>
        {!mobile && <nav style={{display:'flex', gap:4, marginLeft:24}}>
          {['Продукт','Цены','Документация','Истории','Блог'].map(l=>(<button key={l} className="btn btn-ghost btn-sm">{l}</button>))}
        </nav>}
        <div style={{marginLeft:'auto', display:'flex', gap:8}}>
          <button onClick={()=>goto('landing')} className="btn btn-ghost btn-sm"><IconArrowR size={12} style={{transform:'rotate(180deg)'}}/> Покупателям</button>
          <button onClick={()=>goto('devOnboarding')} className="btn btn-secondary btn-sm">Войти</button>
          <button onClick={()=>goto('devOnboarding')} className="btn btn-primary btn-sm">Попробовать</button>
        </div>
      </header>

      {/* Hero */}
      <section style={{padding: mobile?'48px 16px':'80px 32px 64px', background:'linear-gradient(180deg, var(--n-25), var(--surface))'}}>
        <div style={{maxWidth: 1080, margin:'0 auto'}}>
          <div className="badge" style={{background:'var(--n-100)', marginBottom:16, fontSize:12, padding:'5px 12px'}}>
            <span style={{color:'var(--brand-600)', fontWeight:700}}>NEW</span>
            <span>·</span>
            Subagent-схема для Apple/Google разработчиков
          </div>
          <h1 className="display" style={{fontSize: mobile?40:72, fontWeight:800, lineHeight:1.02, letterSpacing:'-0.035em', margin:0, marginBottom:20, maxWidth: 920}}>
            Платежи в ваших<br/>
            мобильных играх<br/>
            <span style={{color:'var(--text-muted)'}}>от 2,5%</span> вместо 30%<span style={{color:'var(--brand-500)'}}>.</span>
          </h1>
          <p style={{fontSize: mobile?16:20, color:'var(--text-soft)', maxWidth: 640, margin:'0 0 32px', lineHeight:1.5}}>
            SDK + чекаут + аналитика уровня RevenueCat для российского рынка. Работает на ₽ через Мир, СБП, SberPay, YandexPay. Запускаемся за <strong style={{color:'var(--text)'}}>1 час</strong>.
          </p>
          <div style={{display:'flex', gap:12, flexWrap:'wrap', marginBottom: 40}}>
            <button onClick={()=>goto('devOnboarding')} className="btn btn-primary btn-lg">Начать бесплатно <IconArrowR size={14}/></button>
            <button className="btn btn-secondary btn-lg"><IconCode size={14}/> Документация</button>
          </div>
          {/* Code block */}
          <div className="card mono" style={{padding: mobile?16:20, background:'var(--n-900)', color:'#E2E8F0', fontSize:13, lineHeight:1.7, maxWidth: 720, overflow:'hidden'}}>
            <div style={{display:'flex', gap:6, marginBottom:12, opacity:0.4}}>
              <span style={{width:8, height:8, borderRadius:'50%', background:'#FF5F57'}}/>
              <span style={{width:8, height:8, borderRadius:'50%', background:'#FEBC2E'}}/>
              <span style={{width:8, height:8, borderRadius:'50%', background:'#28C840'}}/>
              <span style={{marginLeft:'auto', fontSize:11}}>Swift · iOS SDK</span>
            </div>
            <div><span style={{color:'#94A3B8'}}>// 1. Configure once on app launch</span></div>
            <div><span style={{color:'#FCA5A5'}}>RevCut</span>.<span style={{color:'#A5B4FC'}}>configure</span>(apiKey: <span style={{color:'#FDE68A'}}>"pk_live_…"</span>)</div>
            <div style={{height:8}}/>
            <div><span style={{color:'#94A3B8'}}>// 2. Open paywall — that's it.</span></div>
            <div><span style={{color:'#FCA5A5'}}>RevCut</span>.<span style={{color:'#A5B4FC'}}>presentPaywall</span>(productId: <span style={{color:'#FDE68A'}}>"battle_pass_monthly"</span>) {'{'}</div>
            <div>  <span style={{color:'#94A3B8'}}>// purchase delivered to your backend webhook</span></div>
            <div>{'}'}</div>
          </div>
        </div>
      </section>

      {/* Comparison */}
      <section style={{padding: mobile?'48px 16px':'72px 32px', background:'var(--surface)', borderTop:'1px solid var(--border)'}}>
        <div style={{maxWidth: 1080, margin:'0 auto'}}>
          <h2 className="display" style={{fontSize: mobile?28:36, fontWeight:700, margin:'0 0 8px', letterSpacing:'-0.02em', textAlign:'center'}}>Сравните комиссии</h2>
          <p style={{textAlign:'center', color:'var(--text-muted)', fontSize:14, margin:'0 0 32px'}}>На 1 млн ₽ оборота вы получаете больше с rev.cut</p>
          <div className="card" style={{padding:0, overflow:'hidden'}}>
            <table style={{width:'100%', borderCollapse:'collapse', fontSize:14}}>
              <thead style={{background:'var(--n-50)'}}>
                <tr>
                  <th style={{padding:'14px 20px', textAlign:'left', fontWeight:600, fontSize:12, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>Платформа</th>
                  <th style={{padding:'14px 20px', textAlign:'right', fontWeight:600, fontSize:12, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>Комиссия</th>
                  <th style={{padding:'14px 20px', textAlign:'right', fontWeight:600, fontSize:12, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em'}}>Вы получите</th>
                </tr>
              </thead>
              <tbody>
                {[
                  ['Apple App Store', '30%', 700_000, false],
                  ['Google Play Billing', '30% / 15%', 850_000, false],
                  ['Codashop', '5–10%', 920_000, false],
                  ['rev.cut', '2,5–7%', 975_000, true],
                ].map(([n,c,v,h], i)=>(
                  <tr key={i} style={{borderTop:'1px solid var(--border)', background: h?'var(--brand-50)':undefined}}>
                    <td style={{padding:'14px 20px', fontWeight: h?700:500}}>{h && <span style={{color:'var(--brand-600)', marginRight:6}}>★</span>}{n}</td>
                    <td style={{padding:'14px 20px', textAlign:'right', color: h?'var(--brand-700)':'var(--text-soft)', fontWeight:600}}>{c}</td>
                    <td style={{padding:'14px 20px', textAlign:'right', fontWeight: h?800:600, color: h?'var(--brand-700)':undefined, fontFamily:'var(--font-display)'}} className="tnum">{fmtNum(v)} ₽</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </section>

      {/* Use cases */}
      <section style={{padding: mobile?'48px 16px':'72px 32px'}}>
        <div style={{maxWidth: 1080, margin:'0 auto'}}>
          <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'repeat(3,1fr)', gap: 16}}>
            {[
              ['Mobile games', 'Топ-апы кристаллов, боевые пропуска, season pass — нативный SDK для iOS/Android.', <IconBolt size={20}/>],
              ['Edtech & Fitness', 'Подписки с trial, grace period, dunning. Как в RevenueCat — но в ₽.', <IconBook size={20}/>],
              ['B2C apps', 'Customer Portal с magic-link отменой по ст. 26.1 ЗоЗПП. Чеки 54-ФЗ автоматом.', <IconShield2 size={20}/>],
            ].map(([t,d,ic],i)=>(
              <div key={i} className="card" style={{padding:24}}>
                <div style={{width:40, height:40, borderRadius:'var(--r-3)', background:'var(--brand-50)', color:'var(--brand-700)', display:'flex', alignItems:'center', justifyContent:'center', marginBottom:16}}>{ic}</div>
                <h3 style={{fontSize:18, fontWeight:700, margin:'0 0 8px'}}>{t}</h3>
                <p style={{margin:0, fontSize:14, color:'var(--text-soft)', lineHeight:1.6}}>{d}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section style={{padding: mobile?'48px 16px':'80px 32px', background:'var(--n-900)', color:'#fff'}}>
        <div style={{maxWidth: 720, margin:'0 auto', textAlign:'center'}}>
          <h2 className="display" style={{fontSize: mobile?32:48, fontWeight:800, letterSpacing:'-0.025em', margin:'0 0 16px'}}>Запустите за 1 час<span style={{color:'var(--brand-500)'}}>.</span></h2>
          <p style={{color:'#94A3B8', fontSize: mobile?16:18, lineHeight:1.5, margin:'0 0 32px'}}>Free до 1 млн ₽ GMV/мес. Без карты для регистрации. Без минимальных комиссий.</p>
          <button onClick={()=>goto('devOnboarding')} className="btn btn-accent btn-lg">Создать аккаунт <IconArrowR size={14}/></button>
        </div>
      </section>
    </div>
  );
}

// ============== 8. DEV ONBOARDING (step 2) ==============
function ScreenDevOnboarding({ goto, mobile }) {
  const [appName, setAppName] = uS_d('Astral Chronicles');
  const [category, setCategory] = uS_d('rpg');
  const [iosLink, setIosLink] = uS_d('https://apps.apple.com/ru/app/astral-chronicles/id123456789');
  const [androidLink, setAndroidLink] = uS_d('https://play.google.com/store/apps/details?id=com.nebula.astral');
  const [iconUploaded, setIconUploaded] = uS_d(true);
  const [dragActive, setDragActive] = uS_d(false);
  const [description, setDescription] = uS_d('Эпическая RPG в волшебном мире. Сражайтесь за судьбу королевства, открывайте артефакты и исследуйте 5 континентов.');

  return (
    <div style={{background:'var(--bg)', minHeight:'100%'}}>
      {/* Top progress */}
      <header style={{padding:'14px 24px', borderBottom:'1px solid var(--border)', background:'var(--surface)', display:'flex', alignItems:'center', gap:16}}>
        <Wordmark size={18}/>
        <span style={{marginLeft:8, padding:'2px 6px', background:'var(--n-100)', borderRadius:4, fontSize:10, fontWeight:700, textTransform:'uppercase'}}>dev</span>
        <div style={{flex:1, maxWidth: 480, marginLeft:24}}>
          <div style={{display:'flex', justifyContent:'space-between', fontSize:11, color:'var(--text-muted)', marginBottom:6, fontWeight:500}}>
            <span>Шаг 2 из 4 · Приложение</span>
            <span>50%</span>
          </div>
          <div style={{height:4, background:'var(--n-150)', borderRadius:'var(--r-full)', overflow:'hidden'}}>
            <div style={{width:'50%', height:'100%', background:'var(--n-900)', borderRadius:'var(--r-full)', transition:'width .3s'}}/>
          </div>
        </div>
        <button className="btn btn-ghost btn-sm">Сохранить и выйти</button>
      </header>

      <div style={{maxWidth: 720, margin:'0 auto', padding: mobile?'24px 16px':'40px 24px'}}>
        <div style={{display:'flex', gap: 6, marginBottom:24, alignItems:'center', flexWrap:'wrap'}}>
          {['Компания','Приложение','Товары','Интеграция'].map((s,i)=>(
            <Fragment key={i}>
              <div style={{display:'flex', alignItems:'center', gap:6, fontSize:13}}>
                <div style={{
                  width:24, height:24, borderRadius:'50%',
                  background: i<1?'var(--success)':i===1?'var(--n-900)':'var(--n-150)',
                  color: i<=1?'#fff':'var(--text-muted)',
                  display:'flex', alignItems:'center', justifyContent:'center', fontWeight:700, fontSize:12,
                }}>{i<1 ? <IconCheck size={12}/> : i+1}</div>
                <span style={{color: i===1?'var(--text)':'var(--text-muted)', fontWeight: i===1?600:500}}>{s}</span>
              </div>
              {i<3 && <div style={{width:20, height:1, background:'var(--border)'}}/>}
            </Fragment>
          ))}
        </div>

        <h1 className="display" style={{fontSize:28, fontWeight:700, margin:'0 0 8px', letterSpacing:'-0.02em'}}>Расскажите о приложении</h1>
        <p style={{margin:'0 0 32px', color:'var(--text-muted)', fontSize:14}}>Эту информацию увидят покупатели на странице игры. Вы сможете изменить её позже.</p>

        <div className="card" style={{padding:24, display:'flex', flexDirection:'column', gap:20}}>
          {/* Icon upload */}
          <div>
            <label style={{fontSize:13, fontWeight:600, display:'block', marginBottom:8}}>Иконка</label>
            <div
              onDragOver={e=>{e.preventDefault(); setDragActive(true);}}
              onDragLeave={()=>setDragActive(false)}
              onDrop={e=>{e.preventDefault(); setDragActive(false); setIconUploaded(true);}}
              style={{
                display:'flex', gap:16, alignItems:'center', padding:16,
                border:'2px dashed '+(dragActive?'var(--n-900)':'var(--border-strong)'),
                borderRadius:'var(--r-4)', background: dragActive?'var(--n-50)':'var(--n-25)',
                transition:'all .15s',
              }}>
              {iconUploaded ? (
                <div style={{width:64, height:64, borderRadius:'var(--r-4)', overflow:'hidden', flexShrink:0}}>
                  <GameCover slug="astral-chronicles" accent="#6366F1" accent2="#A855F7"/>
                </div>
              ) : (
                <div style={{width:64, height:64, borderRadius:'var(--r-4)', background:'var(--n-100)', display:'flex', alignItems:'center', justifyContent:'center', color:'var(--text-muted)'}}>
                  <IconUpload size={24}/>
                </div>
              )}
              <div style={{flex:1}}>
                <div style={{fontSize:13, fontWeight:600, marginBottom:2}}>{iconUploaded?'astral-icon-512.png':'Перетащите файл сюда'}</div>
                <div style={{fontSize:12, color:'var(--text-muted)'}}>{iconUploaded?'1024×1024 · 84 КБ · ✓':'PNG или JPG, 512×512 минимум'}</div>
              </div>
              <button className="btn btn-secondary btn-sm">{iconUploaded?'Заменить':'Загрузить'}</button>
            </div>
          </div>

          <div>
            <label style={{fontSize:13, fontWeight:600, display:'block', marginBottom:6}}>Название</label>
            <input className="input" value={appName} onChange={e=>setAppName(e.target.value)}/>
            <div style={{fontSize:11, color:'var(--text-muted)', marginTop:4}}>Так приложение увидят покупатели</div>
          </div>

          <div>
            <label style={{fontSize:13, fontWeight:600, display:'block', marginBottom:6}}>Категория</label>
            <select className="input" value={category} onChange={e=>setCategory(e.target.value)}>
              <option value="rpg">RPG</option><option value="strategy">Стратегия</option>
              <option value="casual">Casual</option><option value="racing">Гонки</option>
              <option value="edtech">Edtech</option><option value="fitness">Fitness</option>
            </select>
          </div>

          <div>
            <label style={{fontSize:13, fontWeight:600, display:'block', marginBottom:6}}>Описание</label>
            <textarea className="input" rows={3} value={description} onChange={e=>setDescription(e.target.value)} style={{resize:'vertical', minHeight:84}}/>
            <div style={{fontSize:11, color:'var(--text-muted)', marginTop:4}}>{description.length} / 500 символов</div>
          </div>

          <div style={{display:'grid', gridTemplateColumns: mobile?'1fr':'1fr 1fr', gap:16}}>
            <div>
              <label style={{fontSize:13, fontWeight:600, display:'block', marginBottom:6, display:'flex', alignItems:'center', gap:6}}>
                <span style={{width:14, height:14, background:'#000', color:'#fff', borderRadius:3, fontSize:10, display:'flex', alignItems:'center', justifyContent:'center'}}>A</span>
                App Store
              </label>
              <input className="input" placeholder="https://apps.apple.com/..." value={iosLink} onChange={e=>setIosLink(e.target.value)} style={{fontFamily:'var(--font-mono)', fontSize:12}}/>
            </div>
            <div>
              <label style={{fontSize:13, fontWeight:600, display:'block', marginBottom:6, display:'flex', alignItems:'center', gap:6}}>
                <span style={{width:14, height:14, background:'#3DDC84', color:'#000', borderRadius:3, fontSize:10, display:'flex', alignItems:'center', justifyContent:'center'}}>▶</span>
                Google Play
              </label>
              <input className="input" placeholder="https://play.google.com/..." value={androidLink} onChange={e=>setAndroidLink(e.target.value)} style={{fontFamily:'var(--font-mono)', fontSize:12}}/>
            </div>
          </div>
        </div>

        <div style={{display:'flex', gap:8, marginTop:24, justifyContent:'space-between'}}>
          <button className="btn btn-secondary"><IconChevL size={14}/> Назад</button>
          <button onClick={()=>goto('devDashboard')} className="btn btn-primary btn-lg">Дальше: Товары <IconArrowR size={14}/></button>
        </div>
      </div>
    </div>
  );
}

window.DevShell = DevShell;
window.ScreenDevLanding = ScreenDevLanding;
window.ScreenDevOnboarding = ScreenDevOnboarding;
