/* blog-page.jsx — /blog page composition.
   Mock-data driven v1: 1 featured post + 9 grid posts across
   5 categories. Filter pills update the visible grid.
   Visuals follow the cream-section pattern used in tech-stack
   and the new home agents block.

   Structure:
     1  Nav
     2  BlogHero        (dark teal — eyebrow + headline + search)
     3  FeaturedPost    (cream — large hero card)
     4  PostsGrid       (cream — filters + 3-col grid)
     5  Newsletter      (dark teal — email capture)
     6  CTAFinal + Footer + OrbChat
*/

(function () {
  const { useState, useMemo } = React;

  /* ============================================================
     DATA — categories + posts (hardcoded ES for v1)
     ============================================================ */
  const CATEGORIES = [
    { id: 'all',            label: 'Todos',                   icon: null },
    { id: 'insights',       label: 'Insights',                icon: IconBrain },
    { id: 'producto',       label: 'Producto',                icon: IconStudio },
    { id: 'casos',          label: 'Casos de éxito',          icon: IconBank },
    { id: 'research',       label: 'Research',                icon: IconAnalytics },
    { id: 'conversational', label: 'Conversational Banking', icon: IconWhatsapp },
  ];

  const FEATURED = {
    cat: 'research',
    catLabel: 'Research',
    title: 'El estado de la banca conversacional en LATAM 2026',
    excerpt: 'Hicimos 142 entrevistas a líderes de tecnología, operaciones y CX en 11 países de la región. Te contamos qué bancos están moviendo el acelerador, qué casos están dejando el ROI más rápido y dónde está realmente el techo de adopción.',
    author: 'Equipo Delto',
    authorInitials: 'D',
    date: '14 mayo 2026',
    readTime: '12 min',
    image: '/img/Delto-104.jpg',
  };

  const POSTS = [
    {
      cat: 'insights',
      catLabel: 'Insights',
      title: 'Por qué la mora temprana es la nueva mina de oro de los bancos LATAM',
      excerpt: 'Resolver al cliente en los primeros 30 días de atraso cambia toda la economía del portafolio.',
      author: 'Federico Bouza',
      date: '12 may',
      readTime: '6 min',
    },
    {
      cat: 'casos',
      catLabel: 'Casos de éxito',
      title: 'Cómo Banreservas redujo 32% el tiempo de onboarding con agentes de IA',
      excerpt: 'De 8 días a menos de 90 minutos. La historia detrás del rollout más rápido del año.',
      author: 'Mariana Pérez',
      date: '7 may',
      readTime: '5 min',
    },
    {
      cat: 'producto',
      catLabel: 'Producto',
      title: 'Lanzamos Voice Agents — tu primer canal de voz en producción',
      excerpt: 'Disponible en GA: agentes de voz con compliance bancario y latencia menor a 700ms.',
      author: 'Tomás Rivero',
      date: '5 may',
      readTime: '4 min',
    },
    {
      cat: 'conversational',
      catLabel: 'Conversational Banking',
      title: 'Compliance by design: qué significa y por qué importa',
      excerpt: 'Por qué los bancos no pueden tratar a la IA conversacional como un canal más, y cómo Delto resuelve el día uno.',
      author: 'Laura Vidal',
      date: '2 may',
      readTime: '7 min',
    },
    {
      cat: 'insights',
      catLabel: 'Insights',
      title: 'Cómo funcionan los Banking Large Action Models',
      excerpt: 'BLAMs son la nueva capa entre el LLM y el core bancario. Un deep-dive sobre arquitectura, latencia y costos.',
      author: 'Equipo Delto',
      date: '28 abr',
      readTime: '10 min',
    },
    {
      cat: 'casos',
      catLabel: 'Casos de éxito',
      title: 'Ficohsa habilita WhatsApp para préstamos en 6 semanas',
      excerpt: 'Del primer workshop al primer desembolso en menos de un trimestre. Lecciones del rollout.',
      author: 'Mariana Pérez',
      date: '24 abr',
      readTime: '6 min',
    },
    {
      cat: 'producto',
      catLabel: 'Producto',
      title: 'Q3 2026: Loop entra en GA y cierra la suite agentic',
      excerpt: 'Auto-mejora continua basada en el feedback real. Qué cambia para los equipos de operación.',
      author: 'Tomás Rivero',
      date: '20 abr',
      readTime: '3 min',
    },
    {
      cat: 'conversational',
      catLabel: 'Conversational Banking',
      title: '5 patrones de diseño para conversaciones bancarias',
      excerpt: 'Disclaimers, autenticación step-up, bottom-sheets de monto, confirmaciones — el playbook de los que ya operan.',
      author: 'Laura Vidal',
      date: '17 abr',
      readTime: '8 min',
    },
    {
      cat: 'research',
      catLabel: 'Research',
      title: 'Time-to-recurrent: el nuevo KPI de los proyectos de IA en banca',
      excerpt: 'Por qué medir solo el go-live se quedó corto y qué métrica realmente importa para sostener ROI.',
      author: 'Equipo Delto',
      date: '12 abr',
      readTime: '5 min',
    },
  ];

  /* ============================================================
     CATEGORY ICON — picks the icon component for a category id
     ============================================================ */
  const CATEGORY_ICON = {
    insights:       IconBrain,
    producto:       IconStudio,
    casos:          IconBank,
    research:       IconAnalytics,
    conversational: IconWhatsapp,
  };

  /* ============================================================
     SEARCH GLYPH — small inline SVG (no need to extend icons.jsx)
     ============================================================ */
  function IconSearch({ size = 16 }) {
    return (
      <svg width={size} height={size} viewBox="0 0 24 24" fill="none"
           stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="11" cy="11" r="7"/>
        <line x1="21" y1="21" x2="16.65" y2="16.65"/>
      </svg>
    );
  }

  /* ============================================================
     BLOG HERO — dark teal with dot pattern, eyebrow + headline
     + search (visual only) + meta strip
     ============================================================ */
  function BlogHero() {
    return (
      <section className="bl-hero">
        <div className="hero-bg" aria-hidden>
          <div className="hero-dots"></div>
        </div>
        <div className="bl-hero-inner">
          <div className="bl-hero-eyebrow reveal r-up-sm">
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--dt-lime)', boxShadow: '0 0 10px var(--dt-lime)' }}></span>
            BLOG · NUEVO ARTÍCULO CADA SEMANA
          </div>
          <h1 className="reveal r-up">
            Ideas para la nueva{' '}
            <span className="hl">banca conversacional</span>.
          </h1>
          <p className="bl-hero-sub reveal r-up-sm">
            Research del sector, casos reales y lecturas del equipo que vive
            de cerca la transformación de la banca en LATAM.
          </p>
          <div className="bl-hero-meta reveal r-up-sm">
            <span>+45 artículos publicados</span>
            <span className="bl-hero-meta-dot"></span>
            <span>Promedio 7 min de lectura</span>
            <span className="bl-hero-meta-dot"></span>
            <span>ES · EN · PT-BR</span>
          </div>

          <label className="bl-hero-search reveal r-up-sm">
            <span className="bl-hero-search-ic"><IconSearch size={16} /></span>
            <input
              type="search"
              placeholder="Buscar artículos, casos, autores…"
              aria-label="Buscar artículos"
            />
          </label>
        </div>
      </section>
    );
  }

  /* ============================================================
     FEATURED — large card, photo left + copy right
     ============================================================ */
  function FeaturedPost() {
    return (
      <section className="bl-featured">
        <div className="bl-featured-inner">
          <div className="bl-featured-eyebrow reveal r-up-sm">DESTACADO</div>
          <article className="bl-featured-card reveal r-up" data-cat={FEATURED.cat}>
            <div className="bl-featured-media">
              <img src={FEATURED.image} alt="" />
            </div>
            <div className="bl-featured-copy">
              <span className="bl-featured-cat">
                <span className="bl-card-cat-dot bl-featured-cat-dot"></span>
                {FEATURED.catLabel}
              </span>
              <h2 className="bl-featured-h">{FEATURED.title}</h2>
              <p className="bl-featured-x">{FEATURED.excerpt}</p>
              <div className="bl-featured-meta">
                <span className="bl-featured-avatar">{FEATURED.authorInitials}</span>
                <span className="bl-featured-author">{FEATURED.author}</span>
                <span className="bl-card-meta-dot"></span>
                <span>{FEATURED.date}</span>
                <span className="bl-card-meta-dot"></span>
                <span>{FEATURED.readTime} de lectura</span>
              </div>
              <a href="#" className="bl-featured-link">
                Leer artículo completo
                <IconArrowRight size={14} stroke={2.5} />
              </a>
            </div>
          </article>
        </div>
      </section>
    );
  }

  /* ============================================================
     POSTS GRID — filter pills + 3-col grid + load-more
     ============================================================ */
  function PostsGrid() {
    const [active, setActive] = useState('all');

    const counts = useMemo(() => {
      const c = { all: POSTS.length };
      POSTS.forEach(p => { c[p.cat] = (c[p.cat] || 0) + 1; });
      return c;
    }, []);

    const visible = active === 'all'
      ? POSTS
      : POSTS.filter(p => p.cat === active);

    return (
      <section className="bl-grid-section">
        <div className="bl-grid-inner">
          <div className="bl-filters reveal r-up-sm">
            {CATEGORIES.map(cat => (
              <button
                key={cat.id}
                type="button"
                className={`bl-filter ${active === cat.id ? 'active' : ''}`}
                onClick={() => setActive(cat.id)}
                aria-pressed={active === cat.id}
              >
                {cat.label}
                {counts[cat.id] != null && (
                  <span className="bl-filter-count">{counts[cat.id]}</span>
                )}
              </button>
            ))}
          </div>

          <div className="bl-grid">
            {visible.length === 0 && (
              <div className="bl-empty">No hay artículos en esta categoría todavía.</div>
            )}
            {visible.map((post, i) => {
              const CatIcon = CATEGORY_ICON[post.cat];
              return (
                <a
                  key={i}
                  href="#"
                  className="bl-card reveal r-up-sm"
                  data-cat={post.cat}
                  style={{ animationDelay: `${i * 60}ms` }}
                >
                  <div className="bl-card-media">
                    {CatIcon && <CatIcon className="bl-card-media-ic" size={56} stroke={1.5} />}
                  </div>
                  <div className="bl-card-body">
                    <span className="bl-card-cat">
                      <span className="bl-card-cat-dot"></span>
                      {post.catLabel}
                    </span>
                    <h3 className="bl-card-title">{post.title}</h3>
                    <p className="bl-card-x">{post.excerpt}</p>
                    <div className="bl-card-meta">
                      <span className="bl-card-author">{post.author}</span>
                      <span className="bl-card-meta-dot"></span>
                      <span>{post.date}</span>
                      <span className="bl-card-meta-dot"></span>
                      <span>{post.readTime}</span>
                    </div>
                  </div>
                </a>
              );
            })}
          </div>

          {visible.length >= 6 && (
            <div className="bl-loadmore-wrap reveal r-up-sm">
              <button type="button" className="bl-loadmore">
                Cargar más artículos
              </button>
            </div>
          )}
        </div>
      </section>
    );
  }

  /* ============================================================
     NEWSLETTER — dark teal strip with email capture
     ============================================================ */
  function Newsletter() {
    return (
      <section className="bl-news">
        <div className="bl-news-inner">
          <div className="bl-news-eyebrow reveal r-up-sm">NEWSLETTER</div>
          <h2 className="reveal r-up">
            Recibí los <span className="hl">insights del sector</span> — antes que el resto.
          </h2>
          <p className="bl-news-sub reveal r-up-sm">
            Un mail por semana, 4 minutos de lectura, los movimientos
            de banca conversacional en LATAM bien resumidos.
          </p>
          <form className="bl-news-form reveal r-up-sm" onSubmit={(e) => e.preventDefault()}>
            <input type="email" placeholder="tu@banco.com" aria-label="Email" required />
            <button type="submit">Suscribirme</button>
          </form>
          <p className="bl-news-fine reveal">
            Sin spam. Te podés dar de baja cuando quieras.
          </p>
        </div>
      </section>
    );
  }

  /* ============================================================
     PAGE COMPOSITION
     ============================================================ */
  function BlogPage() {
    const { lang, setLang, t } = useLang();
    useReveal();
    return (
      <>
        <Nav lang={lang} setLang={setLang} t={t} />
        <main>
          <BlogHero />
          <FeaturedPost />
          <PostsGrid />
          <Newsletter />
          <CTAFinal t={t} />
        </main>
        <Footer t={t} />
        <OrbChat />
      </>
    );
  }

  Object.assign(window, { BlogPage });
})();
