// src/pages/ArticlePage.jsx
function setMeta(name, content, attr = 'name') {
  if (!content) return;
  let el = document.querySelector(`meta[${attr}="${name}"]`);
  if (!el) {
    el = document.createElement('meta');
    el.setAttribute(attr, name);
    document.head.appendChild(el);
  }
  el.setAttribute('content', content);
}

function ArticlePage({ item }) {
  const { lang, t, navigate, news, articleSlug, newsLoading } = useApp();
  const [copied, setCopied] = React.useState(false);

  const article = item
    || (articleSlug ? findArticleBySlug(news, articleSlug) : null);

  const title = article
    ? (typeof article.title === 'object' ? article.title[lang] : article.title)
    : '';
  const date = article
    ? (typeof article.date === 'object' ? article.date[lang] : article.date)
    : '';
  const body = article
    ? (typeof article.body === 'object' ? article.body[lang] : (article.body || ''))
    : '';
  const excerpt = article
    ? (typeof article.excerpt === 'object' ? article.excerpt[lang] : article.excerpt)
    : '';

  const sharePath = article
    ? routeToPath('article', getArticleSlug(article, lang))
    : '';
  const shareUrl = sharePath ? getShareUrl(sharePath) : '';

  React.useEffect(() => {
    if (!article) return undefined;

    document.title = `${title} — StopCBDC`;
    setMeta('description', excerpt);
    setMeta('og:title', title, 'property');
    setMeta('og:description', excerpt, 'property');
    setMeta('og:image', ogShareImage(article.img), 'property');
    setMeta('og:url', shareUrl, 'property');
    setMeta('og:type', 'article', 'property');
    setMeta('og:site_name', 'StopCBDC', 'property');
    setMeta('twitter:card', 'summary_large_image');
    setMeta('twitter:title', title);
    setMeta('twitter:description', excerpt);
    setMeta('twitter:image', ogShareImage(article.img));

    return () => {
      document.title = 'StopCBDC';
      setMeta('description', 'Остановим тотальный финансовый контроль!');
    };
  }, [article, title, excerpt, shareUrl]);

  function copyLink() {
    if (!shareUrl) return;
    navigator.clipboard.writeText(shareUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }

  if (!article) {
    if (newsLoading) {
      return (
        <div className="pt-24 pb-16 max-w-[860px] mx-auto px-4 sm:px-6">
          <p style={{ color: 'var(--text-muted)' }}>{t.newsPage.loading}</p>
        </div>
      );
    }
    return null;
  }

  const shareLinks = [
    {
      label: 'Telegram',
      href: `https://t.me/share/url?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(title)}`,
    },
    {
      label: 'X',
      href: `https://twitter.com/intent/tweet?url=${encodeURIComponent(shareUrl)}&text=${encodeURIComponent(title)}`,
    },
  ];

  return (
    <div className="pt-[106px]">
      <div className="max-w-[1400px] mx-auto px-4 sm:px-6">
        <div className="article-cover">
          <img src={article.img} alt={title} />
        </div>

        <div className="py-12">
        <div className="max-w-[860px] flex items-center gap-3 mb-4 flex-wrap">
          <Tag type={article.tag} />
          <span className="text-sm" style={{ color: 'var(--text-muted)' }}>{date}</span>
        </div>

        <h1 className="text-[48px] font-bold mb-8 leading-tight" style={{ color: 'var(--text)' }}>
          {title}
        </h1>

        <div className="max-w-[860px]">
        <div
          className="article-body text-[15px] leading-relaxed"
          style={{ color: 'var(--text-muted)' }}
          dangerouslySetInnerHTML={{ __html: body }}
        />

        <div className="mt-10 pt-8" style={{ borderTop: '1px solid var(--border-card)' }}>
          <p className="text-sm font-medium mb-3" style={{ color: 'var(--text)' }}>
            {t.article.share}
          </p>
          <div className="flex flex-wrap gap-2">
            {shareLinks.map((link) => (
              <a
                key={link.label}
                href={link.href}
                target="_blank"
                rel="noopener noreferrer"
                className="btn-outline text-sm"
              >
                {link.label}
              </a>
            ))}
            <button type="button" className="btn-outline text-sm" onClick={copyLink}>
              {copied ? t.article.copied : t.article.copyLink}
            </button>
          </div>
        </div>

        <div className="mt-8">
          <button className="btn-outline" onClick={() => navigate('news')}>
            {t.article.back}
          </button>
        </div>
        </div>
        </div>
      </div>
    </div>
  );
}
