// ============================================================
// HOME — WSJ-style editorial cover
// ============================================================

function Home() {
  const [articles, setArticles] = useState(null);
  const [categories, setCategories] = useState([]);
  const [email, setEmail] = useState('');
  const [subscribed, setSubscribed] = useState(false);

  useEffect(() => {
    api.listArticles({ status: 'published' }).then(setArticles);
    api.listCategories().then(setCategories);
  }, []);

  if (!articles) {
    return (
      <div>
        <Masthead active="home" categories={categories} />
        <div className="container" style={{ padding: '120px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
          Carregando edição…
        </div>
      </div>
    );
  }

  const featured = articles.find(a => a.featured) || articles[0];
  const rest     = articles.filter(a => a.id !== featured?.id);

  const lead    = rest.slice(0, 4);    // grid top — 4 cards
  const popular = articles.slice(0, 6); // mais lidas list

  // by category
  const byCat = (id) => articles.filter(a => a.category === id).slice(0, 3);

  return (
    <div>
      <Masthead active="home" categories={categories} />

      {/* HERO: featured + mais lidas rail */}
      <section className="container-wide">
        <div className="lead-grid">
          <article className="lead-story">
            <div className="text">
              <span className="eyebrow red">A MANCHETE DE HOJE</span>
              <h2 className="headline">
                <a href={`#/artigo/${featured.slug}`}>{featured.title}</a>
              </h2>
              <p className="kicker">{featured.subtitle}</p>
              <div className="meta-row">
                <span className="byline"><strong>Por {featured.author}</strong></span>
                <span className="dateline">{fmtDate(featured.publishedAt, { long: true })}</span>
                <span className="dateline">· {readingTime(featured.body)} min</span>
              </div>
            </div>
            <div>
              <div className="cover">
                <img src={featured.cover} alt="" />
              </div>
              <p className="caption">{featured.coverCaption}</p>
            </div>
          </article>

          <aside className="rail">
            <h3>Mais lidas</h3>
            <ol>
              {popular.map(a => {
                const cat = categoryById(a.category);
                return (
                  <li key={a.id}>
                    <a href={`#/artigo/${a.slug}`}>
                      <span className="item-eyebrow">{cat?.name}</span>
                      <h4>{a.title}</h4>
                    </a>
                  </li>
                );
              })}
            </ol>
          </aside>
        </div>
      </section>

      {/* Last news strip */}
      <section className="container">
        <div className="band">
          <div className="band-head">
            <h2>Últimas Notícias</h2>
            <a href="#/categoria/tribuna">Todas as edições →</a>
          </div>
          <div className="card-grid-4">
            {lead.map(a => <ArticleCard key={a.id} article={a} />)}
          </div>
        </div>
      </section>

      {/* WhatsApp consultation strip */}
      <section className="wa-strip">
        <div className="container inner">
          <div className="text">
            Está sendo investigado, indiciado ou preso?
            <em>Atendimento 24 horas, sigilo absoluto. Cada hora conta.</em>
          </div>
          <a className="wa-btn" href="https://wa.me/5513978002785" target="_blank" rel="noopener">
            <Icon.whatsapp /> Defesa urgente via WhatsApp
          </a>
        </div>
      </section>

      {/* Featured categories */}
      <section className="container">
        <div className="band">
          <div className="band-head">
            <h2>Editorias</h2>
            <span className="dateline">Áreas de atuação criminal</span>
          </div>
          <div className="cat-strip">
            {categories.map((c, i) => {
              const count = articles.filter(a => a.category === c.id).length;
              return (
                <a key={c.id} className="cat-tile" href={`#/categoria/${c.slug}`}>
                  <span className="num">№ {String(i + 1).padStart(2, '0')}</span>
                  <span className="name">{c.name}</span>
                  <span className="count">{count} {count === 1 ? 'artigo' : 'artigos'}</span>
                </a>
              );
            })}
          </div>
        </div>
      </section>

      {/* Category bands */}
      <section className="container">
        {categories.slice(0, 4).map(c => {
          const list = byCat(c.id);
          if (!list.length) return null;
          return (
            <div className="faixa" key={c.id}>
              <div>
                <h2>{c.name}</h2>
                <p className="sub">{c.blurb}</p>
                <a href={`#/categoria/${c.slug}`} style={{
                  display: 'inline-block', marginTop: 14,
                  fontFamily: 'var(--sans)', fontSize: 11,
                  letterSpacing: '0.14em', textTransform: 'uppercase',
                  color: 'var(--gold)'
                }}>
                  Ver editoria →
                </a>
              </div>
              <div className="faixa-articles">
                {list.map(a => <ArticleCard key={a.id} article={a} size="sm" />)}
              </div>
            </div>
          );
        })}
      </section>

      {/* Newsletter */}
      <section className="newsletter">
        <div className="container inner">
          <div>
            <span style={{
              fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '0.18em',
              textTransform: 'uppercase', color: 'var(--gold-2)'
            }}>
              A Carta Semanal
            </span>
            <h2>Receba uma análise jurídica<br />em sua caixa, toda quarta.</h2>
            <p>
              Casos comentados, decisões recentes do STF e do STJ, e ensaios
              do Dr. Angelo Santos. Sem ruído. Sem propaganda.
            </p>
          </div>
          <form className="form" onSubmit={(e) => {
            e.preventDefault();
            if (!email) return;
            api.subscribe(email).then(() => { setSubscribed(true); setEmail(''); });
          }}>
            <input
              type="email"
              placeholder="seu-e-mail@exemplo.com"
              value={email}
              onChange={e => setEmail(e.target.value)}
              required
            />
            <button type="submit">
              {subscribed ? '✓ Inscrição confirmada' : 'Quero receber'}
            </button>
            <span className="fineprint">
              Ao se inscrever, você concorda com nossa política de privacidade. Cancele quando quiser.
            </span>
          </form>
        </div>
      </section>

      <Footer />
    </div>
  );
}

// ---------- Category page ----------
function CategoryPage({ slug }) {
  const [articles, setArticles] = useState(null);
  const [categories, setCategories] = useState([]);

  useEffect(() => {
    api.listCategories().then(setCategories);
  }, []);

  useEffect(() => {
    const cat = categories.find(c => c.slug === slug);
    if (cat) {
      api.listArticles({ status: 'published', category: cat.id }).then(setArticles);
    } else if (categories.length) {
      setArticles([]);
    }
  }, [slug, categories]);

  const cat = categories.find(c => c.slug === slug);

  return (
    <div>
      <Masthead active={slug} categories={categories} />

      <div className="container" style={{ padding: '50px 0 24px', textAlign: 'center', borderBottom: '1px solid var(--rule)' }}>
        <span className="eyebrow" style={{ display: 'block', marginBottom: 12 }}>Editoria</span>
        <h1 style={{
          fontFamily: 'var(--display)',
          fontWeight: 400,
          fontSize: 'clamp(40px, 5vw, 64px)',
          margin: 0,
          letterSpacing: '0.01em'
        }}>
          {cat?.name || 'Editoria'}
        </h1>
        <p style={{
          fontFamily: 'var(--serif)',
          fontStyle: 'italic',
          color: 'var(--ink-2)',
          fontSize: 18,
          marginTop: 10
        }}>{cat?.blurb}</p>
      </div>

      <section className="container">
        <div className="band">
          {!articles ? (
            <div className="empty">Carregando…</div>
          ) : articles.length === 0 ? (
            <div className="empty">Nenhum artigo publicado nesta editoria ainda.</div>
          ) : (
            <div className="card-grid-3">
              {articles.map(a => <ArticleCard key={a.id} article={a} />)}
            </div>
          )}
        </div>
      </section>

      <Footer />
    </div>
  );
}

Object.assign(window, { Home, CategoryPage });
