/**
 * Flarlo API – Kurzvideo-Plattform (nutzt Jami-Auth-Token).
 */
const VibeLoopApi = {
  _token: '',
  _config: null,
  _profile: null,

  init() {
    this._token = localStorage.getItem('jami_token') || localStorage.getItem('vl_token') || localStorage.getItem('cp_token') || '';
    return this;
  },

  setToken(t) {
    this._token = t || '';
    if (t) {
      localStorage.setItem('vl_token', t);
      localStorage.setItem('cp_token', t);
      localStorage.setItem('jami_token', t);
    }
  },

  async _fetch(path, opts = {}) {
    const headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };
    if (this._token) headers.Authorization = 'Bearer ' + this._token;
    const r = await fetch('/api/vibeloop/' + path, { ...opts, headers });
    let j = {};
    try { j = await r.json(); } catch (e) {}
    if (!r.ok) throw new Error(j.error || 'Server-Fehler');
    return j;
  },

  async getConfig() {
    this._config = await this._fetch('config');
    return this._config;
  },

  async login(email, password) {
    const r = await fetch('/api/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });
    const j = await r.json();
    if (!r.ok) throw new Error(j.error || 'Login fehlgeschlagen');
    this.setToken(j.token);
    return j;
  },

  async register(data) {
    const r = await fetch('/api/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data),
    });
    const j = await r.json();
    if (!r.ok) throw new Error(j.error || 'Registrierung fehlgeschlagen');
    this.setToken(j.token);
    return j;
  },

  async me() {
    const j = await this._fetch('me');
    this._profile = j.profile;
    return j.profile;
  },

  async updateMe(patch) {
    const j = await this._fetch('me', { method: 'PATCH', body: JSON.stringify(patch) });
    this._profile = j.profile;
    return j.profile;
  },

  async feed(opts = {}) {
    const q = new URLSearchParams();
    if (opts.mode) q.set('mode', opts.mode);
    if (opts.niche) q.set('niche', opts.niche);
    if (opts.cursor) q.set('cursor', opts.cursor);
    if (opts.limit) q.set('limit', String(opts.limit));
    return this._fetch('feed?' + q.toString());
  },

  async uploadPost(data) {
    return this._fetch('upload', { method: 'POST', body: JSON.stringify(data) });
  },

  async likePost(postId) {
    return this._fetch('like/' + postId, { method: 'POST' });
  },

  async viewPost(postId) {
    return this._fetch('view/' + postId, { method: 'POST' });
  },

  async getComments(postId) {
    return this._fetch('comments/' + postId);
  },

  async addComment(postId, body) {
    return this._fetch('comments/' + postId, { method: 'POST', body: JSON.stringify({ body }) });
  },

  async follow(userId) {
    return this._fetch('follow/' + userId, { method: 'POST' });
  },

  async getProfile(userId) {
    return this._fetch('profile/' + userId);
  },

  async getPost(postId) {
    return this._fetch('post/' + postId);
  },

  async sharePost(postId) {
    return this._fetch('share/' + postId, { method: 'POST' });
  },

  async sendGift(data) {
    return this._fetch('gift', { method: 'POST', body: JSON.stringify(data) });
  },

  async boostPost(postId) {
    return this._fetch('boost/' + postId, { method: 'POST' });
  },

  async startLive(title) {
    return this._fetch('live/start', { method: 'POST', body: JSON.stringify({ title }) });
  },

  async endLive() {
    return this._fetch('live/end', { method: 'POST' });
  },

  async getLives() {
    return this._fetch('live');
  },

  async getLive(liveId) {
    return this._fetch('live/' + liveId);
  },

  async joinLive(liveId) {
    return this._fetch('live/' + liveId + '/join', { method: 'POST' });
  },

  async leaveLive(liveId) {
    return this._fetch('live/' + liveId + '/leave', { method: 'POST' });
  },

  async uploadLiveSegment(liveId, data) {
    return this._fetch('live/' + liveId + '/segment', { method: 'POST', body: JSON.stringify(data) });
  },

  async getLiveSegments(liveId, opts = {}) {
    const q = new URLSearchParams();
    if (opts.after != null) q.set('after', String(opts.after));
    const qs = q.toString();
    return this._fetch('live/' + liveId + '/segments' + (qs ? '?' + qs : ''));
  },

  async getLiveGifts(liveId) {
    return this._fetch('live/' + liveId + '/gifts');
  },

  async getLiveChat(liveId, opts = {}) {
    const q = new URLSearchParams();
    if (opts.since) q.set('since', opts.since);
    const qs = q.toString();
    return this._fetch('live/' + liveId + '/chat' + (qs ? '?' + qs : ''));
  },

  async sendLiveChat(liveId, text) {
    return this._fetch('live/' + liveId + '/chat', { method: 'POST', body: JSON.stringify({ text }) });
  },

  async getLiveMatch(liveId) {
    return this._fetch('live/' + liveId + '/match');
  },

  async inviteLiveMatch(liveId, opponentLiveId) {
    return this._fetch('live/' + liveId + '/match/invite', {
      method: 'POST',
      body: JSON.stringify({ opponentLiveId }),
    });
  },

  async acceptLiveMatch(liveId) {
    return this._fetch('live/' + liveId + '/match/accept', { method: 'POST' });
  },

  async declineLiveMatch(liveId) {
    return this._fetch('live/' + liveId + '/match/decline', { method: 'POST' });
  },

  async likeLiveMatch(liveId, side) {
    return this._fetch('live/' + liveId + '/match/like', {
      method: 'POST',
      body: JSON.stringify(side ? { side } : {}),
    });
  },

  async endLiveMatch(liveId) {
    return this._fetch('live/' + liveId + '/match/end', { method: 'POST' });
  },

  async getEarnings() {
    return this._fetch('earnings');
  },

  async requestPayout() {
    return this._fetch('payout', { method: 'POST' });
  },

  async getPremium() {
    return this._fetch('premium');
  },

  async checkoutPremium() {
    return this._fetch('premium/checkout', { method: 'POST' });
  },

  async confirmPremium(sessionId) {
    const j = await this._fetch('premium/confirm', {
      method: 'POST',
      body: JSON.stringify({ sessionId }),
    });
    this._profile = j.profile || this._profile;
    return j;
  },

  async checkoutCoins(packId) {
    return this._fetch('coins/checkout', { method: 'POST', body: JSON.stringify({ packId }) });
  },

  async confirmCoins(sessionId) {
    const j = await this._fetch('coins/confirm', {
      method: 'POST',
      body: JSON.stringify({ sessionId }),
    });
    this._profile = j.profile || this._profile;
    return j;
  },

  async getInbox() {
    return this._fetch('inbox');
  },

  async getInboxMessages(userId) {
    return this._fetch('inbox/' + userId + '/messages');
  },

  async sendInboxMessage(userId, text) {
    return this._fetch('inbox/' + userId + '/messages', {
      method: 'POST',
      body: JSON.stringify({ text }),
    });
  },

  async uploadIntroVideo(data) {
    const j = await this._fetch('intro-video', { method: 'POST', body: JSON.stringify(data) });
    this._profile = j.profile || this._profile;
    return j;
  },

  async deleteIntroVideo() {
    const j = await this._fetch('intro-video', { method: 'DELETE' });
    this._profile = j.profile || this._profile;
    return j;
  },

  async blockUser(userId) {
    return this._fetch('block/' + userId, { method: 'POST' });
  },

  async unblockUser(userId) {
    return this._fetch('block/' + userId, { method: 'DELETE' });
  },

  async getBlocks() {
    return this._fetch('blocks');
  },

  async report(data) {
    return this._fetch('report', { method: 'POST', body: JSON.stringify(data) });
  },
};

if (typeof window !== 'undefined') window.VibeLoopApi = VibeLoopApi;
