/* ═══════════════════════════════════════════════════════════
   FICTION IGNITION — js/auth.js  (PRODUCTION VERSION)
   All auth calls go to the real PHP backend.
   Session managed via httpOnly cookie set by PHP.
═══════════════════════════════════════════════════════════ */

'use strict';

const TIERS = {
  free:       { label:'Free',       dailyLimit:3,          adFree:false, history:false, export:false, customGenre:false, advancedAI:false },
  starter:    { label:'Starter',    dailyLimit:10,         adFree:true,  history:false, export:false, customGenre:false, advancedAI:false },
  writer:     { label:'Writer',     dailyLimit:25,         adFree:true,  history:true,  export:true,  customGenre:false, advancedAI:false },
  author_pro: { label:'Author Pro', dailyLimit:Infinity,   adFree:true,  history:true,  export:true,  customGenre:true,  advancedAI:true  },
};

const API_BASE = '/api'; // Adjust if your PHP lives at a different path

const Auth = {
  _session: null,   // { id, name, email, tier }
  _usage:   null,   // { used_today, daily_limit, prompts_left }
  _features: null,

  // ── Login → POST /api/auth/?action=login ─────────────────
  async login(email, password) {
    const data = await _apiFetch(`${API_BASE}/auth/?action=login`, {
      method: 'POST',
      body: JSON.stringify({ email, password }),
    });
    this._session  = data.user;
    this._features = null;
    return data.user;
  },

  // ── Register → POST /api/auth/?action=register ───────────
  async register(name, email, password) {
    const data = await _apiFetch(`${API_BASE}/auth/?action=register`, {
      method: 'POST',
      body: JSON.stringify({ name, email, password }),
    });
    // Registration returns a message; user must verify email before logging in
    return data;
  },

  // ── Logout → POST /api/auth/?action=logout ───────────────
  logout() {
    fetch(`${API_BASE}/auth/?action=logout`, { method: 'POST', credentials: 'include' })
      .catch(() => {});
    this._session  = null;
    this._usage    = null;
    this._features = null;
  },

  // ── Refresh from server → GET /api/auth/?action=me ───────
  async refresh() {
    try {
      const data = await _apiFetch(`${API_BASE}/auth/?action=me`);
      this._session  = data.user;
      this._usage    = data.usage;
      this._features = data.features;
    } catch {
      this._session  = null;
      this._usage    = null;
      this._features = null;
    }
  },

  get isLoggedIn()  { return !!this._session; },
  get user()        { return this._session; },
  get tier()        { return this._session?.tier || 'free'; },
  get isAdmin()     { return !!(this._session?.isAdmin); },
  get tierInfo()    { return TIERS[this.tier] || TIERS.free; },

  hasFeature(f) {
    // Use server-supplied features when available
    if (this._features) return !!this._features[f.replace(/([A-Z])/g, '_$1').toLowerCase()];
    return !!this.tierInfo[f];
  },

  canGenerate() {
    if (!this.isLoggedIn) return false;
    const left = this.promptsLeft();
    return left === null || left > 0;
  },

  promptsLeft() {
    if (!this._usage) {
      const lim = this.tierInfo.dailyLimit;
      return lim === Infinity ? null : lim;
    }
    return this._usage.prompts_left; // null = unlimited
  },

  recordUsage() {
    // Usage is recorded server-side in generate endpoint
    if (this._usage && this._usage.prompts_left !== null) {
      this._usage.prompts_left = Math.max(0, (this._usage.prompts_left || 0) - 1);
      this._usage.used_today   = (this._usage.used_today || 0) + 1;
    }
  },
};

// ── Internal fetch helper ─────────────────────────────────
async function _apiFetch(url, opts = {}) {
  const res = await fetch(url, {
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', ...(opts.headers || {}) },
    ...opts,
  });
  const data = await res.json();
  if (!data.success) throw new Error(data.error || 'Unknown error');
  return data;
}

// ── Check for email verified redirect ─────────────────────
if (typeof window !== 'undefined') {
  const params = new URLSearchParams(window.location.search);
  if (params.get('verified') === '1') {
    // Show success message when landing on app page after verification
    window._fiJustVerified = true;
  }
}
