/* global React, ReactDOM */
/* lp-blog.jsx — dual mode: listing (no slug) / article (slug present) */
const { useEffect: useEff_bl, useState: useSt_bl } = React;

const SANITY_PROJECT = 'gyrzd1m5';
const SANITY_DATASET = 'production';
const SANITY_API     = `https://${SANITY_PROJECT}.api.sanity.io/v2024-01-01/data/query/${SANITY_DATASET}`;
const SANITY_IMG     = `https://cdn.sanity.io/images/gyrzd1m5/${SANITY_DATASET}/`;

const slugify = (text) =>
  text.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]/g, '');

const formatDate = (iso) => {
  if (!iso) return '';
  return new Date(iso).toLocaleDateString('es-MX', { year: 'numeric', month: 'long', day: 'numeric' });
};

/* ══════════════════════════════════════════
   BLOG LISTING
═══════════════════════════════════════════ */

function BlogCard({ post, featured }) {
  const href = `/blog?slug=${post.slug || ''}`;
  if (featured) {
    return (
      <a href={href} className="blc-featured">
        <div className="blc-featured-img" style={post.imageUrl ? { backgroundImage: `url(${post.imageUrl})` } : {}} />
        <div className="blc-featured-body">
          <span className="blc-eyebrow">{post.category}{post.readTime ? ` · ${post.readTime} min` : ''}</span>
          <h2 className="blc-featured-title">{post.title}</h2>
          {post.excerpt && <p className="blc-featured-excerpt">{post.excerpt}</p>}
          <span className="blc-date">{formatDate(post.publishedAt)}</span>
          <span className="blc-cta">Leer artículo
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M3 8h10M9 4l4 4-4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
          </span>
        </div>
      </a>
    );
  }
  return (
    <a href={href} className="blc-card">
      {post.imageUrl && <div className="blc-card-img" style={{ backgroundImage: `url(${post.imageUrl})` }} />}
      <div className="blc-card-body">
        <span className="blc-eyebrow">{post.category}{post.readTime ? ` · ${post.readTime} min` : ''}</span>
        <h3 className="blc-card-title">{post.title}</h3>
        {post.excerpt && <p className="blc-card-excerpt">{post.excerpt}</p>}
        <span className="blc-date">{formatDate(post.publishedAt)}</span>
      </div>
    </a>
  );
}

function BlogListing() {
  const [posts, setPosts]     = useSt_bl([]);
  const [loading, setLoading] = useSt_bl(true);

  useEff_bl(() => {
    const q = encodeURIComponent(
      `*[_type=="post"] | order(publishedAt desc) { title, "slug": slug.current, category, readTime, publishedAt, excerpt, "imageUrl": mainImage.asset->url }`
    );
    fetch(`${SANITY_API}?query=${q}`)
      .then(r => r.json())
      .then(d => { setPosts(d.result || []); setLoading(false); })
      .catch(() => setLoading(false));
  }, []);

  return (
    <>
      <CustomCursor />
      <Nav />

      {/* ── Hero ── */}
      <header className="blc-hero" style={{ backgroundImage: `url('${ASSET_BASE}uploads/jardin.webp')` }}>
        <div className="blc-hero-veil" />
        <div className="container blc-hero-content">
          <span className="blc-hero-eyebrow eyebrow">Diario del refugio</span>
          <h1 className="blc-hero-title">Historias desde<br />Quinta Mompaní</h1>
          <p className="blc-hero-sub">Bodas, celebraciones y los momentos que hacen de este lugar algo único.</p>
        </div>
      </header>

      {/* ── Listing ── */}
      <div className="container blc-container">
        {loading && (
          <div className="blc-loading">
            <div className="blc-skel-featured" />
            <div className="blc-skel-grid">
              <div className="blc-skel-card" />
              <div className="blc-skel-card" />
            </div>
          </div>
        )}

        {!loading && posts.length === 0 && (
          <div className="blc-empty">
            <span className="eyebrow" style={{ color: 'var(--gold)' }}>Próximamente</span>
            <p className="blc-empty-text">Pronto publicaremos nuestras primeras historias.</p>
          </div>
        )}

        {!loading && posts.length > 0 && (
          <>
            <BlogCard post={posts[0]} featured={true} />
            {posts.length > 1 && (
              <>
                <div className="blc-grid-label">
                  <span className="blc-grid-label-line" />
                  <span className="blc-grid-label-text">Más artículos</span>
                  <span className="blc-grid-label-line" />
                </div>
                <div className="blc-grid">
                  {posts.slice(1).map((p, i) => (
                    <BlogCard key={i} post={p} featured={false} />
                  ))}
                </div>
              </>
            )}
          </>
        )}
      </div>

      <Footer />
      <WhatsAppFloat />
    </>
  );
}

/* ══════════════════════════════════════════
   BLOG ARTICLE (detail)
═══════════════════════════════════════════ */

function renderBlock(block, i) {
  if (block._type === 'image') {
    const ref  = block.asset?._ref || '';
    const file = ref.replace('image-', '').replace(/-([a-z]+)$/, '.$1');
    return <img key={i} src={`${SANITY_IMG}${file}`} alt={block.alt || ''} className="bpa-body-img" />;
  }
  if (block._type !== 'block') return null;

  const children = (block.children || []).map((span, si) => {
    let node = span.text;
    if (span.marks?.includes('strong')) node = <strong key={si}>{node}</strong>;
    if (span.marks?.includes('em'))     node = <em key={si}>{node}</em>;
    return node;
  });

  const style   = block.style || 'normal';
  const rawText = (block.children || []).map(s => s.text).join('');

  if (style === 'h2')         return <h2 key={i} id={slugify(rawText)} className="bpa-h2">{children}</h2>;
  if (style === 'h3')         return <h3 key={i} id={slugify(rawText)} className="bpa-h3">{children}</h3>;
  if (style === 'blockquote') return <blockquote key={i} className="bpa-quote">{children}</blockquote>;
  return <p key={i} className="bpa-p">{children}</p>;
}

function TableOfContents({ body }) {
  const headings = (body || [])
    .filter(b => b._type === 'block' && (b.style === 'h2' || b.style === 'h3'))
    .map(b => ({ text: (b.children || []).map(s => s.text).join(''), level: b.style }));

  if (headings.length === 0) return null;

  return (
    <div className="bpa-toc">
      <span className="bpa-toc-label">En este artículo</span>
      <ul className="bpa-toc-list">
        {headings.map((h, i) => (
          <li key={i} className={`bpa-toc-item bpa-toc-${h.level}`}>
            <a href={`#${slugify(h.text)}`} className="bpa-toc-link">{h.text}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

function ReadingProgress() {
  const [pct, setPct] = useSt_bl(0);
  useEff_bl(() => {
    const onScroll = () => {
      const el  = document.documentElement;
      const max = el.scrollHeight - el.clientHeight;
      setPct(max > 0 ? (window.scrollY / max) * 100 : 0);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return <div className="bpa-progress" style={{ width: pct + '%' }} />;
}

function BlogArticle() {
  const [post, setPost]       = useSt_bl(null);
  const [loading, setLoading] = useSt_bl(true);
  const [error, setError]     = useSt_bl(false);

  useEff_bl(() => {
    const slug = new URLSearchParams(window.location.search).get('slug');
    if (!slug) { setError(true); setLoading(false); return; }

    const q = encodeURIComponent(
      `*[_type=="post" && slug.current==$slug][0]{ title, category, readTime, publishedAt, excerpt, "imageUrl": mainImage.asset->url, body }`
    );
    const slugParam = `%24slug=${encodeURIComponent(JSON.stringify(slug))}`;
    fetch(`${SANITY_API}?query=${q}&${slugParam}`)
      .then(r => r.json())
      .then(d => {
        if (!d.result) { setError(true); } else { setPost(d.result); }
        setLoading(false);
      })
      .catch(() => { setError(true); setLoading(false); });
  }, []);

  return (
    <>
      <CustomCursor />
      <ReadingProgress />
      <Nav />

      {loading && (
        <div className="bpa-loading">
          <div className="bpa-skel-hero" />
          <div className="bpa-skel-body container">
            <div className="bpa-skel-line w-sm" />
            <div className="bpa-skel-line w-lg" style={{ height: '2.5rem', marginBottom: '1.5rem' }} />
            <div className="bpa-skel-line w-md" />
            <div className="bpa-skel-line w-lg" />
            <div className="bpa-skel-line w-sm" />
          </div>
        </div>
      )}

      {error && !loading && (
        <div className="bpa-error container">
          <div className="eyebrow" style={{ color: 'var(--gold)' }}>Artículo no encontrado</div>
          <h1 className="display">Este artículo no existe.</h1>
          <a href="/blog" className="bpa-back-btn" style={{ marginTop: '2rem', display: 'inline-flex' }}>
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Ver todos los artículos
          </a>
        </div>
      )}

      {post && !loading && (
        <article className="bpa-article">
          <header
            className="bpa-hero"
            style={post.imageUrl ? { backgroundImage: `url(${post.imageUrl})` } : {}}
          >
            <div className="bpa-hero-veil" />
            <div className="bpa-hero-top container">
              <span className="bpa-eyebrow">
                {post.category}{post.readTime ? ` · ${post.readTime} min` : ''}
              </span>
            </div>
            <div className="bpa-hero-bottom container">
              <h1 className="bpa-title">{post.title}</h1>
              {post.publishedAt && <p className="bpa-hero-date">{formatDate(post.publishedAt)}</p>}
            </div>
          </header>

          <div className="bpa-layout container">
            <aside className="bpa-aside">
              <div className="bpa-aside-sticky">
                {post.publishedAt && (
                  <div className="bpa-meta-block">
                    <span className="bpa-meta-label">Publicado</span>
                    <span className="bpa-meta-val">{formatDate(post.publishedAt)}</span>
                  </div>
                )}
                {post.category && (
                  <div className="bpa-meta-block">
                    <span className="bpa-meta-label">Categoría</span>
                    <span className="bpa-meta-val">{post.category}</span>
                  </div>
                )}
                {post.readTime && (
                  <div className="bpa-meta-block">
                    <span className="bpa-meta-label">Lectura</span>
                    <span className="bpa-meta-val">{post.readTime} min</span>
                  </div>
                )}
                <a href="/blog" className="bpa-back">
                  <svg width="13" height="13" viewBox="0 0 16 16" fill="none"><path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  Todos los artículos
                </a>
              </div>
            </aside>

            <main className="bpa-main">
              {post.excerpt && <p className="bpa-lead">{post.excerpt}</p>}
              <div className="bpa-body">
                {(post.body || []).map((block, i) => renderBlock(block, i))}
              </div>
              <div className="bpa-end">
                <a href="/blog" className="bpa-back-btn">
                  <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M10 3L5 8l5 5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  Ver todos los artículos
                </a>
              </div>
            </main>

            <aside className="bpa-right">
              <div className="bpa-right-sticky">
                <TableOfContents body={post.body} />
              </div>
            </aside>
          </div>
        </article>
      )}

      <Footer />
      <WhatsAppFloat />
    </>
  );
}

/* ══════════════════════════════════════════
   ROUTER — slug present → article, else → listing
═══════════════════════════════════════════ */
const hasSlug = new URLSearchParams(window.location.search).has('slug');
ReactDOM.createRoot(document.getElementById('root')).render(
  hasSlug ? <BlogArticle /> : <BlogListing />
);
