/*
  blog-shared.jsx — helpers del blog: idioma (ES/EN), selección de campo
  bilingüe, formato de fecha y un toggle de idioma. Exporta a window.
*/

const BLOG_SITE = {
  name: "Emiliano Centenero",
  base: "Bienes raíces · Guadalajara & Zapopan",
  wa: "https://wa.me/523327947692",
};

const BLOG_T = {
  es: {
    eyebrow: "Notas y guías",
    title: "Blog",
    lead: "Mercado, colonias y consejos prácticos sobre bienes raíces en Guadalajara y México.",
    readSuffix: "min de lectura",
    by: "Por",
    back: "← Volver al blog",
    empty: "Pronto publicaré las primeras notas.",
    related: "Sigue leyendo",
    share: "Compartir",
    cta: "¿Tienes una duda sobre tu propiedad? Hablemos.",
    ctaBtn: "Escríbeme por WhatsApp",
    all: "Ver todas las notas",
  },
  en: {
    eyebrow: "Notes & guides",
    title: "Blog",
    lead: "Market, neighborhoods and practical advice on real estate in Guadalajara and Mexico.",
    readSuffix: "min read",
    by: "By",
    back: "← Back to the blog",
    empty: "I'll publish the first notes soon.",
    related: "Keep reading",
    share: "Share",
    cta: "Have a question about your property? Let's talk.",
    ctaBtn: "Message me on WhatsApp",
    all: "See all notes",
  },
};

function blogLang() {
  const u = new URLSearchParams(location.search).get("lang");
  if (u === "es" || u === "en") return u;
  try { return localStorage.getItem("ec_lang") || "es"; } catch (e) { return "es"; }
}
function setBlogLang(l) {
  try { localStorage.setItem("ec_lang", l); } catch (e) {}
}
// Devuelve el campo en el idioma pedido, con respaldo al otro.
function pickField(post, base, lang) {
  if (!post) return "";
  return post[base + "_" + lang] || post[base + "_es"] || post[base + "_en"] || "";
}
function fmtDate(iso, lang) {
  if (!iso) return "";
  const d = new Date(iso + "T00:00:00");
  if (isNaN(d.getTime())) return iso;
  return d.toLocaleDateString(lang === "en" ? "en-US" : "es-MX", { year: "numeric", month: "long", day: "numeric" });
}
// Notas que ya tienen página estática (HTML pre-generado, ideal para SEO con IA).
// Cuando generes estáticas de notas nuevas, agrega su slug aquí.
const STATIC_NOTES = ["providencia-vs-andares-2026", "preventas-guadalajara-2026", "tendencias-mercado-gdl-2026"];
function postUrl(post) { return "nota.html?slug=" + encodeURIComponent(post.id); }
function noteUrl(post, lang) {
  if (STATIC_NOTES.indexOf(post.id) !== -1) return "nota-" + post.id + ".html";
  return "nota.html?slug=" + encodeURIComponent(post.id) + "&lang=" + lang;
}

// Toggle ES/EN reutilizable
function BlogLangToggle({ lang, setLang }) {
  return (
    <button
      className="lang-toggle"
      onClick={() => { const n = lang === "es" ? "en" : "es"; setBlogLang(n); setLang(n); }}
      title={lang === "es" ? "Switch to English" : "Cambiar a español"}
    >
      <b>{lang.toUpperCase()}</b>
      <span>/ {lang === "es" ? "EN" : "ES"}</span>
    </button>
  );
}

// Carga notas públicas (DB) con respaldo a window.POSTS
function loadBlogPosts() {
  if (window.ECDB && ECDB.isConfigured()) {
    return ECDB.loadPublicPosts()
      .then((list) => (list && list.length ? list : (window.POSTS || [])))
      .catch(() => (window.POSTS || []));
  }
  return Promise.resolve(window.POSTS || []);
}

Object.assign(window, {
  BLOG_SITE, BLOG_T, blogLang, setBlogLang, pickField, fmtDate, postUrl,
  STATIC_NOTES, noteUrl, BlogLangToggle, loadBlogPosts,
});
