// pages-blog.jsx — Blog list and single post

const { useState: useBlogState, useMemo: useBlogMemo } = React;

const BLOG_CATEGORIES = {
  es: { all: 'Todos', sombreros: 'Sombreros', cuero: 'Cuero', correas: 'Correas', hebillas: 'Hebillas', estilo: 'Estilo' },
  en: { all: 'All',  sombreros: 'Hats',      cuero: 'Leather', correas: 'Belts', hebillas: 'Buckles', estilo: 'Style' },
  fr: { all: 'Tous', sombreros: 'Chapeaux',  cuero: 'Cuir',    correas: 'Ceintures', hebillas: 'Boucles', estilo: 'Style' },
};

const BLOG_UI = {
  es: { readMin: 'min de lectura', backToBlog: '← Volver al blog', relatedTitle: 'Más artículos', featuredEyebrow: 'Artículo destacado', allArticles: 'Todos los artículos', heroEyebrow: 'Mundo Vaquero · SensStyle', heroTitle: 'El blog del cuero y\nel estilo western.', heroSub: 'Guías de cuidado, historia del oficio, tendencias y consejos para vivir con autenticidad.' },
  en: { readMin: 'min read', backToBlog: '← Back to blog', relatedTitle: 'More articles', featuredEyebrow: 'Featured article', allArticles: 'All articles', heroEyebrow: 'Western World · SensStyle', heroTitle: 'The leather & western\nstyle blog.', heroSub: 'Care guides, craft history, trends and advice for living with authenticity.' },
  fr: { readMin: 'min de lecture', backToBlog: '← Retour au blog', relatedTitle: 'Plus d\'articles', featuredEyebrow: 'Article à la une', allArticles: 'Tous les articles', heroEyebrow: 'Monde Western · SensStyle', heroTitle: 'Le blog du cuir et\ndu style western.', heroSub: 'Guides d\'entretien, histoire de l\'artisanat, tendances et conseils pour vivre avec authenticité.' },
};

function formatDate(dateStr, lang) {
  const d = new Date(dateStr);
  const opts = { year: 'numeric', month: 'long', day: 'numeric' };
  const locale = lang === 'fr' ? 'fr-CA' : lang === 'en' ? 'en-CA' : 'es-MX';
  return d.toLocaleDateString(locale, opts);
}

// ── Blog Card ─────────────────────────────────────────────────────────────────
function BlogCard({ post, lang, navigate, featured = false }) {
  const ui = BLOG_UI[lang];
  const cats = BLOG_CATEGORIES[lang];
  return (
    <button
      onClick={() => navigate({ page: 'blog-post', slug: post.slug })}
      style={{ textAlign: 'left', background: 'transparent', width: '100%', display: 'flex', flexDirection: 'column', gap: 0 }}
    >
      <div style={{ position: 'relative', overflow: 'hidden', marginBottom: 20 }}>
        <Placeholder
          label={post.title[lang]}
          ratio={featured ? '16/9' : '3/2'}
          src={post.hero}
          style={{ transition: 'transform 500ms var(--ease)' }}
        />
        <div style={{
          position: 'absolute', top: 14, left: 14,
          background: 'var(--ink)', color: 'var(--cream)',
          fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
          padding: '4px 10px',
        }}>
          {cats[post.category] || post.category}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginBottom: 10 }}>
        <span className="eyebrow muted">{formatDate(post.date, lang)}</span>
        <span style={{ width: 3, height: 3, borderRadius: '50%', background: 'var(--muted)', opacity: 0.5, flexShrink: 0 }} />
        <span className="eyebrow muted">{post.readMin} {ui.readMin}</span>
      </div>
      <h3 style={{
        fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 400,
        fontSize: featured ? 'clamp(24px,3vw,36px)' : 'clamp(18px,2vw,22px)',
        lineHeight: 1.2, color: 'var(--ink)',
        transition: 'color 200ms var(--ease)',
      }}>
        {post.title[lang]}
      </h3>
      <p style={{ marginTop: 10, color: 'var(--muted)', fontSize: 16, lineHeight: 1.55 }}>
        {post.excerpt[lang]}
      </p>
      <span style={{ marginTop: 16, fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--gold-600)' }}>
        {lang === 'fr' ? 'Lire →' : lang === 'en' ? 'Read →' : 'Leer →'}
      </span>
    </button>
  );
}

// ── Blog List Page ────────────────────────────────────────────────────────────
function BlogPage({ lang, navigate }) {
  const [activeCategory, setActiveCategory] = useBlogState('all');
  const ui = BLOG_UI[lang];
  const cats = BLOG_CATEGORIES[lang];

  const filtered = useBlogMemo(() =>
    activeCategory === 'all' ? BLOG_POSTS : BLOG_POSTS.filter(p => p.category === activeCategory),
    [activeCategory]
  );

  const featured = filtered[0];
  const rest = filtered.slice(1);

  return (
    <div className="page-enter" style={{ background: 'var(--parchment)' }}>

      {/* ── HERO ── */}
      <section style={{ background: 'var(--ink)', padding: '100px 0 80px', position: 'relative', overflow: 'hidden' }}>
        <div style={{ position: 'absolute', inset: 0, opacity: 0.06, background: 'radial-gradient(circle at 30% 50%, var(--gold-300), transparent 60%), radial-gradient(circle at 80% 20%, var(--saddle-500), transparent 50%)', pointerEvents: 'none' }} />
        <div className="container">
          <div style={{ color: 'var(--gold-300)', marginBottom: 24 }}><Ornament color="var(--gold-300)" /></div>
          <div className="eyebrow light" style={{ color: 'rgba(245,237,224,0.5)', marginBottom: 20 }}>{ui.heroEyebrow}</div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 400, fontSize: 'clamp(44px,6vw,80px)', lineHeight: 1.05, color: 'var(--cream)', whiteSpace: 'pre-line', maxWidth: '16ch', marginBottom: 24 }}>
            {ui.heroTitle}
          </h1>
          <p style={{ color: 'rgba(245,237,224,0.65)', fontSize: 18, lineHeight: 1.6, maxWidth: '50ch' }}>
            {ui.heroSub}
          </p>
        </div>
      </section>

      {/* ── CATEGORY FILTER ── */}
      <div className="blog-filter-bar" style={{ background: 'var(--parchment)', borderBottom: '1px solid rgba(27,18,10,0.1)', position: 'sticky', top: 'calc(var(--top-bar-h) - 7px)', zIndex: 10, marginTop: -1 }}>
        <div className="container" style={{ display: 'flex', gap: 0, overflowX: 'auto', paddingBottom: 0 }}>
          {Object.entries(cats).map(([key, label]) => (
            <button
              key={key}
              onClick={() => setActiveCategory(key)}
              style={{
                fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase',
                padding: '18px 24px', background: 'none', border: 'none', cursor: 'pointer', whiteSpace: 'nowrap',
                color: activeCategory === key ? 'var(--ink)' : 'var(--muted)',
                borderBottom: activeCategory === key ? '2px solid var(--ink)' : '2px solid transparent',
                transition: 'color 180ms, border-color 180ms',
              }}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      <div className="container" style={{ padding: '72px 0 120px' }}>

        {/* ── FEATURED ── */}
        {featured && (
          <div style={{ marginBottom: 80 }}>
            <div className="eyebrow muted" style={{ marginBottom: 24 }}>{ui.featuredEyebrow}</div>
            <div className="blog-featured-grid" style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 56, alignItems: 'center' }}>
              <BlogCard post={featured} lang={lang} navigate={navigate} featured />
              <div style={{ borderLeft: '1px solid rgba(27,18,10,0.12)', paddingLeft: 56 }}>
                <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 56, color: 'var(--gold-300)', lineHeight: 1, marginBottom: 16, opacity: 0.4 }}>01</div>
                <p style={{ fontSize: 18, lineHeight: 1.7, color: 'var(--charcoal)' }}>{featured.excerpt[lang]}</p>
                <div style={{ marginTop: 32, display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  {featured.content.slice(0,2).filter(b => b.t === 'h2').map((b, i) => (
                    <span key={i} style={{ background: 'rgba(27,18,10,0.06)', padding: '4px 12px', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--muted)' }}>
                      {b.v}
                    </span>
                  ))}
                </div>
              </div>
            </div>
          </div>
        )}

        {/* ── DIVIDER ── */}
        {rest.length > 0 && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 56 }}>
            <div style={{ flex: 1, height: 1, background: 'rgba(27,18,10,0.1)' }} />
            <span className="eyebrow muted">{ui.allArticles}</span>
            <div style={{ flex: 1, height: 1, background: 'rgba(27,18,10,0.1)' }} />
          </div>
        )}

        {/* ── GRID ── */}
        {rest.length > 0 && (
          <div className="blog-grid">
            {rest.map(post => (
              <BlogCard key={post.slug} post={post} lang={lang} navigate={navigate} />
            ))}
          </div>
        )}

        {filtered.length === 0 && (
          <div style={{ textAlign: 'center', padding: '80px 0', color: 'var(--muted)', fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 28 }}>
            {lang === 'fr' ? 'Aucun article dans cette catégorie.' : lang === 'en' ? 'No articles in this category.' : 'No hay artículos en esta categoría.'}
          </div>
        )}
      </div>
    </div>
  );
}

// ── Blog Post Content Renderer ────────────────────────────────────────────────
function BlogContent({ blocks }) {
  return (
    <div className="blog-body">
      {blocks.map((block, i) => {
        if (block.t === 'p') return <p key={i}>{block.v}</p>;
        if (block.t === 'h2') return <h2 key={i}>{block.v}</h2>;
        if (block.t === 'h3') return <h3 key={i}>{block.v}</h3>;
        if (block.t === 'ul') return (
          <ul key={i}>
            {block.v.map((item, j) => <li key={j}>{item}</li>)}
          </ul>
        );
        if (block.t === 'blockquote') return <blockquote key={i}>{block.v}</blockquote>;
        return null;
      })}
    </div>
  );
}

// ── Blog Post Page ────────────────────────────────────────────────────────────
function BlogPostPage({ lang, navigate, slug }) {
  const post = BLOG_POSTS.find(p => p.slug === slug) || BLOG_POSTS[0];
  const ui = BLOG_UI[lang];
  const cats = BLOG_CATEGORIES[lang];
  const related = BLOG_POSTS.filter(p => p.slug !== post.slug && p.category === post.category).slice(0, 2);

  return (
    <div className="page-enter" style={{ background: 'var(--parchment)' }}>

      {/* ── HERO ── */}
      <div style={{ position: 'relative', height: 'clamp(320px, 50vh, 560px)', overflow: 'hidden' }}>
        <Placeholder label={post.title[lang]} ratio="unset" src={post.hero} style={{ height: '100%' }} />
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(to top, rgba(27,18,10,0.85) 0%, rgba(27,18,10,0.2) 60%, transparent 100%)' }} />
        <div className="container" style={{ position: 'absolute', bottom: 0, left: '50%', transform: 'translateX(-50%)', width: '100%', padding: '0 var(--gutter) 48px' }}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'center', marginBottom: 16 }}>
            <span style={{ background: 'var(--gold-500)', color: 'var(--ink)', fontFamily: 'var(--font-mono)', fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase', padding: '4px 10px' }}>
              {cats[post.category]}
            </span>
            <span style={{ color: 'rgba(245,237,224,0.55)', fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.15em' }}>
              {formatDate(post.date, lang)} · {post.readMin} {ui.readMin}
            </span>
          </div>
          <h1 style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontWeight: 400, fontSize: 'clamp(28px,4vw,52px)', lineHeight: 1.1, color: 'var(--cream)', maxWidth: '22ch' }}>
            {post.title[lang]}
          </h1>
        </div>
      </div>

      {/* ── ARTICLE ── */}
      <div className="container blog-post-layout">

        {/* Back link */}
        <button
          onClick={() => navigate({ page: 'blog' })}
          style={{ fontFamily: 'var(--font-mono)', fontSize: 10, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--muted)', background: 'none', border: 'none', cursor: 'pointer', padding: '40px 0 0', display: 'block' }}
        >
          {ui.backToBlog}
        </button>

        {/* Excerpt lead */}
        <p className="blog-lead">{post.excerpt[lang]}</p>

        {/* Body */}
        <BlogContent blocks={post.content} />
      </div>

      {/* ── RELATED ── */}
      {related.length > 0 && (
        <section style={{ borderTop: '1px solid rgba(27,18,10,0.1)', padding: '80px 0 100px', marginTop: 80 }}>
          <div className="container">
            <div className="eyebrow muted" style={{ marginBottom: 40 }}>{ui.relatedTitle}</div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${related.length}, 1fr)`, gap: 40 }}>
              {related.map(p => <BlogCard key={p.slug} post={p} lang={lang} navigate={navigate} />)}
            </div>
          </div>
        </section>
      )}
    </div>
  );
}

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