// ============ AUTH / PREMIUM CLIENT ============
const AuthClient = (() => {
  const RAW_BASE = window.DJANYTHING_API_URL || window.MIXFM_API_URL || '';
  const BASE = String(RAW_BASE).replace(/\/+$/, '');
  const MOCK = !BASE;

  const DEFAULT_CONFIG = {
    auth: {
      googleClientId: '',
      googleEnabled: false,
    },
    premium: {
      freeSessionLimitSeconds: 30 * 60,
      monthlyPriceUsd: 5,
      annualPriceUsd: 29.99,
      stripePublishableKey: '',
      checkoutMonthlyUrl: '',
      checkoutAnnualUrl: '',
      features: [
        'Unlimited party sessions',
        'Full internet DJ library',
        'Premium FX and performance tools',
        'Priority beat analysis',
        'Record and export mixes',
      ],
    },
  };

  const ANON_ACCOUNT = {
    user: null,
    entitlements: {
      isPremium: false,
      plan: 'free',
      freeSessionLimitSeconds: DEFAULT_CONFIG.premium.freeSessionLimitSeconds,
      maxQueueTracks: 25,
      premiumFx: false,
      unlimitedAutomix: false,
      cloudLibrary: false,
      priorityAnalysis: false,
      recordingExport: false,
    },
    usage: { todaySeconds: 0, totalSeconds: 0 },
  };

  function mergeConfig(config) {
    return {
      auth: { ...DEFAULT_CONFIG.auth, ...(config?.auth || {}) },
      premium: { ...DEFAULT_CONFIG.premium, ...(config?.premium || {}) },
    };
  }

  async function api(path, options = {}) {
    if (MOCK) throw new Error('Backend not configured');
    const resp = await fetch(`${BASE}${path}`, {
      credentials: 'include',
      ...options,
      headers: {
        'Content-Type': 'application/json',
        ...(options.headers || {}),
      },
    });
    let data = null;
    try { data = await resp.json(); } catch {}
    if (!resp.ok) throw new Error(data?.error || `Request failed: ${resp.status}`);
    return data;
  }

  async function getConfig() {
    if (MOCK) return DEFAULT_CONFIG;
    try {
      return mergeConfig(await api('/api/config', { method: 'GET', headers: {} }));
    } catch {
      return DEFAULT_CONFIG;
    }
  }

  async function me() {
    if (MOCK) return ANON_ACCOUNT;
    try {
      return await api('/api/me', { method: 'GET', headers: {} });
    } catch {
      return ANON_ACCOUNT;
    }
  }

  async function loginWithGoogle(credential) {
    return api('/api/auth/google', {
      method: 'POST',
      body: JSON.stringify({ credential }),
    });
  }

  async function logout() {
    if (MOCK) return ANON_ACCOUNT;
    return api('/api/auth/logout', { method: 'POST', body: '{}' });
  }

  async function recordUsage(seconds, source = 'mix') {
    if (MOCK) return ANON_ACCOUNT;
    return api('/api/usage/mix-session', {
      method: 'POST',
      body: JSON.stringify({ seconds, source }),
    });
  }

  return {
    MOCK,
    getConfig,
    loginWithGoogle,
    logout,
    me,
    recordUsage,
  };
})();

window.AuthClient = AuthClient;
