/* BlogStore.jsx — CRUD de blog sobre Supabase REST.
 * Lee y escribe en public.blog_posts via la anon key.
 * Exposed as window.BlogStore
 */
const BlogStore = (() => {
  const cfg = window.SUPABASE_CONFIG || { enabled: false };
  const REST = cfg.enabled ? cfg.url + "/rest/v1/blog_posts" : null;
  const CATEGORIES = ["Temas Legales", "Temas Tecnicos", "Temas Generales"];

  function headers(extra) {
    return Object.assign({
      "Content-Type": "application/json",
      "apikey": cfg.anonKey,
      "Authorization": "Bearer " + cfg.anonKey,
    }, extra || {});
  }

  function fmtDate(iso) {
    if (!iso) return "";
    try {
      return new Date(iso).toLocaleDateString("es-HN", { day: "2-digit", month: "long", year: "numeric" });
    } catch { return iso; }
  }

  return {
    CATEGORIES,
    fmtDate,

    async getPublished() {
      if (!REST) return [];
      try {
        const res = await fetch(
          REST + "?select=*&published=eq.true&order=created_at.desc",
          { headers: headers() }
        );
        if (!res.ok) throw new Error("HTTP " + res.status);
        return await res.json();
      } catch { return []; }
    },

    async getAll() {
      if (!REST) return [];
      try {
        const res = await fetch(
          REST + "?select=*&order=created_at.desc",
          { headers: headers() }
        );
        if (!res.ok) throw new Error("HTTP " + res.status);
        return await res.json();
      } catch { return []; }
    },

    async getById(id) {
      if (!REST) return null;
      try {
        const res = await fetch(
          REST + "?id=eq." + id + "&select=*&limit=1",
          { headers: headers() }
        );
        if (!res.ok) throw new Error("HTTP " + res.status);
        const rows = await res.json();
        return rows[0] || null;
      } catch { return null; }
    },

    async add(post) {
      if (!REST) return null;
      const payload = {
        title: post.title || "",
        summary: post.summary || "",
        content: post.content || "",
        author: post.author || "Equipo HONDULEGAL",
        category: post.category || "Temas Generales",
        image_url: post.image_url || "",
        facebook_embed: post.facebook_embed || "",
        published: post.published !== undefined ? post.published : true,
      };
      const res = await fetch(REST, {
        method: "POST",
        headers: headers({ "Prefer": "return=representation" }),
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      const rows = await res.json();
      return rows[0] || null;
    },

    async update(id, patch) {
      if (!REST) return null;
      const res = await fetch(REST + "?id=eq." + id, {
        method: "PATCH",
        headers: headers({ "Prefer": "return=representation" }),
        body: JSON.stringify(patch),
      });
      if (!res.ok) throw new Error("HTTP " + res.status);
      const rows = await res.json();
      return rows[0] || null;
    },

    async remove(id) {
      if (!REST) return;
      await fetch(REST + "?id=eq." + id, {
        method: "DELETE",
        headers: headers(),
      });
    },

    async togglePublish(id, current) {
      return this.update(id, { published: !current });
    },
  };
})();

Object.assign(window, { BlogStore });
