// mgrSNP.js
// Scope: browser-side API facade only.
// No ActiveProject state, AccessTier state, project display cache, or settings cache.

(function () {
  'use strict';

  function getDeckURL() {
    return localStorage.getItem('nv_deck_url') || window.location.origin;
  }

  function setDeckURL(url) {
    const next = String(url || '').trim() || getDeckURL();
    localStorage.setItem('nv_deck_url', next);
  }

  async function call(path, method = 'GET', body = null) {
    try {
      const opts = { method, headers: { 'Content-Type': 'application/json' } };
      if (body !== null) opts.body = JSON.stringify(body);
      const res = await fetch(getDeckURL() + path, opts);
      return await res.json();
    } catch (e) {
      return { ok: false, error: e.message };
    }
  }

  async function loadSettings() {
    const data = await call('/settings');
    return data?.ok ? data.settings : null;
  }

  async function saveSettings(patch) {
    return await call('/settings/save', 'POST', patch);
  }

  async function getAutoPlayHandling() {
    const settings = await loadSettings();
    return settings?.autoPlayHandling || {
      chatManifests: false,
      diagnosticRepair: false,
      enhancementSuggestions: false
    };
  }

  async function isAutoAcceptEnabled() {
    const a = await getAutoPlayHandling();
    return Boolean(a.chatManifests || a.diagnosticRepair || a.enhancementSuggestions);
  }

  async function loadProjects() {
    const data = await call('/projects');
    return data?.ok ? { ...data, projects: Array.isArray(data.projects) ? data.projects : [] } : null;
  }

  async function createProject(name) {
    return await call('/projects/create', 'POST', { name });
  }

  async function saveProject(name, content) {
    return await call('/projects/save', 'POST', { name, content });
  }

  async function login(email, password) {
    const data = await call('/auth/login', 'POST', { email, password });
    if (data?.ok) localStorage.setItem('nv_auth_email', data.email || data.user?.email || email || '');
    return data;
  }

  async function logout() {
    const data = await call('/auth/logout', 'POST');
    if (data?.ok) localStorage.removeItem('nv_auth_email');
    return data;
  }

  async function loadAuthStatus() {
    const data = await call('/auth/status');
    if (data?.email) localStorage.setItem('nv_auth_email', data.email);
    return data?.ok ? {
      authenticated: data.authenticated,
      email: data.email,
      tier: data.accessTier || data.tier,
      accessTier: data.accessTier || data.tier,
      licensed: Boolean(data.licensed),
      tierDetails: data.accessDetails || data.tierDetails,
      telemetry: data.telemetry
    } : null;
  }

  async function setTelemetryConsent(logs) {
    return await call('/auth/telemetry', 'POST', { logs });
  }

  window.SettingsStore = {
    load: loadSettings,
    save: saveSettings,
    getCached: () => null,
    getAutoPlayHandling,
    isAutoAcceptEnabled
  };

  window.AuthSession = {
    login,
    logout,
    loadStatus: loadAuthStatus,
    setTelemetryConsent,
    getCached: () => null,
    isLoggedIn: async () => Boolean((await loadAuthStatus())?.authenticated),
    getCurrentTier: async () => (await loadAuthStatus())?.tier || 'limited'
  };

  window.DeckConnection = {
    getURL: getDeckURL,
    setURL: setDeckURL
  };

  window.ProjectRegistry = {
    load: loadProjects,
    create: createProject,
    save: saveProject
  };

  window.SNP = {
    getDeckURL,
    setDeckURL,
    loadSettings,
    saveSettings,
    getAutoPlayHandling,
    isAutoAcceptEnabled,
    loadProjects,
    createProject,
    saveProject,
    login,
    logout,
    loadAuthStatus,
    setTelemetryConsent
  };
})();
