// api.jsx — typed-ish fetch wrapper with session token storage
const TOKEN_KEY = "rawj_session";

function getToken() {
  try { return localStorage.getItem(TOKEN_KEY) || null; } catch { return null; }
}
function setToken(token) {
  try { token ? localStorage.setItem(TOKEN_KEY, token) : localStorage.removeItem(TOKEN_KEY); } catch {}
}

async function apiCall(method, path, body) {
  const token = getToken();
  const headers = { "Content-Type": "application/json" };
  if (token) headers["Authorization"] = `Bearer ${token}`;
  const resp = await fetch(`${window.RAWJ_CONFIG.API_BASE}${path}`, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });
  let data = null;
  const text = await resp.text();
  try { data = text ? JSON.parse(text) : null; } catch { data = { raw: text }; }
  if (!resp.ok) {
    const msg = (data && data.error) || `HTTP ${resp.status}`;
    const err = new Error(msg);
    err.status = resp.status;
    err.payload = data;
    throw err;
  }
  return data;
}

const API = {
  // ─── Auth ───────────────────────────────────────
  async signup({ name, email, password }) {
    const data = await apiCall("POST", "/api/auth/signup", { name, email, password });
    if (data && data.token) setToken(data.token);
    return data;
  },
  async login({ email, password }) {
    const data = await apiCall("POST", "/api/auth/login", { email, password });
    if (data && data.token) setToken(data.token);
    return data;
  },
  async logout() {
    try { await apiCall("POST", "/api/auth/logout", {}); } catch {}
    setToken(null);
  },
  async me() {
    const token = getToken();
    if (!token) return null;
    try { return await apiCall("GET", "/api/me"); }
    catch (e) { if (e.status === 401) setToken(null); return null; }
  },

  // ─── App data ───────────────────────────────────
  async listAccounts() {
    return await apiCall("GET", "/api/accounts");
  },
  async listAlerts() {
    return await apiCall("GET", "/api/alerts");
  },
  async getNotifications() {
    return await apiCall("GET", "/api/notifications");
  },
  async updateNotifications(body) {
    return await apiCall("PUT", "/api/notifications", body);
  },

  // ─── Connect ad account (paste token, like the bot) ─
  async validateMetaToken({ token }) {
    return await apiCall("POST", "/api/connect/meta/validate", { token });
  },
  async saveMetaAccounts({ token, accountIds }) {
    return await apiCall("POST", "/api/connect/meta/save", { token, accountIds });
  },

  // ─── Token storage helpers ─────────────────────
  hasSession: () => !!getToken(),
  clearSession: () => setToken(null),
};

window.API = API;
