/* ============================================================
   API — fetch wrapper for the Ktor backend
   Exposes window.API and window.API_BASE
   ============================================================ */
(function () {
  const IS_LOCAL = location.hostname === "localhost" || location.hostname === "127.0.0.1";
  const API_BASE = window.API_BASE ||
    (IS_LOCAL ? (location.protocol + "//" + location.hostname + ":8080")
              : "https://probhat-backend.onrender.com");
  const ROOT = API_BASE + "/api";

  const USER_TOKEN_KEY  = "probhat_user_token";
  const STAFF_TOKEN_KEY = "probhat_staff_token";

  function getUserToken()  { return localStorage.getItem(USER_TOKEN_KEY)  || null; }
  function getStaffToken() { return localStorage.getItem(STAFF_TOKEN_KEY) || null; }
  function setUserToken(t)  {
    if (t) localStorage.setItem(USER_TOKEN_KEY,  t); else localStorage.removeItem(USER_TOKEN_KEY);
  }
  function setStaffToken(t) {
    if (t) localStorage.setItem(STAFF_TOKEN_KEY, t); else localStorage.removeItem(STAFF_TOKEN_KEY);
  }

  function pickToken(path) {
    if (path.startsWith("/admin/")) return getStaffToken();
    if (path.startsWith("/public/me/")) return getUserToken();
    if (path.includes("/react")) return getUserToken();
    return null;
  }

  async function request(path, opts) {
    opts = opts || {};
    const headers = Object.assign({ "Accept": "application/json" }, opts.headers || {});
    if (opts.body && !(opts.body instanceof FormData)) {
      headers["Content-Type"] = "application/json";
    }
    const token = pickToken(path);
    if (token) headers["Authorization"] = "Bearer " + token;

    const body = (opts.body && !(opts.body instanceof FormData))
      ? JSON.stringify(opts.body)
      : opts.body;

    let res;
    try {
      res = await fetch(ROOT + path, { method: opts.method || "GET", headers, body });
    } catch (e) {
      throw { kind: "network", message: "নেটওয়ার্ক ত্রুটি — সার্ভার চালু আছে কি না দেখুন।" };
    }

    let json = null;
    const text = await res.text();
    if (text) {
      try { json = JSON.parse(text); } catch (_) { json = { raw: text }; }
    }
    if (!res.ok) {
      const err = { kind: "http", status: res.status, error: (json && json.error) || "error", message: (json && json.message) || res.statusText };
      throw err;
    }
    return json;
  }

  function qs(params) {
    if (!params) return "";
    const s = new URLSearchParams();
    Object.keys(params).forEach(k => { if (params[k] != null) s.set(k, params[k]); });
    const out = s.toString();
    return out ? "?" + out : "";
  }

  function imgUrl(path) {
    if (!path) return null;
    if (/^https?:/.test(path)) return path;
    return API_BASE + path;
  }

  const API = {
    BASE: API_BASE,
    imgUrl,
    getUserToken, getStaffToken, setUserToken, setStaffToken,

    // public (no auth)
    publicArticles: {
      list:     (params)        => request("/public/articles" + qs(params)),
      featured: (limit)         => request("/public/articles/featured" + qs({ limit })),
      byCat:    (slug, sort, limit) => request("/public/categories/" + encodeURIComponent(slug) + "/articles" + qs({ sort, limit })),
      detail:   (id)            => request("/public/articles/" + encodeURIComponent(id)),
      related:  (id)            => request("/public/articles/" + encodeURIComponent(id) + "/related"),
      view:     (id)            => request("/public/articles/" + encodeURIComponent(id) + "/view", { method: "POST" }),
    },
    publicCategories: {
      list: () => request("/public/categories"),
    },

    // consumer auth + engagement
    auth: {
      register: (name, email, password) => request("/public/auth/register", { method: "POST", body: { name, email, password } }),
      login:    (email, password)       => request("/public/auth/login",    { method: "POST", body: { email, password } }),
    },
    me: {
      react:          (id, reaction)  => request("/public/articles/" + encodeURIComponent(id) + "/react", { method: "POST", body: { reaction } }),
      reactions:      ()              => request("/public/me/reactions"),
      bookmarks:      ()              => request("/public/me/bookmarks"),
      addBookmark:    (id)            => request("/public/me/bookmarks/" + encodeURIComponent(id), { method: "POST" }),
      removeBookmark: (id)            => request("/public/me/bookmarks/" + encodeURIComponent(id), { method: "DELETE" }),
    },

    // admin
    admin: {
      login: (email, password) => request("/admin/auth/login", { method: "POST", body: { email, password } }),

      articles: {
        list:   (params)       => request("/admin/articles" + qs(params)),
        get:    (id)           => request("/admin/articles/" + encodeURIComponent(id)),
        create: (payload)      => request("/admin/articles", { method: "POST", body: payload }),
        update: (id, payload)  => request("/admin/articles/" + encodeURIComponent(id), { method: "PATCH", body: payload }),
        remove: (id)           => request("/admin/articles/" + encodeURIComponent(id), { method: "DELETE" }),
        uploadImage: (id, file) => {
          const fd = new FormData();
          fd.append("image", file);
          return request("/admin/articles/" + encodeURIComponent(id) + "/image", { method: "POST", body: fd });
        },
      },

      feeds: {
        list:      ()                => request("/admin/feeds"),
        create:    (payload)         => request("/admin/feeds", { method: "POST", body: payload }),
        update:    (id, payload)     => request("/admin/feeds/" + encodeURIComponent(id), { method: "PATCH", body: payload }),
        setStatus: (id, status)      => request("/admin/feeds/" + encodeURIComponent(id) + "/status" + qs({ status }), { method: "PATCH" }),
        remove:    (id)              => request("/admin/feeds/" + encodeURIComponent(id), { method: "DELETE" }),
      },

      categoryAliases: {
        list:   ()        => request("/admin/category-aliases"),
        create: (payload) => request("/admin/category-aliases", { method: "POST", body: payload }),
        remove: (term)    => request("/admin/category-aliases/" + encodeURIComponent(term), { method: "DELETE" }),
      },

      queue: {
        list:    ()   => request("/admin/queue"),
        approve: (id) => request("/admin/queue/" + encodeURIComponent(id) + "/approve", { method: "POST" }),
        reject:  (id) => request("/admin/queue/" + encodeURIComponent(id) + "/reject",  { method: "POST" }),
      },

      // Re-fetch full text for RSS articles whose body is only a feed summary.
      backfill: {
        start:  (payload) => request("/admin/articles/backfill-bodies", { method: "POST", body: payload || {} }),
        status: ()        => request("/admin/articles/backfill-bodies/status"),
      },

      staff: {
        list:   ()             => request("/admin/staff"),
        create: (payload)      => request("/admin/staff", { method: "POST", body: payload }),
        update: (id, payload)  => request("/admin/staff/" + encodeURIComponent(id), { method: "PATCH", body: payload }),
        remove: (id)           => request("/admin/staff/" + encodeURIComponent(id), { method: "DELETE" }),
      },

      dashboard: () => request("/admin/dashboard/stats"),
    },
  };

  window.API_BASE = API_BASE;
  window.API = API;

  // Unobtrusive environment badge — local hosts only; production never sees this.
  if (IS_LOCAL) {
    const badge = document.createElement("div");
    badge.id = "env-badge";
    badge.textContent = "LOCAL → " + API_BASE;
    badge.style.cssText =
      "position:fixed;bottom:8px;left:8px;z-index:9999;padding:3px 8px;" +
      "font:11px/1.4 monospace;color:#fff;background:rgba(180,40,40,.85);" +
      "border-radius:4px;pointer-events:none;opacity:.85;";
    document.body.appendChild(badge);
  }
})();
