// ui_kits/website/BlogGrid.jsx
// Featured + grid section. Uses BlogCard.
//
// Posts are stored bilingually — title/excerpt/date are objects keyed
// by language. We "resolve" them down to flat strings for the current
// language before passing to BlogCard, so the card stays language-agnostic.

const gridStyles = {
  section: { background: 'var(--brand-cream)', padding: '80px 0' },
  header: {
    maxWidth: 1200, margin: '0 auto', padding: '0 32px',
    display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end',
    marginBottom: 36,
  },
  hLeft: {},
  filters: { display: 'flex', gap: 6, alignItems: 'center' },
  chip: {
    fontFamily: 'var(--font-sans)', fontSize: 12, fontWeight: 600,
    letterSpacing: '0.1em', textTransform: 'uppercase',
    padding: '8px 14px', borderRadius: 9999,
    background: 'transparent', color: '#525150',
    border: '1px solid var(--color-divider)',
    cursor: 'pointer', transition: 'all 200ms var(--ease-out)',
  },
  chipActive: {
    background: 'var(--brand-leaf)', color: '#fff',
    borderColor: 'var(--brand-leaf)',
  },
  grid: {
    maxWidth: 1200, margin: '0 auto', padding: '0 32px',
    display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 28,
  },
  feature: {
    maxWidth: 1200, margin: '0 auto 32px', padding: '0 32px',
  },
  more: {
    display: 'flex', justifyContent: 'center', marginTop: 48,
  },
};

// Bilingual sample posts. Spanish titles drawn from the live
// topnaturaltips.com where they exist; the rest are written to match
// the voice (warm, neutral LatAm). Roughly 4 per section so the section
// pages have enough to populate featured + library.
const SAMPLE_POSTS = [
  // ---------- Health / Salud ----------
  { id: 1, category: 'Health', readMinutes: 4, author: 'Paola D.',
    date:    { es: '12 mayo, 2026',  en: 'May 12, 2026' },
    title:   { es: 'Cómo Aliviar la Sinusitis con Métodos Sencillos',
               en: 'How to Relieve Sinusitis with Simple Methods' },
    excerpt: { es: 'Un ritual de vapor tibio, dos hierbas de tu cocina y el patrón de respiración que abre los senos congestionados en menos de un minuto.',
               en: 'A warm-steam ritual, two herbs from your kitchen, and the breathing pattern that opens stuck sinuses in under a minute.' } },

  { id: 3, category: 'Health', readMinutes: 5, author: 'Paola D.',
    date:    { es: '6 mayo, 2026',  en: 'May 6, 2026' },
    title:   { es: 'Poder del Hielo en la Nuca Según la Medicina Tradicional China',
               en: 'The Power of Ice on the Nape, According to Traditional Chinese Medicine' },
    excerpt: { es: 'Dos minutos de hielo en un punto específico de la nuca activan el nervio vago. La medicina tradicional china lo sabía hace siglos; los estudios modernos lo confirman.',
               en: 'Two minutes of ice on a specific point at the nape activates the vagus nerve. TCM knew this for centuries; modern studies are catching up.' } },

  { id: 4, category: 'Health', readMinutes: 8, author: 'Paola D.',
    date:    { es: '3 mayo, 2026',  en: 'May 3, 2026' },
    title:   { es: '¿La felicidad llega a los 60? Esto dice Harvard tras 85 años de estudio',
               en: 'Does Happiness Arrive at 60? What Harvard Says After 85 Years' },
    excerpt: { es: 'El estudio más largo del mundo sobre el bienestar humano tiene una conclusión incómoda: la riqueza no predice la felicidad. Las relaciones sí.',
               en: "The world's longest study on human well-being lands on an uncomfortable conclusion: wealth doesn't predict happiness. Relationships do." } },

  { id: 8, category: 'Health', readMinutes: 3, author: 'Paola D.',
    date:    { es: '18 abril, 2026',  en: 'Apr 18, 2026' },
    title:   { es: 'La respiración 4-7-8: cómo dormirte en menos de tres minutos',
               en: '4-7-8 Breathing: How to Fall Asleep in Under Three Minutes' },
    excerpt: { es: 'Inhala cuatro segundos, retén siete, exhala ocho. Es absurdamente simple y funciona — porque obliga al sistema parasimpático a tomar el control.',
               en: 'Inhale four, hold seven, exhale eight. Absurdly simple and it works — because it forces the parasympathetic system to take over.' } },

  // ---------- Beauty / Belleza ----------
  { id: 5, category: 'Beauty', readMinutes: 3, author: 'Paola D.',
    date:    { es: '30 abril, 2026',  en: 'Apr 30, 2026' },
    title:   { es: 'La mascarilla de miel de cinco ingredientes que sí funciona',
               en: 'The Five-Ingredient Honey Mask That Actually Works' },
    excerpt: { es: 'Miel cruda, yogur natural, cúrcuma, avena molida, una gota de aceite de almendras. Diez minutos. Por qué cada ingrediente está ahí — y cuáles puedes saltar.',
               en: 'Raw honey, plain yogurt, turmeric, ground oats, one drop of almond oil. Ten minutes. Why each ingredient is there — and which you can skip.' } },

  { id: 7, category: 'Beauty', readMinutes: 5, author: 'Paola D.',
    date:    { es: '22 abril, 2026',  en: 'Apr 22, 2026' },
    title:   { es: 'Mioquimia: causas y recomendaciones para el temblor palpebral',
               en: 'Myokymia: Causes and Recommendations for Eyelid Twitching' },
    excerpt: { es: 'Ese párpado que tiembla solo no es nervio dañado — es magnesio bajo, cafeína alta, o sueño insuficiente. Casi siempre los tres a la vez.',
               en: "That eyelid twitch isn't nerve damage — it's low magnesium, high caffeine, or short sleep. Almost always all three at once." } },

  { id: 9, category: 'Beauty', readMinutes: 4, author: 'Paola D.',
    date:    { es: '16 abril, 2026',  en: 'Apr 16, 2026' },
    title:   { es: 'Aceite de jojoba: el más parecido al sebo humano y por qué eso importa',
               en: 'Jojoba Oil: The Closest Match to Human Sebum and Why That Matters' },
    excerpt: { es: 'Técnicamente es una cera, no un aceite — y por eso tu piel lo reconoce. Funciona en pieles grasas, secas y mixtas. Cómo usarlo sin saturar.',
               en: "Technically a wax, not an oil — which is why your skin recognizes it. Works on oily, dry, and combination skin. How to use it without overdoing it." } },

  { id: 10, category: 'Beauty', readMinutes: 6, author: 'Paola D.',
    date:    { es: '10 abril, 2026',  en: 'Apr 10, 2026' },
    title:   { es: 'Cómo leer la lista de ingredientes de tu skincare en 30 segundos',
               en: 'How to Read Your Skincare Ingredient List in 30 Seconds' },
    excerpt: { es: 'Los primeros cinco ingredientes son el 80% del producto. Las palabras clave que importan, los rellenos que no, y la trampa del "natural".',
               en: 'The first five ingredients are 80% of the product. The keywords that matter, the fillers that don\'t, and the "natural" trap.' } },

  // ---------- Nutrition / Nutrición ----------
  { id: 2, category: 'Nutrition', readMinutes: 6, author: 'Paola D.',
    date:    { es: '9 mayo, 2026',  en: 'May 9, 2026' },
    title:   { es: 'Alimentos que deben comerse juntos: manzanas y chocolate oscuro',
               en: 'Foods That Should Be Eaten Together: Apples & Dark Chocolate' },
    excerpt: { es: 'Los polifenoles de la manzana y los flavanoles del cacao se potencian entre sí — efecto cardiovascular medido en estudios. Un puñado y un cuadrito basta.',
               en: 'Apple polyphenols and cocoa flavanols amplify each other — a measurable cardiovascular effect. A small handful and one square is enough.' } },

  { id: 11, category: 'Nutrition', readMinutes: 5, author: 'Paola D.',
    date:    { es: '19 abril, 2026',  en: 'Apr 19, 2026' },
    title:   { es: 'Té de cúrcuma: el protocolo, la pimienta negra, y por qué importa la grasa',
               en: 'Turmeric Tea: The Protocol, the Black Pepper, and Why Fat Matters' },
    excerpt: { es: 'La curcumina es casi inabsorbible sola. Con pimienta negra, multiplica su biodisponibilidad veinte veces. Con grasa, llega a tejidos. Aquí, la receta.',
               en: 'Curcumin is barely absorbable on its own. With black pepper, bioavailability multiplies twentyfold. With fat, it reaches tissues. Here\'s the recipe.' } },

  { id: 12, category: 'Nutrition', readMinutes: 7, author: 'Paola D.',
    date:    { es: '14 abril, 2026',  en: 'Apr 14, 2026' },
    title:   { es: 'Magnesio: por qué casi todos lo necesitamos y qué tipo elegir',
               en: 'Magnesium: Why Almost Everyone Needs It and Which Type to Pick' },
    excerpt: { es: 'Glicinato para dormir, citrato para digestión, malato para energía, óxido para nada. La guía rápida — sin propaganda de suplementos.',
               en: 'Glycinate for sleep, citrate for digestion, malate for energy, oxide for nothing. The quick guide — without the supplement propaganda.' } },

  { id: 13, category: 'Nutrition', readMinutes: 4, author: 'Paola D.',
    date:    { es: '7 abril, 2026',  en: 'Apr 7, 2026' },
    title:   { es: 'Cómo combinar legumbres y granos para obtener proteína completa',
               en: 'How to Combine Legumes and Grains for Complete Protein' },
    excerpt: { es: 'Arroz con frijoles, pan pita con hummus, tortilla con lentejas. Tu abuela ya lo sabía. La ciencia detrás de la combinación más antigua del mundo.',
               en: 'Rice and beans, pita and hummus, tortilla and lentils. Your grandmother knew. The science behind the world\'s oldest food pairing.' } },

  // ---------- Exercise / Ejercicio ----------
  { id: 6, category: 'Exercise', readMinutes: 4, author: 'Paola D.',
    date:    { es: '26 abril, 2026',  en: 'Apr 26, 2026' },
    title:   { es: 'Caminar hacia atrás: el truco para las rodillas que los fisioterapeutas adoran en silencio',
               en: 'Walking Backwards: The Knee Trick Physiotherapists Quietly Love' },
    excerpt: { es: 'Cinco minutos hacia atrás activan los cuádriceps profundos y descomprimen la articulación. Estudios pequeños, evidencia consistente, ridículo de hacer.',
               en: 'Five minutes backwards activates the deep quadriceps and decompresses the joint. Small studies, consistent evidence, ridiculous to do.' } },

  { id: 14, category: 'Exercise', readMinutes: 5, author: 'Paola D.',
    date:    { es: '20 abril, 2026',  en: 'Apr 20, 2026' },
    title:   { es: 'Diez minutos de yoga al despertar — la rutina mínima que sí mantienes',
               en: 'Ten Minutes of Morning Yoga — The Minimal Routine That Actually Sticks' },
    excerpt: { es: 'Ocho posturas en orden fijo, sin pensar. No transforma tu vida en una semana — la transforma cuando llevas tres años haciéndolo.',
               en: 'Eight poses in a fixed order, no thinking. It doesn\'t change your life in a week — it changes it once you\'ve done it for three years.' } },

  { id: 15, category: 'Exercise', readMinutes: 6, author: 'Paola D.',
    date:    { es: '12 abril, 2026',  en: 'Apr 12, 2026' },
    title:   { es: 'Cómo llegar a 10,000 pasos sin pensar en ello (ni usar una caminadora)',
               en: 'How to Hit 10,000 Steps Without Thinking About It (or Using a Treadmill)' },
    excerpt: { es: 'Estacionarse lejos, llamadas caminando, la regla de las escaleras bajo cuatro pisos. Los hábitos invisibles que suman sin que te enteres.',
               en: 'Park far, walk during calls, the "stairs under four floors" rule. The invisible habits that add up without you noticing.' } },

  { id: 16, category: 'Exercise', readMinutes: 4, author: 'Paola D.',
    date:    { es: '5 abril, 2026',  en: 'Apr 5, 2026' },
    title:   { es: 'Recuperación: por qué descansar también es entrenar',
               en: 'Recovery: Why Resting Is Also Training' },
    excerpt: { es: 'El músculo no crece en el gimnasio, crece en la cama. La fisiología del descanso — y cómo dejar de sentirte culpable por tomártelo en serio.',
               en: "Muscle doesn't grow in the gym — it grows in bed. The physiology of rest, and how to stop feeling guilty about taking it seriously." } },
];

// Pick the single most-recent post per category, in the supplied order.
// Posts are roughly date-sorted in SAMPLE_POSTS, but we sort by id descending
// (newer ids = newer posts) just to be safe.
function oneFromEachSection(posts, categories) {
  const byCat = new Map();
  for (const p of [...posts].sort((a, b) => b.id - a.id)) {
    if (!byCat.has(p.category)) byCat.set(p.category, p);
  }
  return categories.map(c => byCat.get(c)).filter(Boolean);
}

function pickLang(value, lang) {
  if (value && typeof value === 'object' && (value.es !== undefined || value.en !== undefined)) {
    return value[lang] ?? value[I18N_DEFAULT_LANG] ?? '';
  }
  return value;
}

// Flatten a bilingual post into single-language strings, plus a translated
// category label, for the card to consume.
function resolvePost(post, lang) {
  return {
    ...post,
    title:    pickLang(post.title, lang),
    excerpt:  pickLang(post.excerpt, lang),
    date:     pickLang(post.date, lang),
    categoryLabel: t('cat.' + post.category, lang),
  };
}

function BlogGrid({ onOpenPost }) {
  const lang = React.useContext(LangContext);
  const tr = useT();

  // Re-render when blog-feed.js swaps in real posts
  const [, force] = React.useReducer(x => x + 1, 0);
  React.useEffect(() => {
    const handler = () => force();
    window.addEventListener('blog-feed-updated', handler);
    return () => window.removeEventListener('blog-feed-updated', handler);
  }, []);

  const [filter, setFilter] = React.useState('All');
  const filters = ['All', 'Health', 'Beauty', 'Nutrition', 'Exercise'];

  // On the homepage we surface one story per section (a tasting menu).
  // Filtering by a single section drops back into "everything in that
  // section" so users can browse the full library inline.
  const filtered = filter === 'All'
    ? oneFromEachSection(SAMPLE_POSTS, filters.slice(1))
    : SAMPLE_POSTS.filter(p => p.category === filter);
  const resolved = filtered.map(p => resolvePost(p, lang));
  const [featured, ...rest] = resolved;

  const chipLabel = (f) => f === 'All' ? tr('blog.filter.all') : tr('cat.' + f);

  return (
    <section style={gridStyles.section}>
      <div style={gridStyles.header}>
        <div style={gridStyles.hLeft}>
          <div className="eyebrow">{tr('blog.eyebrow')}</div>
          <h2 className="section-title" style={{ marginTop: 8 }}>{tr('blog.title')}</h2>
        </div>
        <div style={gridStyles.filters}>
          {filters.map(f => (
            <button key={f}
              style={{ ...gridStyles.chip, ...(filter === f ? gridStyles.chipActive : {}) }}
              onClick={() => setFilter(f)}>{chipLabel(f)}</button>
          ))}
        </div>
      </div>

      {featured && (
        <div style={gridStyles.feature}>
          <BlogCard post={featured} variant="horizontal" onClick={() => onOpenPost && onOpenPost(featured)}/>
        </div>
      )}

      <div style={gridStyles.grid}>
        {rest.map(p => (
          <BlogCard key={p.id} post={p} onClick={() => onOpenPost && onOpenPost(p)}/>
        ))}
      </div>

      <div style={gridStyles.more}>
        <button className="btn btn--secondary">{tr('blog.viewAll')} <ArrowRight size={16}/></button>
      </div>
    </section>
  );
}

window.BlogGrid = BlogGrid;
window.SAMPLE_POSTS = SAMPLE_POSTS;
window.resolvePost = resolvePost;
