// Storefront screens: Landing, Catalog, Game page, Checkout, Success, Account
const { useState: uS_s, useEffect: uE_s, useMemo: uM_s, useRef: uR_s } = React;

// ============== SHARED CHROME ==============
function StorefrontHeader({ goto, mobile, currentScreen }) {
  return (
    <header style={{
      position:'sticky', top:0, zIndex:30, background:'rgba(255,255,255,0.92)',
      backdropFilter:'blur(8px)', borderBottom:'1px solid var(--border)',
      padding: mobile ? '10px 16px' : '12px 32px',
      display:'flex', alignItems:'center', gap: mobile ? 12 : 24,
    }}>
      <button onClick={()=>goto('landing')} style={{display:'flex', alignItems:'center'}}>
        <Wordmark size={mobile ? 18 : 20}/>
      </button>
      {!mobile && (
        <nav style={{display:'flex', gap:4, marginLeft:8}}>
          {[['catalog','Каталог'],['landing','Главная'],['account','Аккаунт']].map(([k,l])=>(
            <button key={k} onClick={()=>goto(k)} className="btn btn-ghost btn-sm" style={{
              color: currentScreen===k ? 'var(--n-900)' : 'var(--text-soft)',
              fontWeight: currentScreen===k ? 600 : 500,
            }}>{l}</button>
          ))}
        </nav>
      )}
      <div style={{flex:1, maxWidth: mobile ? 'none' : 400, position:'relative'}}>
        <IconSearch style={{position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:'var(--n-400)'}}/>
        <input className="input" placeholder="Поиск игр и товаров" style={{paddingLeft:36}}/>
      </div>
      {!mobile && <>
        <button className="btn btn-ghost btn-sm"><IconHeart size={18}/></button>
        <button className="btn btn-ghost btn-sm" style={{position:'relative'}}>
          <IconCart size={18}/>
          <span style={{position:'absolute', top:0, right:0, background:'var(--brand-500)', width:8, height:8, borderRadius:'50%'}}/>
        </button>
        <button onClick={()=>goto('account')} style={{marginLeft: 4}}>
          <Avatar name="Игрок Демо" size={32} accent="var(--n-900)"/>
        </button>
      </>}
      {mobile && <button onClick={()=>goto('account')}><Avatar name="Игрок Демо" size={28} accent="var(--n-900)"/></button>}
    </header>
  );
}

function StorefrontFooter({ mobile }) {
  return (
    <footer style={{
      borderTop:'1px solid var(--border)', background:'var(--surface)',
      padding: mobile ? '24px 16px' : '40px 32px', marginTop:48,
    }}>
      <div style={{display:'grid', gridTemplateColumns: mobile?'1fr 1fr':'2fr 1fr 1fr 1fr', gap: 24}}>
        <div>
          <Wordmark size={20}/>
          <p style={{color:'var(--text-muted)', fontSize:13, lineHeight:1.6, marginTop:12, maxWidth: 320}}>
            Платежная инфраструктура для российских мобильных игр и приложений. Работаем по 161-ФЗ.
          </p>
          <div style={{display:'flex', gap:8, marginTop:16, flexWrap:'wrap'}}>
            <PayLogo kind="mir"/><PayLogo kind="sbp"/><PayLogo kind="sberpay"/><PayLogo kind="yandexpay"/>
          </div>
        </div>
        <div>
          <h4 style={{fontSize:12, fontWeight:700, color:'var(--n-900)', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom: 12}}>Магазин</h4>
          <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:8, fontSize:13, color:'var(--text-soft)'}}>
            <li>Каталог</li><li>Категории</li><li>Скидки</li><li>Подписки</li>
          </ul>
        </div>
        <div>
          <h4 style={{fontSize:12, fontWeight:700, color:'var(--n-900)', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom: 12}}>Помощь</h4>
          <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:8, fontSize:13, color:'var(--text-soft)'}}>
            <li>FAQ</li><li>Возвраты</li><li>54-ФЗ Чеки</li><li>Поддержка</li>
          </ul>
        </div>
        <div>
          <h4 style={{fontSize:12, fontWeight:700, color:'var(--n-900)', textTransform:'uppercase', letterSpacing:'0.05em', marginBottom: 12}}>Разработчикам</h4>
          <ul style={{listStyle:'none', padding:0, margin:0, display:'flex', flexDirection:'column', gap:8, fontSize:13, color:'var(--text-soft)'}}>
            <li>Подключение</li><li>Документация</li><li>SDK</li><li>Pricing</li>
          </ul>
        </div>
      </div>
      <div style={{borderTop:'1px solid var(--border)', marginTop:24, paddingTop:16, fontSize:12, color:'var(--text-muted)', display:'flex', justifyContent:'space-between', flexWrap:'wrap', gap:8}}>
        <span>© 2026 rev.cut · ООО «Ревкат» · ОГРН 1234567890123</span>
        <span>Политика · Оферта · 152-ФЗ</span>
      </div>
    </footer>
  );
}

// ============== 1. LANDING ==============
function ScreenLanding({ goto, mobile }) {
  const featured = MOCK_GAMES.slice(0,4);
  const trending = MOCK_GAMES;
  return (
    <div style={{background:'var(--bg)', minHeight:'100%'}}>
      <StorefrontHeader goto={goto} mobile={mobile} currentScreen="landing"/>
      {/* Hero */}
      <section style={{
        background: 'linear-gradient(135deg, #FEFCE8 0%, #FFFFFF 60%)',
        padding: mobile ? '32px 16px 40px' : '64px 32px 80px',
        borderBottom: '1px solid var(--border)',
      }}>
        <div style={{maxWidth: 1200, margin:'0 auto'}}>
          <div className="badge badge-brand" style={{marginBottom:16}}>
            <span style={{width:6, height:6, background:'var(--brand-600)', borderRadius:'50%'}}/>
            Топ-апы и подписки в ₽ · по 161-ФЗ
          </div>
          <h1 className="display" style={{
            fontSize: mobile? 32 : 56, fontWeight: 800, lineHeight: 1.05, letterSpacing:'-0.03em',
            margin: 0, marginBottom: 16, maxWidth: 880,
          }}>
            Покупай в любимых играх<br/>
            <span style={{position:'relative'}}>
              быстро, в рублях
              <svg viewBox="0 0 200 10" style={{position:'absolute', bottom:-4, left:0, width:'100%', height:8}}>
                <path d="M2 6 Q50 1, 100 5 T 198 4" stroke="var(--brand-500)" strokeWidth="3" fill="none" strokeLinecap="round"/>
              </svg>
            </span>
            <span style={{color:'var(--brand-500)'}}>.</span>
          </h1>
          <p style={{fontSize: mobile ? 15 : 18, color:'var(--text-soft)', maxWidth: 600, margin:'0 0 24px', lineHeight:1.5}}>
            Топ-апы, подписки и боевые пропуска в мобильных играх. Оплата картой Мир, СБП, SberPay или YandexPay. Чек по 54-ФЗ автоматически — на e-mail.
          </p>
          <div style={{display:'flex', gap:12, flexWrap:'wrap', marginBottom: 32}}>
            <button onClick={()=>goto('catalog')} className="btn btn-primary btn-lg">
              Открыть каталог <IconArrowR size={16}/>
            </button>
            <button onClick={()=>goto('game')} className="btn btn-secondary btn-lg">
              <IconBolt size={16}/> Топ-ап за 30 сек
            </button>
          </div>
          <div style={{display:'flex', gap: mobile? 8 : 16, alignItems:'center', flexWrap:'wrap'}}>
            <span style={{fontSize:12, color:'var(--text-muted)', fontWeight:500}}>Принимаем:</span>
            <PayLogo kind="mir"/><PayLogo kind="sbp"/><PayLogo kind="sberpay"/><PayLogo kind="yandexpay"/>
          </div>
        </div>
      </section>

      {/* Trust row */}
      <section style={{padding: mobile ? '20px 16px' : '24px 32px', background:'var(--surface)', borderBottom:'1px solid var(--border)'}}>
        <div style={{maxWidth:1200, margin:'0 auto', display:'grid', gridTemplateColumns: mobile? '1fr 1fr' : 'repeat(4, 1fr)', gap: 16}}>
          {[
            [<IconBolt size={20}/>, 'Оплата за 30 секунд', 'СБП и кошельки без 3DS'],
            [<IconReceipt size={20}/>, 'Чек по 54-ФЗ', 'автоматом, на e-mail'],
            [<IconShield2 size={20}/>, '161-ФЗ', 'через ЮKassa, прозрачно'],
            [<IconRefresh size={20}/>, 'Гарантия доставки', 'не пришло — вернём'],
          ].map(([ic,t,sub], i)=>(
            <div key={i} style={{display:'flex', gap:12, alignItems:'flex-start'}}>
              <div style={{width:36, height:36, borderRadius:'var(--r-3)', background:'var(--brand-50)', color:'var(--brand-700)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0}}>{ic}</div>
              <div>
                <div style={{fontSize:13, fontWeight:600}}>{t}</div>
                <div style={{fontSize:12, color:'var(--text-muted)'}}>{sub}</div>
              </div>
            </div>
          ))}
        </div>
      </section>

      {/* Featured games */}
      <section style={{padding: mobile ? '32px 16px' : '48px 32px'}}>
        <div style={{maxWidth:1200, margin:'0 auto'}}>
          <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 20}}>
            <h2 className="display" style={{fontSize: mobile?22:28, fontWeight:700, margin:0, letterSpacing:'-0.02em'}}>Популярные игры</h2>
            <button onClick={()=>goto('catalog')} className="btn btn-ghost btn-sm">Все игры <IconArrowR size={14}/></button>
          </div>
          <div style={{display:'grid', gridTemplateColumns: mobile? '1fr' : 'repeat(4, 1fr)', gap: 16}}>
            {featured.map(g => (
              <button key={g.slug} onClick={()=>goto('game', g.slug)} className="card lift" style={{padding:0, overflow:'hidden', textAlign:'left'}}>
                <div style={{aspectRatio:'16/9', overflow:'hidden', position:'relative'}}>
                  <GameCover slug={g.slug} accent={g.accent} accent2={g.accent2}/>
                  {g.tag && <div style={{position:'absolute', top:8, left:8}} className="badge badge-brand">{g.tag}</div>}
                </div>
                <div style={{padding:12}}>
                  <div style={{fontWeight:600, fontSize:14}}>{g.title}</div>
                  <div style={{fontSize:12, color:'var(--text-muted)', display:'flex', justifyContent:'space-between', marginTop:4}}>
                    <span>{g.dev}</span>
                    <span style={{display:'flex', alignItems:'center', gap:2}}><IconStar size={12} fill="var(--brand-500)" stroke={0}/> {g.rating}</span>
                  </div>
                  <div style={{fontSize:12, color:'var(--brand-700)', marginTop:8, fontWeight:500}}>от {Math.min(...g.products.map(p=>p.price))} ₽</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Trending products */}
      <section style={{padding: mobile ? '0 16px 32px' : '0 32px 48px'}}>
        <div style={{maxWidth:1200, margin:'0 auto'}}>
          <h2 className="display" style={{fontSize: mobile?22:28, fontWeight:700, margin:'0 0 20px', letterSpacing:'-0.02em'}}>Топ-апы недели</h2>
          <div className="scroll-thin" style={{display:'flex', gap:12, overflowX:'auto', paddingBottom: 8, marginBottom: -8}}>
            {trending.flatMap(g => g.products.filter(p=>p.was).slice(0,1).map(p => ({g,p}))).slice(0,6).map(({g,p}, i) => (
              <button key={i} onClick={()=>goto('game', g.slug)} className="card lift" style={{flexShrink:0, width: 240, padding:0, overflow:'hidden', textAlign:'left'}}>
                <div style={{height:90, position:'relative'}}>
                  <GameCover slug={g.slug} accent={g.accent} accent2={g.accent2}/>
                  {p.badge && <div style={{position:'absolute', top:8, right:8, background:'var(--danger)', color:'#fff', fontSize:11, fontWeight:700, padding:'3px 7px', borderRadius:'var(--r-3)'}}>{p.badge}</div>}
                </div>
                <div style={{padding:12}}>
                  <div style={{fontSize:11, color:'var(--text-muted)', textTransform:'uppercase', letterSpacing:'0.05em', fontWeight:600, marginBottom:4}}>{g.title}</div>
                  <div style={{fontWeight:600, fontSize:14, marginBottom:8}}>{p.name}</div>
                  <div style={{display:'flex', alignItems:'baseline', gap:8}}>
                    <span style={{fontSize:18, fontWeight:700, fontFamily:'var(--font-display)'}} className="tnum">{fmtNum(p.price)} ₽</span>
                    {p.was && <span style={{fontSize:13, color:'var(--text-muted)', textDecoration:'line-through'}} className="tnum">{fmtNum(p.was)} ₽</span>}
                  </div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </section>

      {/* Categories */}
      <section style={{padding: mobile ? '0 16px 48px' : '0 32px 64px'}}>
        <div style={{maxWidth:1200, margin:'0 auto'}}>
          <h2 className="display" style={{fontSize: mobile?22:28, fontWeight:700, margin:'0 0 20px', letterSpacing:'-0.02em'}}>Категории</h2>
          <div style={{display:'grid', gridTemplateColumns: mobile?'repeat(2,1fr)':'repeat(6,1fr)', gap: 12}}>
            {[
              ['RPG', '#6366F1'],['Стратегия','#0EA5E9'],['Casual','#F59E0B'],
              ['Гонки','#EF4444'],['Edtech','#8B5CF6'],['Fitness','#10B981'],
            ].map(([n,c])=>(
              <button key={n} onClick={()=>goto('catalog')} className="card lift" style={{padding: 16, display:'flex', flexDirection:'column', alignItems:'flex-start', gap:8, textAlign:'left'}}>
                <div style={{width:32, height:32, borderRadius:'var(--r-3)', background: c+'18', color: c, display:'flex', alignItems:'center', justifyContent:'center'}}>
                  <IconLayers size={16}/>
                </div>
                <span style={{fontWeight:600, fontSize:14}}>{n}</span>
              </button>
            ))}
          </div>
        </div>
      </section>

      <StorefrontFooter mobile={mobile}/>
    </div>
  );
}

// ============== 2. CATALOG ==============
function ScreenCatalog({ goto, mobile }) {
  const [genre, setGenre] = uS_s('all');
  const [sort, setSort] = uS_s('popular');
  const [hasSub, setHasSub] = uS_s(false);
  const [hasTopup, setHasTopup] = uS_s(false);
  const [discount, setDiscount] = uS_s(false);
  const [query, setQuery] = uS_s('');
  const [showFilters, setShowFilters] = uS_s(false);

  const genres = ['all', ...new Set(MOCK_GAMES.map(g=>g.genre))];
  const filtered = MOCK_GAMES
    .filter(g => genre === 'all' || g.genre === genre)
    .filter(g => g.title.toLowerCase().includes(query.toLowerCase()))
    .filter(g => !hasSub || g.products.some(p => p.type==='sub'))
    .filter(g => !hasTopup || g.products.some(p => p.type==='topup'))
    .filter(g => !discount || g.products.some(p => p.was));

  const FilterPanel = () => (
    <aside style={{width: mobile?'100%':260, flexShrink:0}}>
      <div className="card" style={{padding:16, marginBottom:12}}>
        <h3 style={{fontSize:13, fontWeight:700, margin:0, marginBottom:12, textTransform:'uppercase', letterSpacing:'0.05em'}}>Жанр</h3>
        <div style={{display:'flex', flexDirection:'column', gap:4}}>
          {genres.map(g => (
            <button key={g} onClick={()=>setGenre(g)} style={{
              textAlign:'left', padding:'8px 10px', borderRadius:'var(--r-3)',
              background: genre===g ? 'var(--n-100)' : 'transparent',
              fontSize:13, fontWeight: genre===g ? 600 : 500,
              color: genre===g ? 'var(--n-900)' : 'var(--text-soft)',
            }}>
              {g === 'all' ? 'Все жанры' : g}
            </button>
          ))}
        </div>
      </div>
      <div className="card" style={{padding:16}}>
        <h3 style={{fontSize:13, fontWeight:700, margin:0, marginBottom:12, textTransform:'uppercase', letterSpacing:'0.05em'}}>Тип продукта</h3>
        <div style={{display:'flex', flexDirection:'column', gap:10}}>
          {[
            ['С подпиской', hasSub, setHasSub],
            ['С топ-апами', hasTopup, setHasTopup],
            ['Со скидкой', discount, setDiscount],
          ].map(([l,v,set],i)=>(
            <label key={i} style={{display:'flex', alignItems:'center', gap:8, fontSize:13, cursor:'pointer'}}>
              <input type="checkbox" checked={v} onChange={e=>set(e.target.checked)} style={{accentColor:'var(--n-900)'}}/>
              {l}
            </label>
          ))}
        </div>
      </div>
    </aside>
  );

  return (
    <div style={{background:'var(--bg)', minHeight:'100%'}}>
      <StorefrontHeader goto={goto} mobile={mobile} currentScreen="catalog"/>
      <div style={{padding: mobile?'16px':'32px', maxWidth:1280, margin:'0 auto'}}>
        <nav style={{fontSize:13, color:'var(--text-muted)', marginBottom: 12}}>
          <button onClick={()=>goto('landing')}>Главная</button> · <span style={{color:'var(--text)'}}>Каталог игр</span>
        </nav>
        <div style={{display:'flex', alignItems:'baseline', justifyContent:'space-between', marginBottom: 20, flexWrap:'wrap', gap:8}}>
          <h1 className="display" style={{fontSize: mobile?24:32, fontWeight:700, margin:0, letterSpacing:'-0.02em'}}>Каталог игр</h1>
          <span style={{fontSize:13, color:'var(--text-muted)'}}>Найдено: {filtered.length} {filtered.length===1?'игра':'игр'}</span>
        </div>
        <div style={{display:'flex', gap: 24, flexDirection: mobile?'column':'row'}}>
          {!mobile && <FilterPanel/>}
          <div style={{flex:1, minWidth:0}}>
            <div style={{display:'flex', gap:8, marginBottom:16, flexWrap:'wrap'}}>
              <div style={{flex:1, minWidth: 200, position:'relative'}}>
                <IconSearch style={{position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:'var(--n-400)'}}/>
                <input className="input" placeholder="Поиск" value={query} onChange={e=>setQuery(e.target.value)} style={{paddingLeft:36}}/>
              </div>
              {mobile && (
                <button onClick={()=>setShowFilters(!showFilters)} className="btn btn-secondary"><IconFilter size={14}/> Фильтры</button>
              )}
              <select className="input" value={sort} onChange={e=>setSort(e.target.value)} style={{width: mobile?'100%':200}}>
                <option value="popular">По популярности</option>
                <option value="new">По новизне</option>
                <option value="price-desc">Цена: убывание</option>
                <option value="discount">По скидке</option>
              </select>
            </div>
            {mobile && showFilters && <div style={{marginBottom:16}}><FilterPanel/></div>}
            {filtered.length === 0 ? (
              <div className="card" style={{padding:48, textAlign:'center'}}>
                <div style={{fontSize:32, marginBottom:8}}>🔍</div>
                <div style={{fontWeight:600, marginBottom:4}}>Ничего не нашли</div>
                <div style={{fontSize:13, color:'var(--text-muted)'}}>Попробуйте сбросить фильтры</div>
              </div>
            ) : (
              <div style={{display:'grid', gridTemplateColumns: mobile?'repeat(2,1fr)':'repeat(3,1fr)', gap: 16}}>
                {filtered.map(g => (
                  <button key={g.slug} onClick={()=>goto('game', g.slug)} className="card lift" style={{padding:0, overflow:'hidden', textAlign:'left'}}>
                    <div style={{aspectRatio:'16/9', position:'relative'}}>
                      <GameCover slug={g.slug} accent={g.accent} accent2={g.accent2}/>
                      {g.tag && <div style={{position:'absolute', top:8, left:8}} className="badge badge-brand">{g.tag}</div>}
                      {g.products.some(p=>p.was) && <div style={{position:'absolute', top:8, right:8, background:'var(--danger)', color:'#fff', fontSize:11, fontWeight:700, padding:'3px 7px', borderRadius:'var(--r-3)'}}>SALE</div>}
                    </div>
                    <div style={{padding:12}}>
                      <div style={{fontWeight:600, fontSize: mobile?13:14, marginBottom: 2}}>{g.title}</div>
                      <div style={{fontSize:11, color:'var(--text-muted)', marginBottom: 8}}>{g.dev} · {g.genre}</div>
                      <div style={{display:'flex', justifyContent:'space-between', alignItems:'center'}}>
                        <span style={{fontSize:12, color:'var(--brand-700)', fontWeight:600}} className="tnum">от {fmtNum(Math.min(...g.products.map(p=>p.price)))} ₽</span>
                        <span style={{fontSize:11, color:'var(--text-muted)', display:'flex', alignItems:'center', gap:2}}><IconStar size={11} fill="var(--brand-500)" stroke={0}/> {g.rating}</span>
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
      <StorefrontFooter mobile={mobile}/>
    </div>
  );
}

window.ScreenLanding = ScreenLanding;
window.ScreenCatalog = ScreenCatalog;
window.StorefrontHeader = StorefrontHeader;
window.StorefrontFooter = StorefrontFooter;
