/* IslamPlay — API client + Russian translations */

// ── Russian names for all 114 surahs
const SURAH_RU = {
  1: 'Аль-Фатиха', 2: 'Аль-Бакара', 3: 'Аль Имран', 4: 'Ан-Ниса', 5: 'Аль-Маида',
  6: 'Аль-Анам', 7: 'Аль-Араф', 8: 'Аль-Анфаль', 9: 'Ат-Тауба', 10: 'Юнус',
  11: 'Худ', 12: 'Юсуф', 13: 'Ар-Раад', 14: 'Ибрахим', 15: 'Аль-Хиджр',
  16: 'Ан-Нахль', 17: 'Аль-Исра', 18: 'Аль-Кахф', 19: 'Марьям', 20: 'Та-Ха',
  21: 'Аль-Анбия', 22: 'Аль-Хадж', 23: 'Аль-Муминун', 24: 'Ан-Нур', 25: 'Аль-Фуркан',
  26: 'Аш-Шуара', 27: 'Ан-Намль', 28: 'Аль-Касас', 29: 'Аль-Анкабут', 30: 'Ар-Рум',
  31: 'Лукман', 32: 'Ас-Саджда', 33: 'Аль-Ахзаб', 34: 'Саба', 35: 'Фатыр',
  36: 'Йа Син', 37: 'Ас-Саффат', 38: 'Сад', 39: 'Аз-Зумар', 40: 'Гафир',
  41: 'Фуссылат', 42: 'Аш-Шура', 43: 'Аз-Зухруф', 44: 'Ад-Духан', 45: 'Аль-Джасия',
  46: 'Аль-Ахкаф', 47: 'Мухаммад', 48: 'Аль-Фатх', 49: 'Аль-Худжурат', 50: 'Каф',
  51: 'Аз-Зарият', 52: 'Ат-Тур', 53: 'Ан-Наджм', 54: 'Аль-Камар', 55: 'Ар-Рахман',
  56: 'Аль-Вакиа', 57: 'Аль-Хадид', 58: 'Аль-Муджадала', 59: 'Аль-Хашр', 60: 'Аль-Мумтахана',
  61: 'Ас-Сафф', 62: 'Аль-Джумуа', 63: 'Аль-Мунафикун', 64: 'Ат-Тагабун', 65: 'Ат-Талак',
  66: 'Ат-Тахрим', 67: 'Аль-Мульк', 68: 'Аль-Калям', 69: 'Аль-Хакка', 70: 'Аль-Мааридж',
  71: 'Нух', 72: 'Аль-Джинн', 73: 'Аль-Муззаммиль', 74: 'Аль-Муддассир', 75: 'Аль-Кияма',
  76: 'Аль-Инсан', 77: 'Аль-Мурсалят', 78: 'Ан-Наба', 79: 'Ан-Назиат', 80: 'Абаса',
  81: 'Ат-Таквир', 82: 'Аль-Инфитар', 83: 'Аль-Мутаффифин', 84: 'Аль-Иншикак', 85: 'Аль-Бурудж',
  86: 'Ат-Тарик', 87: 'Аль-Аля', 88: 'Аль-Гашия', 89: 'Аль-Фаджр', 90: 'Аль-Балад',
  91: 'Аш-Шамс', 92: 'Аль-Лейль', 93: 'Ад-Духа', 94: 'Аш-Шарх', 95: 'Ат-Тин',
  96: 'Аль-Алак', 97: 'Аль-Кадр', 98: 'Аль-Баййина', 99: 'Аз-Залзала', 100: 'Аль-Адият',
  101: 'Аль-Кариа', 102: 'Ат-Такасур', 103: 'Аль-Аср', 104: 'Аль-Хумаза', 105: 'Аль-Филь',
  106: 'Курайш', 107: 'Аль-Маун', 108: 'Аль-Каусар', 109: 'Аль-Кафирун', 110: 'Ан-Наср',
  111: 'Аль-Масад', 112: 'Аль-Ихлас', 113: 'Аль-Фаляк', 114: 'Ан-Нас',
};

// ── Russian playlist titles keyed by server slug
const PLAYLIST_RU = {
  'heart-of-quran': { title: 'Сердце Корана',    subtitle: 'Ясин, Рахман, Мульк и другие', cover: '/covers/heart-of-quran.jpg' },
  'fajr-rotation':  { title: 'Утренние суры',    subtitle: 'Чтения на заре',                cover: '/covers/fajr-rotation.jpg' },
  'before-sleep':   { title: 'Перед сном',       subtitle: 'Мульк, Кахф и Ясин',            cover: '/covers/before-sleep.jpg' },
  'short-surahs':   { title: 'Короткие суры',    subtitle: 'Из Джуз Амма',                  cover: '/covers/short-surahs.jpg' },
};

// ── Russian reciter names + photos
const RECITER_RU = {
  'yasser-al-dossari':    { name: 'Ясир Ад-Доссари',      photo: '/reciters/yasser-al-dossari.jpg' },
  'muhammad-al-luhaidan': { name: 'Мухаммад Аль Лихидан', photo: null },
};
const COUNTRY_RU = {
  'Saudi Arabia': 'Саудовская Аравия',
  'Kuwait':       'Кувейт',
  'Egypt':        'Египет',
};
const STYLE_RU = {
  'Hafs · Murattal': 'Хафс · Муратталь',
  'Hafs · Mujawwad': 'Хафс · Муджаввад',
};

// Helpers
function ruSurah(n) { return SURAH_RU[n] || ''; }
function ruPlaylist(slug, fallback) { return PLAYLIST_RU[slug] || fallback; }
function ruReciter(slug, fallback) { return RECITER_RU[slug]?.name || fallback; }
function ruReciterPhoto(slug)     { return RECITER_RU[slug]?.photo || null; }

// Transform a track so titles are in Russian
function localizeTrack(t) {
  if (!t) return t;
  return {
    ...t,
    title: SURAH_RU[t.surah] || t.titleTr || t.title,
    reciter: RECITER_RU[t.reciterSlug]?.name || t.reciter,
  };
}

function localizePlaylist(p) {
  if (!p) return p;
  const ru = PLAYLIST_RU[p.slug];
  return {
    ...p,
    title: ru?.title || p.title,
    subtitle: ru?.subtitle || p.subtitle,
    cover: ru?.cover || null,
    tracks: (p.tracks || []).map(localizeTrack),
  };
}

const IP_API = {
  async register(name, email, password) {
    const r = await fetch('/api/auth/register', {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ name, email, password }),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'register_failed');
    return data.user;
  },
  async login(email, password) {
    const r = await fetch('/api/auth/login', {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    const data = await r.json();
    if (!r.ok) throw new Error(data.error || 'login_failed');
    return data.user;
  },
  async logout() {
    await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });
  },
  async me() {
    const r = await fetch('/api/auth/me', { credentials: 'include' });
    if (!r.ok) return null;
    const data = await r.json();
    return data.user;
  },
  async tracks() {
    const r = await fetch('/api/tracks', { credentials: 'include' });
    const data = await r.json();
    return data.map(localizeTrack);
  },
  async playlists() {
    const r = await fetch('/api/playlists', { credentials: 'include' });
    const data = await r.json();
    return data.map(p => ({
      ...p,
      title:    PLAYLIST_RU[p.slug]?.title    || p.title,
      subtitle: PLAYLIST_RU[p.slug]?.subtitle || p.subtitle,
      cover:    PLAYLIST_RU[p.slug]?.cover    || null,
    }));
  },
  async playlist(id) {
    const r = await fetch('/api/playlists/' + id, { credentials: 'include' });
    if (!r.ok) return null;
    const data = await r.json();
    return localizePlaylist(data);
  },
  async reciters() {
    const r = await fetch('/api/reciters', { credentials: 'include' });
    const data = await r.json();
    return data.map(x => ({
      ...x,
      name:    RECITER_RU[x.slug]?.name  || x.name,
      photo:   RECITER_RU[x.slug]?.photo || null,
      country: COUNTRY_RU[x.country] || x.country,
      style:   STYLE_RU[x.style] || x.style,
    }));
  },
  async stats() {
    const r = await fetch('/api/stats', { credentials: 'include' });
    if (!r.ok) return { plays: 0, uniqueTracks: 0, favorites: 0, listenDays: 0, joined: null };
    return r.json();
  },
  async recent() {
    const r = await fetch('/api/history/recent', { credentials: 'include' });
    if (!r.ok) return [];
    const data = await r.json();
    return data.map(localizeTrack);
  },
  async logPlay(trackId, progressSec) {
    try {
      await fetch('/api/history', {
        method: 'POST', credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ trackId, progressSec }),
      });
    } catch {}
  },
  async createPlaylist(title) {
    const r = await fetch('/api/playlists', {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title }),
    });
    if (!r.ok) throw new Error('create_failed');
    return r.json();
  },
  async renamePlaylist(id, title) {
    const r = await fetch('/api/playlists/' + id, {
      method: 'PATCH', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title }),
    });
    if (!r.ok) throw new Error('rename_failed');
    return r.json();
  },
  async deletePlaylist(id) {
    const r = await fetch('/api/playlists/' + id, {
      method: 'DELETE', credentials: 'include',
    });
    if (!r.ok) throw new Error('delete_failed');
  },
  async addTrackToPlaylist(playlistId, trackId) {
    const r = await fetch(`/api/playlists/${playlistId}/tracks`, {
      method: 'POST', credentials: 'include',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ trackId }),
    });
    if (!r.ok) throw new Error('add_failed');
  },
  async removeTrackFromPlaylist(playlistId, trackId) {
    const r = await fetch(`/api/playlists/${playlistId}/tracks/${trackId}`, {
      method: 'DELETE', credentials: 'include',
    });
    if (!r.ok) throw new Error('remove_failed');
  },
  async favorite(trackId, isFav) {
    await fetch('/api/favorites/' + trackId, {
      method: isFav ? 'POST' : 'DELETE', credentials: 'include',
    });
  },
};

// Mutable globals screens read
var IP_YASIN_TRACKS = [];
var IP_PLAYLISTS = [];
var IP_RECITERS = [];
var IP_RECENT = [];

Object.assign(window, {
  IP_API, IP_YASIN_TRACKS, IP_PLAYLISTS, IP_RECITERS, IP_RECENT,
  SURAH_RU, PLAYLIST_RU, ruSurah, ruPlaylist, ruReciter, ruReciterPhoto,
});
