/* IslamPlay — Основные экраны приложения (русский) */

// ── ГЛАВНАЯ
function HomeScreen({ ctx }) {
  const { setTab, openPlaylist, playTrack, user, reciterSlug } = ctx;
  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Доброе утро' : hour < 18 ? 'Добрый день' : 'Добрый вечер';
  // Пул треков выбранного чтеца (fallback — все)
  const pool = (reciterSlug ? IP_YASIN_TRACKS.filter(t => t.reciterSlug === reciterSlug) : IP_YASIN_TRACKS);
  const tracksPool = pool.length ? pool : IP_YASIN_TRACKS;
  // Избранная сура — предпочтительно Ясин (36) выбранного чтеца, иначе первая в пуле.
  const featured =
    tracksPool.find(t => t.surah === 36) ||
    tracksPool[0];
  return (
    <IPScreen>
      <IPTopBar
        subtitle={`${greeting}, ассаляму алейкум`}
        title={user.name.split(' ')[0]}
        right={<button style={{
          width: 36, height: 36, borderRadius: 12,
          background: 'rgba(212, 175, 106, 0.08)',
          border: `1px solid ${IP_THEME.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><IPIcon name="bell" size={18} color={IP_THEME.goldLight}/></button>}
      />

      {/* Hero — Featured surah */}
      {featured && (
        <div style={{ padding: '0 20px' }}>
          <div onClick={() => playTrack(featured)} style={{
            position: 'relative', borderRadius: 20, overflow: 'hidden',
            background: 'linear-gradient(135deg, #3a2a10 0%, #221810 60%, #0f0a06 100%)',
            border: `1px solid ${IP_THEME.lineStrong}`,
            padding: 20, cursor: 'pointer',
            boxShadow: '0 12px 36px rgba(0,0,0,0.4)',
          }}>
            <IPPattern opacity={0.09}/>
            <div style={{ position: 'relative', zIndex: 1, display: 'flex', alignItems: 'center', gap: 16 }}>
              <IPMihrab size={84} glow={false}>
                <div style={{ fontFamily: 'Amiri, serif', fontSize: 22, color: IP_THEME.goldLight, fontWeight: 700 }}>{featured.titleAr}</div>
              </IPMihrab>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 10, letterSpacing: '0.18em', color: IP_THEME.goldLight, textTransform: 'uppercase', fontWeight: 600 }}>
                  Избранное · Сура {featured.surah}
                </div>
                <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 24, fontWeight: 600, color: IP_THEME.cream, marginTop: 2, lineHeight: 1.15 }}>
                  Сура {featured.title}
                </div>
                <div style={{ fontSize: 12, color: IP_THEME.creamMute, marginTop: 2 }}>
                  {featured.reciter} · {featured.ayah_count || featured.verses} аятов
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 12 }}>
                  <button onClick={e => { e.stopPropagation(); playTrack(featured); }} style={{
                    height: 36, padding: '0 16px', borderRadius: 10,
                    background: 'linear-gradient(180deg, #e9c97a, #b8904a)',
                    border: 'none', color: '#17130d', fontSize: 13, fontWeight: 600,
                    display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer',
                  }}>
                    <IPIcon name="play" size={14} color="#17130d"/> Слушать
                  </button>
                  <button onClick={e => { e.stopPropagation(); IP_API.favorite(featured.id, true); }} style={{
                    height: 36, width: 36, borderRadius: 10,
                    background: 'rgba(212, 175, 106, 0.1)',
                    border: `1px solid ${IP_THEME.line}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
                  }}><IPIcon name="heart" size={16} color={IP_THEME.goldLight}/></button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Быстрый доступ */}
      <div style={{ padding: '20px 20px 0' }}>
        <SectionTitle>Быстрый доступ</SectionTitle>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {IP_PLAYLISTS.slice(0, 4).map(pl => {
            const short = pl.title.split('·')[0].trim();
            return (
              <div key={pl.id} onClick={() => openPlaylist(pl)} style={{
                display: 'flex', alignItems: 'center', gap: 10,
                background: 'rgba(212, 175, 106, 0.05)',
                border: `1px solid ${IP_THEME.line}`,
                borderRadius: 12, padding: 8, cursor: 'pointer',
                height: 60, overflow: 'hidden',
              }}>
                <IPCover title={short} size={44} radius={8} hue={pl.hue} cover={pl.cover}/>
                <div style={{
                  fontSize: 12.5, fontWeight: 500, color: IP_THEME.cream, lineHeight: 1.2,
                  display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
                  overflow: 'hidden', minWidth: 0,
                }}>{short}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Подборка для вас */}
      <div style={{ padding: '22px 0 0' }}>
        <div style={{ padding: '0 20px' }}>
          <SectionTitle hint="Все">Для вас</SectionTitle>
        </div>
        <div className="ip-hscroll" style={{
          display: 'flex', gap: 14, padding: '4px 20px 6px', overflowX: 'auto',
        }}>
          {IP_PLAYLISTS.map(pl => (
            <div key={pl.id} onClick={() => openPlaylist(pl)} style={{
              width: 148, flexShrink: 0, cursor: 'pointer',
            }}>
              <div style={{ position: 'relative' }}>
                <BigCover title={pl.title} size={148} hue={pl.hue} cover={pl.cover}/>
              </div>
              <div style={{ fontSize: 13, fontWeight: 600, color: IP_THEME.cream, marginTop: 10, lineHeight: 1.2 }}>{pl.title}</div>
              <div style={{ fontSize: 11, color: IP_THEME.creamDim, marginTop: 2 }}>{pl.subtitle}</div>
            </div>
          ))}
        </div>
      </div>

      {/* Недавно прослушанные */}
      <div style={{ padding: '22px 20px 0' }}>
        <SectionTitle>Недавно слушали</SectionTitle>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
          {IP_RECENT.slice(0, 4).map(t => (
            <TrackRow key={t.id} track={t} onPlay={() => playTrack(t)}/>
          ))}
        </div>
      </div>

      {/* Популярные чтецы */}
      <div style={{ padding: '22px 0 180px' }}>
        <div style={{ padding: '0 20px' }}>
          <SectionTitle>Популярные чтецы</SectionTitle>
        </div>
        <div className="ip-hscroll" style={{ display: 'flex', gap: 12, padding: '4px 20px', overflowX: 'auto' }}>
          {IP_RECITERS.map(r => {
            const selected = r.slug === reciterSlug;
            return (
              <div key={r.id} onClick={() => ctx.setReciterSlug(r.slug)}
                style={{ width: 96, flexShrink: 0, textAlign: 'center', cursor: 'pointer' }}>
                <ReciterAvatar reciter={r} size={96} selected={selected} fontSize={34}/>
                <div style={{ fontSize: 11.5, fontWeight: selected ? 700 : 500, color: selected ? IP_THEME.goldLight : IP_THEME.cream, marginTop: 8, lineHeight: 1.2 }}>{r.name}</div>
                <div style={{ fontSize: 10, color: IP_THEME.creamDim, marginTop: 2 }}>{r.country}</div>
              </div>
            );
          })}
        </div>
      </div>
    </IPScreen>
  );
}

// ── SEARCH
function SearchScreen({ ctx }) {
  const { playTrack, reciterSlug } = ctx;
  const [q, setQ] = React.useState('');
  // Фильтруем треки по выбранному чтецу (если есть)
  const activeTracks = reciterSlug
    ? (IP_YASIN_TRACKS.filter(t => t.reciterSlug === reciterSlug).length
        ? IP_YASIN_TRACKS.filter(t => t.reciterSlug === reciterSlug)
        : IP_YASIN_TRACKS)
    : IP_YASIN_TRACKS;
  const activeReciter = IP_RECITERS.find(r => r.slug === reciterSlug);
  // Popular surah numbers, pulled from real track data
  const POPULAR_SURAHS = [36, 67, 18, 1, 55, 56, 93, 112];
  const TONES = {
    36: 'hsl(20 60% 30%)',  67: 'hsl(45 55% 30%)',  18: 'hsl(95 40% 28%)',  1:  'hsl(150 35% 28%)',
    55: 'hsl(200 40% 28%)', 56: 'hsl(280 30% 28%)', 93: 'hsl(30 60% 32%)',  112:'hsl(340 35% 28%)',
  };
  const popular = POPULAR_SURAHS
    .map(n => activeTracks.find(t => t.surah === n))
    .filter(Boolean);

  const ql = q.trim().toLowerCase();
  const results = ql ? activeTracks.filter(t =>
    String(t.surah).includes(ql) ||
    (t.title || '').toLowerCase().includes(ql) ||
    (t.titleTr || '').toLowerCase().includes(ql) ||
    (t.titleAr || '').includes(q.trim()) ||
    (t.reciter || '').toLowerCase().includes(ql)
  ) : [];
  return (
    <IPScreen>
      <IPTopBar title="Поиск" subtitle="Найдите аудиозаписи"/>
      <div style={{ padding: '0 20px' }}>
        <IPField icon="search" placeholder="Сура, чтец или ключевое слово…" value={q} onChange={setQ}
          trailing={<IPIcon name="mic" size={18} color={IP_THEME.goldLight}/>}
        />
      </div>

      {/* Чтецы — горизонтальная лента с выбором */}
      {IP_RECITERS.length > 1 && (
        <div className="ip-hscroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', padding: '14px 20px 0' }}>
          {IP_RECITERS.map(r => {
            const selected = r.slug === reciterSlug;
            return (
              <button key={r.slug} onClick={() => ctx.setReciterSlug(r.slug)} style={{
                padding: '7px 14px', borderRadius: 999, whiteSpace: 'nowrap',
                background: selected ? 'linear-gradient(180deg, #e9c97a, #b8904a)' : 'rgba(212, 175, 106, 0.08)',
                border: selected ? 'none' : `1px solid ${IP_THEME.line}`,
                color: selected ? '#17130d' : IP_THEME.cream,
                fontSize: 12, fontWeight: 600, cursor: 'pointer', flexShrink: 0,
              }}>{r.name}</button>
            );
          })}
        </div>
      )}

      {!q && (
        <>
          <div style={{ padding: '20px 20px 8px' }}><SectionTitle>Популярное</SectionTitle></div>
          <div style={{ padding: '0 20px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {popular.map(t => (
              <div key={t.id} onClick={() => playTrack(t)} style={{
                height: 92, borderRadius: 14, position: 'relative', overflow: 'hidden', cursor: 'pointer',
                background: `linear-gradient(135deg, ${TONES[t.surah] || 'hsl(30 40% 25%)'} 0%, hsl(20 30% 10%) 120%)`,
                border: `1px solid ${IP_THEME.line}`, padding: 14,
              }}>
                <div style={{ position: 'relative', zIndex: 1 }}>
                  <div style={{ fontSize: 10, color: IP_THEME.creamDim, letterSpacing: '0.15em', textTransform: 'uppercase', marginBottom: 4 }}>
                    Сура {t.surah}
                  </div>
                  <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 18, fontWeight: 600, color: IP_THEME.cream, lineHeight: 1.1 }}>
                    {t.title}
                  </div>
                  <div style={{ fontFamily: 'Amiri, serif', fontSize: 14, color: IP_THEME.goldLight, marginTop: 2 }}>
                    {t.titleAr}
                  </div>
                </div>
                <svg viewBox="0 0 100 100" width="72" height="72" style={{ position: 'absolute', right: -10, bottom: -10, opacity: 0.25 }}>
                  <path d="M50 5 L90 25 L90 75 L50 95 L10 75 L10 25 Z" fill="none" stroke="#e9c97a" strokeWidth="2"/>
                  <path d="M50 20 L75 33 L75 67 L50 80 L25 67 L25 33 Z" fill="none" stroke="#e9c97a" strokeWidth="1.5"/>
                  <circle cx="50" cy="50" r="8" fill="none" stroke="#e9c97a" strokeWidth="1.5"/>
                </svg>
              </div>
            ))}
          </div>

          <div style={{ padding: '24px 20px 8px' }}>
            <SectionTitle>{activeReciter ? `Все суры — ${activeReciter.name}` : 'Все 114 сур'}</SectionTitle>
          </div>
          <div style={{ padding: '0 20px 8px', display: 'flex', flexDirection: 'column', gap: 2 }}>
            {activeTracks.slice(0, 12).map(t => (
              <TrackRow key={t.id} track={t} onPlay={() => playTrack(t)}/>
            ))}
            {activeTracks.length > 12 && (
              <div style={{ fontSize: 11, color: IP_THEME.creamDim, textAlign: 'center', padding: 10 }}>
                Воспользуйтесь поиском, чтобы найти любую из {activeTracks.length} сур
              </div>
            )}
          </div>

          <div style={{ padding: '24px 20px 8px' }}><SectionTitle>По чтецам</SectionTitle></div>
          <div style={{ padding: '0 20px 180px' }}>
            {IP_RECITERS.slice(0, 5).map(r => (
              <div key={r.id} onClick={() => ctx.setReciterSlug(r.slug)} style={{
                display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer',
                padding: '10px 4px', borderBottom: `1px solid ${IP_THEME.line}`,
              }}>
                <ReciterAvatar reciter={r} size={44} fontSize={16}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: IP_THEME.cream }}>{r.name}</div>
                  <div style={{ fontSize: 11, color: IP_THEME.creamDim }}>{r.style} · {r.country}</div>
                </div>
                <IPIcon name="more" size={18} color={IP_THEME.creamDim}/>
              </div>
            ))}
          </div>
        </>
      )}

      {q && (
        <div style={{ padding: '16px 20px 180px' }}>
          <div style={{ fontSize: 11, color: IP_THEME.creamDim, letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 10 }}>
            Найдено: {results.length}
          </div>
          {results.map(t => <TrackRow key={t.id} track={t} onPlay={() => playTrack(t)}/>)}
        </div>
      )}
    </IPScreen>
  );
}

// ── LIBRARY
function LibraryScreen({ ctx }) {
  const { openPlaylist, refreshPlaylists } = ctx;
  const [filter, setFilter] = React.useState('Все');
  const [createOpen, setCreateOpen] = React.useState(false);
  const [actionPl, setActionPl] = React.useState(null);      // playlist that the action sheet is for
  const [renameOpen, setRenameOpen] = React.useState(false);
  const [deleteOpen, setDeleteOpen] = React.useState(false);
  const [, bump] = React.useReducer(x => x + 1, 0);

  async function create(title) {
    if (!title) return;
    await IP_API.createPlaylist(title);
    setCreateOpen(false);
    await refreshPlaylists();
    bump();
  }
  async function rename(title) {
    if (!title || !actionPl) return;
    await IP_API.renamePlaylist(actionPl.id, title);
    setRenameOpen(false); setActionPl(null);
    await refreshPlaylists(); bump();
  }
  async function destroy() {
    if (!actionPl) return;
    await IP_API.deletePlaylist(actionPl.id);
    setDeleteOpen(false); setActionPl(null);
    await refreshPlaylists(); bump();
  }

  const filters = ['Все', 'Мои', 'Системные'];
  const filtered = IP_PLAYLISTS.filter(p => {
    if (filter === 'Мои') return p.mine;
    if (filter === 'Системные') return !p.mine;
    return true;
  });

  return (
    <IPScreen>
      <IPTopBar
        title="Моя библиотека"
        subtitle="Сохранённые плейлисты"
        right={<button onClick={() => setCreateOpen(true)} style={{
          width: 36, height: 36, borderRadius: 12,
          background: 'rgba(212, 175, 106, 0.08)',
          border: `1px solid ${IP_THEME.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><IPIcon name="plus" size={18} color={IP_THEME.goldLight}/></button>}
      />
      <div style={{ padding: '0 20px' }}>
        <div className="ip-hscroll" style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 6 }}>
          {filters.map(f => (
            <button key={f} onClick={() => setFilter(f)} style={{
              padding: '7px 14px', borderRadius: 999,
              background: filter === f ? 'linear-gradient(180deg, #e9c97a, #b8904a)' : 'rgba(212, 175, 106, 0.08)',
              border: filter === f ? 'none' : `1px solid ${IP_THEME.line}`,
              color: filter === f ? '#17130d' : IP_THEME.cream,
              fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap',
            }}>{f}</button>
          ))}
        </div>
      </div>

      <div style={{ padding: '16px 20px 180px', display: 'flex', flexDirection: 'column', gap: 6 }}>
        {filtered.length === 0 && (
          <div style={{ textAlign: 'center', padding: '40px 20px', color: IP_THEME.creamDim, fontSize: 13 }}>
            Плейлистов нет.<br/>Нажмите «+» чтобы создать.
          </div>
        )}
        {filtered.map(pl => (
          <div key={pl.id} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '8px 6px',
          }}>
            <div onClick={() => openPlaylist(pl)} style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1, cursor: 'pointer', minWidth: 0 }}>
              <BigCover title={pl.title} size={60} hue={pl.hue} cover={pl.cover}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{
                  fontSize: 14, fontWeight: 600, color: IP_THEME.cream,
                  display: 'flex', alignItems: 'center', gap: 6,
                }}>
                  {pl.pinned && <svg width="11" height="11" viewBox="0 0 24 24" fill={IP_THEME.goldLight}><path d="M16 12V4h1V2H7v2h1v8l-2 2v2h5v7l1 1 1-1v-7h5v-2z"/></svg>}
                  {pl.title}
                </div>
                <div style={{ fontSize: 12, color: IP_THEME.creamDim, marginTop: 2 }}>
                  Плейлист{pl.subtitle ? ' · ' + pl.subtitle : ''} · {pl.count || 0} записей
                </div>
              </div>
            </div>
            {pl.mine && (
              <button onClick={() => setActionPl(pl)} style={{
                background: 'transparent', border: 'none', cursor: 'pointer', padding: 8,
              }}>
                <IPIcon name="more" size={18} color={IP_THEME.creamDim}/>
              </button>
            )}
          </div>
        ))}
      </div>

      <IPPrompt
        open={createOpen}
        title="Новый плейлист"
        placeholder="Название"
        onCancel={() => setCreateOpen(false)}
        onSubmit={create}
        submitLabel="Создать"
      />
      <IPSheet
        open={!!actionPl && !renameOpen && !deleteOpen}
        onClose={() => setActionPl(null)}
        title={actionPl?.title}
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <IPButton variant="ghost" onClick={() => setRenameOpen(true)}>Переименовать</IPButton>
          <IPButton variant="danger" onClick={() => setDeleteOpen(true)}>Удалить плейлист</IPButton>
          <IPButton variant="outline" onClick={() => setActionPl(null)}>Закрыть</IPButton>
        </div>
      </IPSheet>
      <IPPrompt
        open={renameOpen}
        title="Переименовать"
        defaultValue={actionPl?.title}
        onCancel={() => setRenameOpen(false)}
        onSubmit={rename}
        submitLabel="Сохранить"
      />
      <IPConfirm
        open={deleteOpen}
        title="Удалить плейлист?"
        message="Это действие нельзя отменить."
        onCancel={() => setDeleteOpen(false)}
        onConfirm={destroy}
        confirmLabel="Удалить"
        danger
      />
    </IPScreen>
  );
}

// ── PROFILE
function ProfileScreen({ ctx }) {
  const { user, onLogout, reciterSlug, setReciterSlug } = ctx;
  const [s, setS] = React.useState({ plays: 0, uniqueTracks: 0, favorites: 0, listenDays: 0, joined: null });
  const [reciterPickerOpen, setReciterPickerOpen] = React.useState(false);
  React.useEffect(() => { IP_API.stats().then(setS); }, []);
  const stats = [
    { label: 'Прослушано', value: String(s.plays) },
    { label: 'Избранное',  value: String(s.favorites) },
    { label: 'Дней',       value: String(s.listenDays) },
  ];
  const joinedLabel = s.joined
    ? new Date(s.joined).toLocaleDateString('ru-RU', { month: 'long', year: 'numeric' })
    : '—';
  const currentReciter = IP_RECITERS.find(r => r.slug === reciterSlug) || IP_RECITERS[0];
  const defaultReciter = currentReciter?.name || '—';
  return (
    <IPScreen>
      <IPTopBar title="Профиль" subtitle="Ваш духовный путь"
        right={<button style={{
          width: 36, height: 36, borderRadius: 12,
          background: 'rgba(212, 175, 106, 0.08)',
          border: `1px solid ${IP_THEME.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
        }}><IPIcon name="settings" size={18} color={IP_THEME.goldLight}/></button>}
      />

      {/* Avatar + identity */}
      <div style={{ textAlign: 'center', padding: '4px 20px 24px' }}>
        <div style={{ display: 'inline-block', position: 'relative' }}>
          <div style={{
            width: 108, height: 108, borderRadius: '50%',
            background: 'linear-gradient(135deg, #3a2a10, #15100a)',
            border: `2px solid ${IP_THEME.gold}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'Amiri, serif', fontSize: 44, color: IP_THEME.goldLight,
            boxShadow: '0 0 32px rgba(212, 175, 106, 0.3)',
          }}>{user.name.split(' ').map(w => w[0]).slice(0, 2).join('')}</div>
        </div>
        <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 26, fontWeight: 600, color: IP_THEME.cream, marginTop: 12 }}>
          {user.name}
        </div>
        <div style={{ fontSize: 12.5, color: IP_THEME.creamMute, marginTop: 2 }}>
          {user.email} · С нами с {joinedLabel}
        </div>
      </div>

      {/* Stats */}
      <div style={{ padding: '0 20px' }}>
        <div style={{
          display: 'grid', gridTemplateColumns: '1fr 1fr 1fr',
          background: 'rgba(212, 175, 106, 0.05)',
          border: `1px solid ${IP_THEME.line}`,
          borderRadius: 16, padding: '18px 10px',
        }}>
          {stats.map((s, i) => (
            <div key={s.label} style={{
              textAlign: 'center',
              borderRight: i < stats.length - 1 ? `1px solid ${IP_THEME.line}` : 'none',
            }}>
              <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 28, fontWeight: 600, color: IP_THEME.goldLight }}>
                {s.value}
              </div>
              <div style={{ fontSize: 10.5, color: IP_THEME.creamDim, letterSpacing: '0.1em', textTransform: 'uppercase', marginTop: 2 }}>
                {s.label}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Menu */}
      <div style={{ padding: '20px 20px 180px' }}>
        <MenuGroup title="Настройки" items={[
          { icon: 'globe', label: 'Язык', meta: 'Русский · العربية' },
          { icon: 'mic', label: 'Чтец по умолчанию', meta: defaultReciter, onClick: () => setReciterPickerOpen(true) },
          { icon: 'moon', label: 'Тёмная тема', meta: 'Включено' },
          { icon: 'book', label: 'Всего сур', meta: `${IP_YASIN_TRACKS.length} доступно` },
        ]}/>
        <MenuGroup title="Аккаунт" items={[
          { icon: 'user', label: 'Редактировать профиль' },
          { icon: 'lock', label: 'Конфиденциальность' },
          { icon: 'book', label: 'Всего прослушиваний', meta: String(s.plays) },
        ]}/>
        <div style={{ marginTop: 16 }}>
          <IPButton variant="danger" icon="logout" onClick={onLogout}>Выйти</IPButton>
        </div>
        <div style={{ textAlign: 'center', marginTop: 16, fontFamily: 'Amiri, serif', fontSize: 13, color: IP_THEME.creamDim }}>
          جزاك الله خيراً
        </div>
      </div>

      <IPSheet open={reciterPickerOpen} onClose={() => setReciterPickerOpen(false)} title="Чтец по умолчанию">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {IP_RECITERS.map(r => {
            const selected = r.slug === reciterSlug;
            return (
              <button key={r.slug} onClick={() => { setReciterSlug(r.slug); setReciterPickerOpen(false); }} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: selected ? 'rgba(212, 175, 106, 0.10)' : 'transparent',
                border: `1px solid ${selected ? IP_THEME.lineStrong : 'transparent'}`,
                borderRadius: 12, padding: '12px 12px', cursor: 'pointer', textAlign: 'left',
              }}>
                <ReciterAvatar reciter={r} size={44} fontSize={16}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: IP_THEME.cream }}>{r.name}</div>
                  <div style={{ fontSize: 11, color: IP_THEME.creamDim }}>{r.style} · {r.country}</div>
                </div>
                {selected && <IPIcon name="check" size={18} color={IP_THEME.goldLight} stroke={2.4}/>}
              </button>
            );
          })}
        </div>
      </IPSheet>
    </IPScreen>
  );
}

// ── PLAYLIST DETAIL
function PlaylistScreen({ ctx, playlist }) {
  const { back, playTrack, currentTrack, refreshPlaylists, openPlaylist } = ctx;
  const [tracks, setTracks] = React.useState(playlist.tracks || []);
  React.useEffect(() => { setTracks(playlist.tracks || []); }, [playlist]);

  async function removeTrack(t) {
    if (!playlist.mine) return;
    await IP_API.removeTrackFromPlaylist(playlist.id, t.id);
    setTracks(ts => ts.filter(x => x.id !== t.id));
    refreshPlaylists && refreshPlaylists();
  }

  return (
    <IPScreen noPattern>
      {/* Hero */}
      <div style={{
        position: 'relative', padding: `calc(20px + env(safe-area-inset-top, 0px)) 20px 20px`,
        background: `linear-gradient(180deg, hsl(${30 + playlist.hue * 0.3} 40% 22%) 0%, transparent 100%)`,
      }}>
        <IPPattern opacity={0.06}/>
        <div style={{ position: 'relative', zIndex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
            <button onClick={back} style={{
              width: 36, height: 36, borderRadius: 12,
              background: 'rgba(15, 13, 10, 0.5)',
              border: `1px solid ${IP_THEME.line}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
              backdropFilter: 'blur(8px)',
            }}><IPIcon name="back" size={18} color={IP_THEME.cream}/></button>
            <IPIcon name="more" size={22} color={IP_THEME.cream}/>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
            <BigCover title={playlist.title} size={160} hue={playlist.hue} cover={playlist.cover}/>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontSize: 10.5, letterSpacing: '0.18em', color: IP_THEME.goldLight, textTransform: 'uppercase', fontWeight: 600 }}>
                Плейлист
              </div>
              <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 24, fontWeight: 600, color: IP_THEME.cream, lineHeight: 1.15, marginTop: 4, textWrap: 'balance', maxWidth: 260 }}>
                {playlist.title}
              </div>
              <div style={{ fontSize: 12, color: IP_THEME.creamMute, marginTop: 6 }}>{playlist.subtitle}</div>
            </div>
          </div>
          {/* Action buttons */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 20 }}>
            <IPIcon name="heart-fill" size={26} color={IP_THEME.gold}/>
            <IPIcon name="download" size={22} color={IP_THEME.cream}/>
            <IPIcon name="share" size={22} color={IP_THEME.cream}/>
            <IPIcon name="more" size={22} color={IP_THEME.cream}/>
            <div style={{ flex: 1 }}/>
            <IPIcon name="shuffle" size={22} color={IP_THEME.goldLight}/>
            <button onClick={() => tracks[0] && playTrack(tracks[0])} disabled={!tracks.length} style={{
              width: 54, height: 54, borderRadius: '50%',
              background: 'linear-gradient(180deg, #e9c97a, #b8904a)',
              border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center',
              cursor: tracks.length ? 'pointer' : 'not-allowed',
              opacity: tracks.length ? 1 : 0.4,
              boxShadow: '0 8px 20px rgba(212, 175, 106, 0.4)',
            }}>
              <IPIcon name="play" size={24} color="#17130d"/>
            </button>
          </div>
        </div>
      </div>

      {/* Track list */}
      <div style={{ padding: '12px 20px 200px' }}>
        {tracks.length === 0 && (
          <div style={{ textAlign: 'center', padding: '30px 16px', color: IP_THEME.creamDim, fontSize: 13 }}>
            {playlist.mine ? 'Плейлист пуст. Откройте суру и нажмите «⋯» → «Добавить в плейлист».' : 'Плейлист пуст.'}
          </div>
        )}
        {tracks.map((t, i) => (
          <TrackRow
            key={t.id + '-' + i}
            track={t}
            index={i + 1}
            showIndex
            onPlay={() => playTrack(t)}
            active={currentTrack && currentTrack.id === t.id}
            onRemoveFromPlaylist={playlist.mine ? () => removeTrack(t) : null}
          />
        ))}
      </div>
    </IPScreen>
  );
}

// ── FULL PLAYER
function FullPlayerScreen({ ctx }) {
  const { currentTrack, playing, togglePlay, progress, setProgress, duration, next, prev, closePlayer } = ctx;
  const [shuffle, setShuffle] = React.useState(false);
  const [repeat, setRepeat] = React.useState(false);
  const [fav, setFav] = React.useState(!!currentTrack?.favorite);
  const [addOpen, setAddOpen] = React.useState(false);
  const [queueOpen, setQueueOpen] = React.useState(false);
  const [shareMsg, setShareMsg] = React.useState(null);

  // Keep fav icon in sync when current track changes
  React.useEffect(() => { setFav(!!currentTrack?.favorite); }, [currentTrack?.id]);

  if (!currentTrack) return null;

  const myPlaylists = IP_PLAYLISTS.filter(p => p.mine);

  async function addTo(pl) {
    await IP_API.addTrackToPlaylist(pl.id, currentTrack.id);
    setAddOpen(false);
    setShareMsg('Добавлено в «' + pl.title + '»');
    setTimeout(() => setShareMsg(null), 2500);
  }

  async function share() {
    const url = location.origin + currentTrack.audioUrl;
    const data = {
      title: 'Ислам Плей — ' + currentTrack.title,
      text: `${currentTrack.title} · ${currentTrack.reciter}`,
      url,
    };
    try {
      if (navigator.share) {
        await navigator.share(data);
      } else {
        await navigator.clipboard.writeText(url);
        setShareMsg('Ссылка скопирована');
        setTimeout(() => setShareMsg(null), 2500);
      }
    } catch {}
  }

  function download() {
    const a = document.createElement('a');
    a.href = currentTrack.audioUrl;
    a.download = `${String(currentTrack.surah).padStart(3, '0')}-${currentTrack.title}.mp3`;
    document.body.appendChild(a);
    a.click();
    a.remove();
  }

  // Prefer real audio duration from <audio>, fall back to server-provided length
  const totalSec = duration || currentTrack.length || 0;
  const curSec = totalSec ? Math.floor(totalSec * progress) : 0;
  const fmt = s => {
    if (!s || !Number.isFinite(s)) return '--:--';
    return `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
  };
  return (
    <IPScreen noPattern style={{
      background: 'radial-gradient(ellipse at top, #3a2a10 0%, #1a1208 55%, #000 100%)',
    }}>
      <IPPattern opacity={0.07}/>
      <div style={{ position: 'relative', zIndex: 1, padding: `calc(20px + env(safe-area-inset-top, 0px)) 24px 40px`, minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
        {/* Header */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <button onClick={closePlayer} style={{
            width: 36, height: 36, borderRadius: 12,
            background: 'rgba(15, 13, 10, 0.5)',
            border: `1px solid ${IP_THEME.line}`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer',
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={IP_THEME.cream} strokeWidth="2" strokeLinecap="round"><path d="M6 9l6 6 6-6"/></svg>
          </button>
          <div style={{ textAlign: 'center', flex: 1 }}>
            <div style={{ fontSize: 10.5, letterSpacing: '0.18em', color: IP_THEME.creamMute, textTransform: 'uppercase' }}>Сейчас играет</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: IP_THEME.cream, marginTop: 2 }}>{currentTrack.title}</div>
          </div>
          <IPIcon name="more" size={22} color={IP_THEME.cream}/>
        </div>

        {/* Cover art — mihrab */}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '30px 0' }}>
          <IPMihrab size={230}>
            <div style={{ textAlign: 'center' }}>
              <div style={{ fontFamily: 'Amiri, serif', fontSize: 56, color: IP_THEME.goldLight, fontWeight: 700, lineHeight: 1, textShadow: '0 0 24px rgba(212, 175, 106, 0.4)' }}>{currentTrack.titleAr || '﷽'}</div>
              <div style={{ fontSize: 9.5, color: IP_THEME.creamMute, letterSpacing: '0.25em', marginTop: 10, textTransform: 'uppercase' }}>
                {currentTrack.surah ? `Сура ${currentTrack.surah}` : ''}
              </div>
            </div>
          </IPMihrab>
        </div>

        {/* Title + reciter */}
        <div style={{ textAlign: 'center', marginBottom: 4 }}>
          <div style={{ fontFamily: 'Cormorant Garamond, serif', fontSize: 24, fontWeight: 600, color: IP_THEME.cream, lineHeight: 1.2 }}>
            {currentTrack.title}
          </div>
          <div style={{ fontSize: 13, color: IP_THEME.goldLight, marginTop: 6, fontWeight: 500 }}>
            {currentTrack.reciter}
          </div>
        </div>

        {/* Progress bar */}
        <div style={{ margin: '24px 0 4px' }}>
          <div onClick={e => {
            const r = e.currentTarget.getBoundingClientRect();
            setProgress(Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)));
          }} style={{
            height: 4, background: 'rgba(212, 175, 106, 0.15)',
            borderRadius: 2, position: 'relative', cursor: 'pointer',
          }}>
            <div style={{
              position: 'absolute', left: 0, top: 0, bottom: 0, width: `${progress * 100}%`,
              background: 'linear-gradient(90deg, #d4af6a, #e9c97a)', borderRadius: 2,
            }}/>
            <div style={{
              position: 'absolute', left: `calc(${progress * 100}% - 7px)`, top: -5,
              width: 14, height: 14, borderRadius: '50%',
              background: '#e9c97a',
              boxShadow: '0 2px 8px rgba(212, 175, 106, 0.6)',
            }}/>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontSize: 11, color: IP_THEME.creamDim, fontVariantNumeric: 'tabular-nums' }}>
            <span>{fmt(curSec)}</span>
            <span>{currentTrack.verses} аятов</span>
            <span>{totalSec ? '-' + fmt(totalSec - curSec) : fmt(totalSec)}</span>
          </div>
        </div>

        {/* Controls */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 24 }}>
          <button onClick={() => setShuffle(!shuffle)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 8 }}>
            <IPIcon name="shuffle" size={22} color={shuffle ? IP_THEME.goldLight : IP_THEME.creamMute}/>
          </button>
          <button onClick={prev} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 8 }}>
            <IPIcon name="prev" size={30} color={IP_THEME.cream}/>
          </button>
          <button onClick={togglePlay} style={{
            width: 72, height: 72, borderRadius: '50%',
            background: 'linear-gradient(180deg, #e9c97a, #b8904a)',
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            boxShadow: '0 10px 30px rgba(212, 175, 106, 0.5)',
          }}>
            <IPIcon name={playing ? 'pause' : 'play'} size={32} color="#17130d"/>
          </button>
          <button onClick={next} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 8 }}>
            <IPIcon name="next" size={30} color={IP_THEME.cream}/>
          </button>
          <button onClick={() => setRepeat(!repeat)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', padding: 8 }}>
            <IPIcon name="repeat" size={22} color={repeat ? IP_THEME.goldLight : IP_THEME.creamMute}/>
          </button>
        </div>

        {/* Footer actions */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 28, padding: '0 6px' }}>
          <FooterBtn onClick={() => { const nv = !fav; setFav(nv); IP_API.favorite(currentTrack.id, nv); }}
            icon={fav ? 'heart-fill' : 'heart'} size={22} color={fav ? IP_THEME.gold : IP_THEME.creamMute}
            label={fav ? 'В избранном' : 'В избранное'}/>
          <FooterBtn onClick={download} icon="download" color={IP_THEME.creamMute} label="Скачать"/>
          <FooterBtn onClick={() => setAddOpen(true)} icon="plus" color={IP_THEME.creamMute} label="В плейлист"/>
          <FooterBtn onClick={() => setQueueOpen(true)} icon="queue" color={IP_THEME.creamMute} label="Очередь"/>
          <FooterBtn onClick={share} icon="share" color={IP_THEME.creamMute} label="Поделиться"/>
        </div>

        {shareMsg && (
          <div style={{
            position: 'absolute', left: '50%', bottom: 20, transform: 'translateX(-50%)',
            background: 'rgba(212, 175, 106, 0.95)', color: '#17130d',
            padding: '10px 18px', borderRadius: 999,
            fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap',
            boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
            animation: 'ipFade 0.2s ease-out',
          }}>{shareMsg}</div>
        )}
      </div>

      {/* Add-to-playlist sheet */}
      <IPSheet open={addOpen} onClose={() => setAddOpen(false)} title="Добавить в плейлист">
        {myPlaylists.length === 0 ? (
          <div style={{ fontSize: 13, color: IP_THEME.creamDim, textAlign: 'center', padding: '16px 0 20px' }}>
            У вас ещё нет плейлистов.<br/>Создайте в «Моей библиотеке».
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2, maxHeight: 400, overflowY: 'auto' }}>
            {myPlaylists.map(pl => (
              <button key={pl.id} onClick={() => addTo(pl)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: 'transparent', border: 'none', cursor: 'pointer',
                padding: '12px 8px', textAlign: 'left',
              }}>
                <BigCover title={pl.title} size={42} hue={pl.hue} cover={pl.cover}/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, color: IP_THEME.cream, fontWeight: 500 }}>{pl.title}</div>
                  <div style={{ fontSize: 11, color: IP_THEME.creamDim }}>{pl.count || 0} записей</div>
                </div>
                <IPIcon name="plus" size={18} color={IP_THEME.goldLight}/>
              </button>
            ))}
          </div>
        )}
      </IPSheet>

      {/* Queue sheet — next tracks */}
      <IPSheet open={queueOpen} onClose={() => setQueueOpen(false)} title="Очередь">
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2, maxHeight: 420, overflowY: 'auto' }}>
          {IP_YASIN_TRACKS.slice(
            Math.max(0, IP_YASIN_TRACKS.findIndex(t => t.id === currentTrack.id)),
            Math.max(0, IP_YASIN_TRACKS.findIndex(t => t.id === currentTrack.id)) + 20
          ).map((t, i) => (
            <div key={t.id} onClick={() => { ctx.playTrack(t); setQueueOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              padding: '10px 8px', cursor: 'pointer', borderRadius: 8,
              background: t.id === currentTrack.id ? 'rgba(212, 175, 106, 0.08)' : 'transparent',
            }}>
              <div style={{
                width: 28, textAlign: 'center',
                fontFamily: 'Cormorant Garamond, serif', fontSize: 15,
                color: t.id === currentTrack.id ? IP_THEME.goldLight : IP_THEME.creamDim,
              }}>{i === 0 ? '▶' : t.surah}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13.5, fontWeight: 500,
                  color: t.id === currentTrack.id ? IP_THEME.goldLight : IP_THEME.cream,
                  whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {t.title}
                </div>
                <div style={{ fontSize: 11, color: IP_THEME.creamDim }}>{t.reciter}</div>
              </div>
            </div>
          ))}
        </div>
      </IPSheet>
    </IPScreen>
  );
}

// Footer button — icon with small label below
function FooterBtn({ onClick, icon, size = 20, color, label }) {
  return (
    <button onClick={onClick} style={{
      background: 'transparent', border: 'none', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
      padding: '6px 4px', minWidth: 52,
    }}>
      <IPIcon name={icon} size={size} color={color}/>
      <span style={{ fontSize: 9.5, color: IP_THEME.creamDim, letterSpacing: '0.05em' }}>{label}</span>
    </button>
  );
}

// ── Helpers
function SectionTitle({ children, hint }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', margin: '0 0 12px' }}>
      <div style={{
        fontFamily: 'Cormorant Garamond, serif', fontSize: 18, fontWeight: 600, color: IP_THEME.cream,
      }}>{children}</div>
      {hint && <div style={{ fontSize: 11, color: IP_THEME.goldLight, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{hint}</div>}
    </div>
  );
}

// Circular reciter avatar. Shows the real photo when available, otherwise
// a gold-on-dark monogram derived from the name.
function ReciterAvatar({ reciter, size = 44, fontSize, selected = false }) {
  const photo = reciter?.photo;
  const initials = (reciter?.name || '').split(' ').map(w => w[0]).slice(0, 2).join('');
  const borderWidth = size >= 80 ? 2 : 1;
  const common = {
    width: size, height: size, borderRadius: '50%',
    border: `${borderWidth}px solid ${selected ? IP_THEME.gold : IP_THEME.lineStrong}`,
    flexShrink: 0,
    boxShadow: selected ? '0 6px 20px rgba(212, 175, 106, 0.45)' : '0 4px 14px rgba(0,0,0,0.35)',
    overflow: 'hidden',
    position: 'relative',
  };
  if (photo) {
    return (
      <div style={{
        ...common,
        background: `#1a160f url(${photo}) center/cover no-repeat`,
      }}/>
    );
  }
  return (
    <div style={{
      ...common,
      background: 'linear-gradient(135deg, hsl(30 40% 22%), hsl(18 50% 12%))',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: 'Amiri, serif',
      fontSize: fontSize || Math.round(size * 0.36),
      color: IP_THEME.goldLight,
    }}>{initials}</div>
  );
}

function BigCover({ title, size = 148, hue = 0, cover }) {
  const seed = [...(title || '')].reduce((a, c) => a + c.charCodeAt(0), 0) + hue;
  const baseStyle = {
    width: size, height: size, borderRadius: 14,
    position: 'relative', overflow: 'hidden',
    border: `1px solid ${IP_THEME.lineStrong}`,
    boxShadow: '0 8px 24px rgba(0,0,0,0.45)',
    flexShrink: 0,
  };
  // When a real image is provided, show it with a subtle inner border + gradient overlay
  if (cover) {
    return (
      <div style={{
        ...baseStyle,
        background: `#1a160f url(${cover}) center/cover no-repeat`,
      }}>
        <div style={{
          position: 'absolute', inset: 0,
          background: 'linear-gradient(180deg, transparent 55%, rgba(0,0,0,0.35) 100%)',
          pointerEvents: 'none',
        }}/>
      </div>
    );
  }
  // Fallback — generative Islamic pattern tile
  return (
    <div style={{
      ...baseStyle,
      background: `linear-gradient(135deg, hsl(${30 + hue * 0.3} 45% 24%) 0%, hsl(${18 + hue * 0.2} 55% 10%) 100%)`,
    }}>
      <svg width="100%" height="100%" viewBox="0 0 120 120" style={{ position: 'absolute', inset: 0, opacity: 0.45 }}>
        <defs>
          <pattern id={`bc-${seed}`} width="30" height="30" patternUnits="userSpaceOnUse">
            <path d="M15 2l12 13-12 13-12-13z" fill="none" stroke="#e9c97a" strokeWidth="0.6"/>
            <path d="M15 9l6 6-6 6-6-6z" fill="none" stroke="#d4af6a" strokeWidth="0.5"/>
            <circle cx="15" cy="15" r="1.5" fill="#d4af6a" opacity="0.7"/>
          </pattern>
        </defs>
        <rect width="120" height="120" fill={`url(#bc-${seed})`}/>
      </svg>
      <svg viewBox="0 0 100 100" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        <path d="M50 20 C 62 20, 70 30, 70 44 L 70 80 L 30 80 L 30 44 C 30 30, 38 20, 50 20 Z"
              fill="none" stroke="#e9c97a" strokeWidth="0.8" opacity="0.5"/>
      </svg>
      <div style={{
        position: 'absolute', inset: 0, display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        fontFamily: 'Amiri, serif', color: IP_THEME.goldLight,
        fontSize: size * 0.24, fontWeight: 700,
        textShadow: '0 2px 10px rgba(0,0,0,0.7)',
      }}>
        {(title || '').charAt(0)}
      </div>
    </div>
  );
}

function TrackRow({ track, onPlay, index, showIndex, active, onRemoveFromPlaylist }) {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [pickerOpen, setPickerOpen] = React.useState(false);

  async function addTo(pl) {
    try {
      await IP_API.addTrackToPlaylist(pl.id, track.id);
      setPickerOpen(false);
      setMenuOpen(false);
    } catch {}
  }

  const myPlaylists = IP_PLAYLISTS.filter(p => p.mine);

  return (
    <>
      <div onClick={onPlay} style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '10px 6px', cursor: 'pointer',
        borderRadius: 10,
        background: active ? 'rgba(212, 175, 106, 0.08)' : 'transparent',
      }}>
        {showIndex ? (
          <div style={{
            width: 28, textAlign: 'center',
            fontFamily: 'Cormorant Garamond, serif', fontSize: 16,
            color: active ? IP_THEME.goldLight : IP_THEME.creamDim,
          }}>{index}</div>
        ) : (
          <IPCover title={track.title} size={44} radius={8}/>
        )}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 13.5, fontWeight: 500,
            color: active ? IP_THEME.goldLight : IP_THEME.cream,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{track.title}</div>
          <div style={{
            fontSize: 11.5, color: IP_THEME.creamDim, marginTop: 2,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            {track.downloaded && (
              <svg width="10" height="10" viewBox="0 0 24 24" fill={IP_THEME.goldLight}><circle cx="12" cy="12" r="10"/><path d="M16 10l-5 6-3-3" stroke="#17130d" strokeWidth="2.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            )}
            {track.reciter}{track.duration ? ' · ' + track.duration : ''}
          </div>
        </div>
        {track.favorite && <IPIcon name="heart-fill" size={14} color={IP_THEME.gold}/>}
        <button onClick={e => { e.stopPropagation(); setMenuOpen(true); }} style={{
          background: 'transparent', border: 'none', cursor: 'pointer', padding: 8,
        }}>
          <IPIcon name="more" size={18} color={IP_THEME.creamDim}/>
        </button>
      </div>

      <IPSheet open={menuOpen} onClose={() => setMenuOpen(false)} title={track.title}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <IPButton variant="ghost" icon="play" onClick={() => { setMenuOpen(false); onPlay(); }}>Слушать</IPButton>
          <IPButton variant="ghost" icon="plus" onClick={() => setPickerOpen(true)}>Добавить в плейлист</IPButton>
          <IPButton variant="ghost" icon="heart" onClick={async () => { await IP_API.favorite(track.id, !track.favorite); setMenuOpen(false); }}>
            {track.favorite ? 'Убрать из избранного' : 'В избранное'}
          </IPButton>
          {onRemoveFromPlaylist && (
            <IPButton variant="danger" onClick={() => { onRemoveFromPlaylist(); setMenuOpen(false); }}>Убрать из плейлиста</IPButton>
          )}
          <IPButton variant="outline" onClick={() => setMenuOpen(false)}>Закрыть</IPButton>
        </div>
      </IPSheet>

      <IPSheet open={pickerOpen} onClose={() => setPickerOpen(false)} title="Выберите плейлист">
        {myPlaylists.length === 0 && (
          <div style={{ fontSize: 13, color: IP_THEME.creamDim, textAlign: 'center', padding: 16 }}>
            У вас ещё нет плейлистов.<br/>Создайте в «Моей библиотеке».
          </div>
        )}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2, maxHeight: 360, overflowY: 'auto' }}>
          {myPlaylists.map(pl => (
            <button key={pl.id} onClick={() => addTo(pl)} style={{
              display: 'flex', alignItems: 'center', gap: 12,
              background: 'transparent', border: 'none', cursor: 'pointer',
              padding: '12px 8px', textAlign: 'left',
            }}>
              <BigCover title={pl.title} size={40} hue={pl.hue} cover={pl.cover}/>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, color: IP_THEME.cream, fontWeight: 500 }}>{pl.title}</div>
                <div style={{ fontSize: 11, color: IP_THEME.creamDim }}>{pl.count || 0} записей</div>
              </div>
            </button>
          ))}
        </div>
      </IPSheet>
    </>
  );
}

function MenuGroup({ title, items }) {
  return (
    <div style={{ marginBottom: 20 }}>
      <div style={{ fontSize: 11, color: IP_THEME.creamDim, letterSpacing: '0.15em', textTransform: 'uppercase', fontWeight: 500, margin: '0 4px 8px' }}>
        {title}
      </div>
      <div style={{
        background: 'rgba(212, 175, 106, 0.04)',
        border: `1px solid ${IP_THEME.line}`,
        borderRadius: 14, overflow: 'hidden',
      }}>
        {items.map((item, i) => (
          <div key={item.label} onClick={item.onClick} style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '14px 14px',
            borderBottom: i < items.length - 1 ? `1px solid ${IP_THEME.line}` : 'none',
            cursor: item.onClick ? 'pointer' : 'default',
          }}>
            <IPIcon name={item.icon} size={18} color={IP_THEME.goldLight}/>
            <div style={{ flex: 1, fontSize: 14, color: IP_THEME.cream }}>{item.label}</div>
            {item.meta && <div style={{ fontSize: 12, color: IP_THEME.creamDim }}>{item.meta}</div>}
            <IPIcon name="back" size={14} color={IP_THEME.creamDim} style={{ transform: 'rotate(180deg)' }}/>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { HomeScreen, SearchScreen, LibraryScreen, ProfileScreen, PlaylistScreen, FullPlayerScreen, TrackRow });
