// ==============================================
// src/api.jsx — Cloudflare API Client
// เชื่อมต่อกับ Cloudflare Pages Functions + D1
// Falls back gracefully to demo mode if API not available
// ==============================================

(function () {
  const API_BASE = "/api";
  let _token = null;

  // Restore token from storage
  try { _token = localStorage.getItem("isp_token") || null; } catch {}

  function setToken(tok) {
    _token = tok;
    try {
      if (tok) localStorage.setItem("isp_token", tok);
      else localStorage.removeItem("isp_token");
    } catch {}
  }

  async function req(path, options = {}) {
    const headers = {
      "Content-Type": "application/json",
      ...(_token ? { Authorization: "Bearer " + _token } : {}),
      ...(options.headers || {}),
    };
    let url = API_BASE + path;
    if (options.params) {
      const q = new URLSearchParams(
        Object.fromEntries(Object.entries(options.params).filter(([, v]) => v != null))
      );
      if (q.toString()) url += "?" + q.toString();
    }
    const res = await fetch(url, {
      method: options.method || "GET",
      headers,
      body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
    });
    let data;
    try { data = await res.json(); } catch { data = { error: res.statusText }; }
    if (!res.ok) throw new Error(data.error || "HTTP " + res.status);
    return data;
  }

  const api = {
    // ── Status ──
    async isAvailable() {
      try { await req("/categories"); return true; } catch { return false; }
    },

    // ── Products ──
    async getProducts(filters) {
      return req("/products", { params: filters });
    },
    async getProduct(id) {
      return req("/products/" + id);
    },

    // ── Categories & Brands ──
    async getCategories() { return req("/categories"); },
    async getBrands()     { return req("/brands"); },

    // ── Quotations ──
    async createQuotation(data) {
      return req("/quotations", { method: "POST", body: data });
    },
    async getMyQuotations() {
      return req("/quotations");
    },

    // ── Auth ──
    async login(email, password, role) {
      const data = await req("/auth/login", { method: "POST", body: { email, password, role } });
      setToken(data.token);
      return data.user;
    },
    async register(email, password, name, company, role) {
      const data = await req("/auth/register", { method: "POST", body: { email, password, name, company, role } });
      setToken(data.token);
      return data.user;
    },
    async logout() {
      try { await req("/auth/logout", { method: "POST" }); } catch {}
      setToken(null);
    },
    async getMe() {
      return req("/auth/me");
    },

    // ── Admin ──
    admin: {
      async getStats()         { return req("/admin/stats"); },
      async getProducts()      { return req("/admin/products"); },
      async createProduct(d)   { return req("/admin/products",       { method: "POST",   body: d }); },
      async updateProduct(id, d){ return req("/admin/products/" + id, { method: "PUT",    body: d }); },
      async deleteProduct(id)  { return req("/admin/products/" + id, { method: "DELETE" }); },
      async getQuotations(status) { return req("/admin/quotations", { params: status ? { status } : {} }); },
      async updateQuotation(id, d) { return req("/admin/quotations/" + id, { method: "PATCH", body: d }); },
      async getMembers()       { return req("/admin/members"); },
      async updateMember(id, d){ return req("/admin/members/" + id, { method: "PATCH", body: d }); },
    },

    // ── Setup (run once) ──
    async setup() { return req("/setup", { method: "POST" }); },

    // expose internals for tests
    _setToken: setToken,
    get _token() { return _token; },
  };

  window.ISP_API = api;
  window.api = api; // shorthand
})();
