/*
  CONFIG — where the API lives. Resolution order:
    1. ?api=<url> query param on any page (session override)
    2. localStorage (saved from the Settings dialog)
    3. built-in default
*/
(function () {
  'use strict';

  const DEFAULT_BASE = 'https://bug-api-test.tuns.sh';
  const STORAGE_KEY = 'streamreverse.apiBase.v1';

  function normalize(value) {
    let v = String(value || '').trim();
    if (!v) return '';
    if (!/^https?:\/\//i.test(v)) v = `https://${v}`;
    return v.replace(/\/+$/, '');
  }

  function getBase() {
    const fromQuery = SR.util.getParam('api');
    if (fromQuery) return normalize(fromQuery);
    try {
      const stored = localStorage.getItem(STORAGE_KEY);
      if (stored) return normalize(stored);
    } catch (e) {
      /* private mode etc. */
    }
    return DEFAULT_BASE;
  }

  function setBase(value) {
    const v = normalize(value);
    try {
      localStorage.setItem(STORAGE_KEY, v);
    } catch (e) {
      /* ignore */
    }
    return v;
  }

  function clearBase() {
    try {
      localStorage.removeItem(STORAGE_KEY);
    } catch (e) {
      /* ignore */
    }
  }

  window.SR = window.SR || {};
  SR.config = { DEFAULT_BASE, STORAGE_KEY, getBase, setBase, clearBase };
})();
