(function () {
  async function request(url, options) {
    const response = await fetch(url, options);
    if (!response.ok) {
      let message = `HTTP ${response.status}`;
      try { message = (await response.json()).error || message; } catch (_) {}
      throw new Error(message);
    }
    return response;
  }

  window.LanPlayApi = {
    async browse(path) {
      return (await request(`/api/browse?path=${encodeURIComponent(path)}`)).json();
    },

    async info() {
      return (await request('/api/info')).json();
    },
    async startDash(path, startSeconds = 0) {
      const query = `path=${encodeURIComponent(path)}&start=${encodeURIComponent(startSeconds)}`;
      return (await request(`/api/dash?${query}`, { method: 'POST' })).json();
    },
    async stopDash(sessionId) {
      await request(`/api/dash/${sessionId}`, { method: 'DELETE' });
    },
    async subtitles(path) {
      return (await request(`/api/subtitles?path=${encodeURIComponent(path)}`)).json();
    }
  };
})();
