/*
  CONFIG — where the API lives + which providers to query.

  API base resolution order:
    1. ?api=<url> query param on any page (session override)
    2. localStorage (saved from Settings)
    3. built-in default

  Providers: until the user toggles anything in Settings, the server's own
  enabled list is used. Once customized, a {name: bool} map is stored in
  localStorage; names missing from the map default to enabled.
*/
(function () {
  'use strict';

  const DEFAULT_BASE = 'https://api-tv.bug.tools';
  const STORAGE_KEY = 'streamreverse.apiBase.v1';
  const PROVIDER_KEY = 'streamreverse.providers.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 */
    }
  }

  // null → user has not customized; caller should fall back to server defaults
  function getProviders() {
    try {
      const raw = localStorage.getItem(PROVIDER_KEY);
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
    } catch (e) {
      return null;
    }
  }

  function setProviders(map) {
    try {
      localStorage.setItem(PROVIDER_KEY, JSON.stringify(map));
    } catch (e) {
      /* ignore */
    }
  }

  function clearProviders() {
    try {
      localStorage.removeItem(PROVIDER_KEY);
    } catch (e) {
      /* ignore */
    }
  }

  const PREFERRED_PROVIDERS = ['cineby', 'playimdb', 'vidrock'];

  // Merge the server's provider lists with the user's toggles.
  // Returns the enabled provider names, in the server's `all` order.
  function enabledProviders(allNames, serverEnabled) {
    const all = Array.isArray(allNames) ? allNames : [];
    const overrides = getProviders();
    if (overrides) {
      return Object.keys(overrides).filter((n) => overrides[n] !== false);
    }
    const server = Array.isArray(serverEnabled) ? serverEnabled : [];
    const wanted = new Set([...PREFERRED_PROVIDERS, ...server]);
    return (all.length ? all : PREFERRED_PROVIDERS.slice()).filter((n) =>
      wanted.has(n)
    );
  }

  // Watch-page resolver. Re-reads localStorage on every call so provider
  // changes made in Settings apply to the next lookup without a reload.
  function resolveProviders(catalog) {
    const all = Array.isArray(catalog && catalog.all) ? catalog.all : [];
    const serverEnabled = Array.isArray(catalog && catalog.enabled) ? catalog.enabled : [];
    const overrides = getProviders();
    if (overrides) {
      return {
        names: Object.keys(overrides).filter((n) => overrides[n] !== false),
        customized: true,
        useServerDefaults: false,
      };
    }
    const wanted = new Set([...PREFERRED_PROVIDERS, ...serverEnabled]);
    const names = all.length
      ? all.filter((n) => wanted.has(n))
      : PREFERRED_PROVIDERS.slice();
    return {
      names,
      customized: false,
      useServerDefaults: !names.length,
    };
  }

  window.SR = window.SR || {};
  SR.config = {
    DEFAULT_BASE,
    STORAGE_KEY,
    PROVIDER_KEY,
    getBase,
    setBase,
    clearBase,
    getProviders,
    setProviders,
    clearProviders,
    enabledProviders,
    resolveProviders,
  };
})();
