// Article reader page with progress bar, TOC, margin notes
const { useState: useStateA, useEffect: useEffectA, useMemo: useMemoA, useRef: useRefA } = React;

// Inline markdown: **bold** and _italic_
function renderText(str) {
  if (!str) return null;
  const html = str
    .replace(/\*\*(.*?)\*\*/gs, '<strong>$1</strong>')
    .replace(/_(.*?)_/gs, '<em>$1</em>');
  return React.createElement('span', { dangerouslySetInnerHTML: { __html: html } });
}

function buildTOC(body) {
  return body.filter((b) => b.type === "h2").map((b, i) => ({
    id: `h-${i}`,
    text: b.text,
  }));
}

function ArticlePage({ post, onBack, variant = "editorial" }) {
  const [progress, setProgress] = useStateA(0);
  const [activeHead, setActiveHead] = useStateA(0);
  const [showTop, setShowTop] = useStateA(false);
  const articleRef = useRefA(null);

  const toc = useMemoA(() => buildTOC(post.body), [post]);

  useEffectA(() => {
    const onScroll = () => {
      const el = articleRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const total = el.scrollHeight - window.innerHeight;
      const scrolled = Math.max(0, -rect.top);
      const p = Math.min(1, total > 0 ? scrolled / total : 0);
      setProgress(p);
      setShowTop(scrolled > 400);

      const heads = [...el.querySelectorAll("h2")];
      let idx = 0;
      heads.forEach((h, i) => {
        if (h.getBoundingClientRect().top < 120) idx = i;
      });
      setActiveHead(idx);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [post]);

  let h2i = 0;
  const rendered = post.body.map((b, i) => {
    if (b.type === "p") return <p key={i}>{renderText(b.text)}</p>;
    if (b.type === "h2") {
      const id = `h-${h2i++}`;
      return <h2 key={i} id={id}>{b.text}</h2>;
    }
    if (b.type === "pull") {
      return <blockquote key={i} className="pull">{renderText(b.text)}</blockquote>;
    }
    if (b.type === "list") {
      return (
        <ol key={i} className="ord-list">
          {b.items.map((it, j) => <li key={j}>{renderText(it)}</li>)}
        </ol>
      );
    }
    if (b.type === "code") {
      return (
        <div key={i} className="code-block">
          <code>{b.text}</code>
        </div>
      );
    }
    if (b.type === "note") {
      return (
        <aside key={i} className="margin-note">
          <span className="note-label">边注</span>
          {renderText(b.text)}
        </aside>
      );
    }
    return null;
  });

  return (
    <div className={`article-page article-page--${variant}`}>
      <div className="progress-bar" style={{ transform: `scaleX(${progress})` }} />

      <header className="art-mast">
        <a className="art-back" onClick={(e) => { e.preventDefault(); onBack(); }} href="#">
          <span aria-hidden>←</span> brady
        </a>
        <nav className="art-nav">
          <a href="#" className="nav-link">写作</a>
          <a href="#" className="nav-link">关于</a>
          <a href="#" className="nav-link">↗ X</a>
        </nav>
      </header>

      <article ref={articleRef} className="article">
        <div className="art-meta">
          <span>{post.category}</span>
          <span className="dot">·</span>
          <span>{fmtDate(post.date)}</span>
          <span className="dot">·</span>
          <span>{post.readTime}</span>
        </div>
        <h1 className="art-title">{post.title}</h1>
        {post.subtitle ? <p className="art-sub">{post.subtitle}</p> : null}
        <div className="art-rule" />

        <div className="art-body">
          {rendered}
        </div>

        <div className="art-end">
          <div className="end-rule" />
          <div className="end-note">
            写于 {fmtDate(post.date)}。<br/>
            如果你有想法想交换，欢迎来 <a href="#">X</a> 上找我。
          </div>
        </div>
      </article>

      {toc.length > 0 ? (
        <aside className="toc">
          <div className="toc-label">本文目录</div>
          <ul>
            {toc.map((t, i) => (
              <li key={t.id} className={i === activeHead ? "active" : ""}>
                <a href={`#${t.id}`} onClick={(e) => {
                  e.preventDefault();
                  document.getElementById(t.id)?.scrollIntoView({ behavior: "smooth", block: "start" });
                }}>{t.text}</a>
              </li>
            ))}
          </ul>
        </aside>
      ) : null}

      {showTop ? (
        <button className="back-top" onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })} aria-label="回到顶部">
          ↑
        </button>
      ) : null}

      <nav className="art-nav-foot">
        <a href="#" onClick={(e) => { e.preventDefault(); onBack(); }}>← 回到首页</a>
      </nav>
    </div>
  );
}

window.ArticlePage = ArticlePage;
