// ============================================================
// ARTICLE — Single article page
// ============================================================

function Article({ slug }) {
  const [article, setArticle] = useState(null);
  const [related, setRelated] = useState([]);
  const [categories, setCategories] = useState([]);
  const [notFound, setNotFound] = useState(false);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    api.listCategories().then(setCategories);
    api.getArticle(slug).then(a => {
      if (!a) { setNotFound(true); return; }
      setArticle(a);
      // related from same category
      api.listArticles({ status: 'published', category: a.category }).then(list => {
        setRelated(list.filter(x => x.id !== a.id).slice(0, 3));
      });
    });
  }, [slug]);

  if (notFound) {
    return (
      <div>
        <Masthead categories={categories} />
        <div className="container" style={{ padding: '120px 0', textAlign: 'center' }}>
          <span className="eyebrow">404 · Sem manchete</span>
          <h1 style={{ fontFamily: 'var(--display)', fontSize: 48, fontWeight: 400, marginTop: 12 }}>
            Este artigo não foi encontrado.
          </h1>
          <a href="#/" style={{
            display: 'inline-block', marginTop: 18,
            fontFamily: 'var(--sans)', fontSize: 12, letterSpacing: '0.12em',
            textTransform: 'uppercase', color: 'var(--gold)'
          }}>
            ← Voltar à capa
          </a>
        </div>
        <Footer />
      </div>
    );
  }
  if (!article) {
    return (
      <div>
        <Masthead categories={categories} />
        <div className="container" style={{ padding: '120px 0', textAlign: 'center', color: 'var(--ink-3)' }}>
          Carregando edição…
        </div>
      </div>
    );
  }

  const cat = categoryById(article.category);
  const shareUrl = window.location.href;
  const shareTitle = article.title;

  const shareWA = () => window.open(`https://wa.me/?text=${encodeURIComponent(shareTitle + ' — ' + shareUrl)}`, '_blank');
  const shareX  = () => window.open(`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareTitle)}&url=${encodeURIComponent(shareUrl)}`, '_blank');
  const shareIn = () => window.open(`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(shareUrl)}`, '_blank');
  const copyLink= () => { navigator.clipboard?.writeText(shareUrl); setCopied(true); setTimeout(() => setCopied(false), 1500); };

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

      <article className="article-shell">
        <header className="article-head">
          {cat && <span className="eyebrow">{cat.name}</span>}
          <h1 className="headline">{article.title}</h1>
          <p className="kicker">{article.subtitle}</p>
          <div className="article-meta">
            <span>Por <strong>{article.author}</strong></span>
            <span className="sep" />
            <span>{fmtDateLong(article.publishedAt)}</span>
            <span className="sep" />
            <span>{readingTime(article.body)} min de leitura</span>
          </div>
        </header>

        {article.cover && (
          <figure className="cover-figure">
            <div className="img"><img src={article.cover} alt="" /></div>
            {article.coverCaption && <figcaption className="cap">{article.coverCaption}</figcaption>}
          </figure>
        )}

        <div className="article-layout">
          {/* Share rail */}
          <aside className="share-rail" aria-label="Compartilhar">
            <span className="label">Compartilhar</span>
            <button className="share-btn wa" onClick={shareWA} title="WhatsApp"><Icon.whatsapp /></button>
            <button className="share-btn" onClick={shareX} title="X (Twitter)"><Icon.x /></button>
            <button className="share-btn" onClick={shareIn} title="LinkedIn"><Icon.linkedin /></button>
            <button className="share-btn" onClick={copyLink} title="Copiar link">
              {copied ? <Icon.check /> : <Icon.link />}
            </button>
          </aside>

          <div className="article-body" dangerouslySetInnerHTML={{ __html: article.body }} />

          <div /> {/* right gutter */}
        </div>

        {/* Tags */}
        {article.tags && article.tags.length > 0 && (
          <div style={{
            maxWidth: 'var(--container-text)',
            margin: '32px auto 0',
            padding: '0 24px',
            display: 'flex',
            gap: 10,
            flexWrap: 'wrap',
            borderTop: '1px solid var(--rule)',
            paddingTop: 18
          }}>
            <span style={{
              fontFamily: 'var(--sans)', fontSize: 11, letterSpacing: '0.14em',
              textTransform: 'uppercase', color: 'var(--ink-3)', marginRight: 4
            }}>Etiquetas</span>
            {article.tags.map(t => (
              <a key={t} href={`#/`} style={{
                fontFamily: 'var(--sans)', fontSize: 12,
                padding: '4px 10px', border: '1px solid var(--rule)',
                color: 'var(--ink-2)', textTransform: 'lowercase'
              }}>{t}</a>
            ))}
          </div>
        )}

        {/* Author bio */}
        <div className="author-card">
          <div className="avatar">
            <HedcutAvatar />
          </div>
          <div>
            <h4>Dr. Angelo Santos</h4>
            <div className="role">Advogado Criminalista · OAB-SP 377.580</div>
            <p>
              Pós-graduado em Ciências Criminais pela PUC-MG e ex-representante da OAB Santos
              na Comissão de Política de Drogas. Mais de uma década atuando em defesa criminal,
              com mais de 300 casos em tribunal.
            </p>
          </div>
        </div>
      </article>

      {/* Related */}
      {related.length > 0 && (
        <section className="related">
          <div className="container">
            <h3>Leia também</h3>
            <div className="card-grid-3">
              {related.map(a => <ArticleCard key={a.id} article={a} />)}
            </div>
          </div>
        </section>
      )}

      {/* Sticky consultation CTA */}
      <a className="consult-cta" href="https://wa.me/5513978002785" target="_blank" rel="noopener">
        <Icon.whatsapp /> Consultar Dr. Angelo
      </a>

      <Footer />
    </div>
  );
}

// ---------- Hedcut-style portrait (stylized SVG) ----------
function HedcutAvatar() {
  return (
    <svg viewBox="0 0 96 96" width="96" height="96" aria-hidden="true">
      <defs>
        <pattern id="dots" x="0" y="0" width="3" height="3" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="0.7" fill="#14171C" />
        </pattern>
        <pattern id="dots2" x="0" y="0" width="4" height="4" patternUnits="userSpaceOnUse">
          <circle cx="1" cy="1" r="0.5" fill="#14171C" opacity="0.7" />
        </pattern>
        <clipPath id="head">
          <ellipse cx="48" cy="42" rx="22" ry="26" />
        </clipPath>
        <clipPath id="bust">
          <path d="M14 96 L14 80 Q 24 64 48 62 Q 72 64 82 80 L82 96 Z" />
        </clipPath>
      </defs>
      <rect width="96" height="96" fill="#F1ECE2" />
      {/* face */}
      <ellipse cx="48" cy="42" rx="22" ry="26" fill="#E0D7C2" />
      <g clipPath="url(#head)">
        <rect width="96" height="96" fill="url(#dots2)" opacity="0.4" />
        {/* shading */}
        <ellipse cx="58" cy="46" rx="14" ry="18" fill="url(#dots)" opacity="0.55" />
        <ellipse cx="48" cy="62" rx="20" ry="6" fill="url(#dots)" opacity="0.5" />
      </g>
      {/* hair */}
      <path d="M 28 28 Q 32 16 48 16 Q 64 16 68 28 Q 68 22 62 18 Q 50 12 38 18 Q 30 22 28 28 Z" fill="#14171C" />
      <path d="M 28 30 Q 32 22 36 26 Q 40 22 44 26 Q 48 22 52 26 Q 56 22 60 26 Q 64 22 68 30 L 68 24 Q 50 14 28 24 Z" fill="#14171C" opacity="0.8" />
      {/* beard */}
      <path d="M 32 50 Q 36 64 48 68 Q 60 64 64 50 Q 60 56 48 56 Q 36 56 32 50 Z" fill="url(#dots)" opacity="0.6" />
      {/* eyes */}
      <ellipse cx="41" cy="40" rx="1.2" ry="1.4" fill="#14171C" />
      <ellipse cx="55" cy="40" rx="1.2" ry="1.4" fill="#14171C" />
      {/* brows */}
      <path d="M 38 36 Q 41 34 44 36" stroke="#14171C" strokeWidth="1" fill="none" />
      <path d="M 52 36 Q 55 34 58 36" stroke="#14171C" strokeWidth="1" fill="none" />
      {/* nose */}
      <path d="M 48 42 L 47 50 L 49 50" stroke="#14171C" strokeWidth="0.6" fill="none" />
      {/* mouth */}
      <path d="M 44 55 Q 48 57 52 55" stroke="#14171C" strokeWidth="0.8" fill="none" />
      {/* suit */}
      <path d="M 14 96 L 14 80 Q 24 64 48 62 Q 72 64 82 80 L 82 96 Z" fill="#14171C" />
      <g clipPath="url(#bust)">
        <rect width="96" height="96" fill="url(#dots)" opacity="0.25" />
      </g>
      {/* shirt */}
      <path d="M 44 64 L 48 80 L 52 64 L 50 62 L 46 62 Z" fill="#F1ECE2" />
      {/* tie */}
      <path d="M 47 64 L 49 64 L 50 70 L 48 78 L 46 70 Z" fill="#A8821C" />
      {/* lapel rules */}
      <path d="M 32 96 L 44 64" stroke="#3A3D44" strokeWidth="0.5" fill="none" />
      <path d="M 64 96 L 52 64" stroke="#3A3D44" strokeWidth="0.5" fill="none" />
    </svg>
  );
}

Object.assign(window, { Article, HedcutAvatar });
