// src/pages/HistoryArticlePage.jsx
function setHistoryMeta(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 HistoryArticlePage({ item }) {
  const { lang, t, navigate, stories, historyArticleSlug, storiesLoading } = useApp();
  const [copied, setCopied] = React.useState(false);

  const story = item
    || (historyArticleSlug ? findStoryBySlug(stories, historyArticleSlug) : null);

  const title = story
    ? (typeof story.title === 'object' ? story.title[lang] : story.title)
    : '';
  const date = story
    ? (typeof story.date === 'object' ? story.date[lang] : story.date)
    : '';
  const body = story
    ? (typeof story.body === 'object' ? story.body[lang] : (story.body || ''))
    : '';
  const preview = story
    ? (typeof story.text === 'object' ? story.text[lang] : story.text)
    : '';

  const sharePath = story
    ? routeToPath('history-article', getStorySlug(story, lang))
    : '';
  const shareUrl = sharePath ? getShareUrl(sharePath) : '';

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

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

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

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

  if (!story) {
    if (storiesLoading) {
      return (
        <div className="pt-24 pb-16 max-w-[860px] mx-auto px-4 sm:px-6">
          <p style={{ color: 'var(--text-muted)' }}>{t.historyPage.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">
        {story.img ? (
          <div className="article-cover">
            <img src={story.img} alt={title} />
          </div>
        ) : (
          <div
            className="article-cover flex items-center justify-center text-center px-6"
            style={{ color: 'var(--text-muted)', fontSize: 14, lineHeight: 1.5 }}
          >
            {story.imgPlaceholder?.[lang] || story.imgPlaceholder?.ru}
          </div>
        )}

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

          <h1 className="text-[48px] font-bold mb-8 leading-tight max-w-[860px]" 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.storyArticle.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.storyArticle.copied : t.storyArticle.copyLink}
                </button>
              </div>
            </div>

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