/* page-reader.jsx — single draft view: markdown + optional interactive */

function PageReader({ type, slug }) {
  const { items, loading: indexLoading } = useContent();
  const { lang } = useLang();
  const item = findItem(items, type, slug);

  const [md, setMd] = React.useState({ loading: true, html: '', error: null });
  const [interactiveReady, setInteractiveReady] = React.useState(false);
  const [, forceRerender] = React.useReducer(n => n + 1, 0);
  const contentPath = item ? contentPathForLang(item, lang) : null;

  // Load markdown
  React.useEffect(() => {
    if (indexLoading) return;
    if (!item) { setMd({ loading: false, html: '', error: 'not in index' }); return; }
    setMd({ loading: true, html: '', error: null });
    authFetch(contentPath, { cache: 'no-cache' })
      .then(r => {
        if (r.status === 401) throw new Error('登录已过期，请重新登录。');
        if (r.status === 403) throw new Error('此邮箱未被允许访问内容。');
        if (!r.ok) throw new Error('content file missing');
        return r.text();
      })
      .then(text => {
        const stripped = stripFirstH1(text);
        const html = window.marked && window.marked.parse
          ? window.marked.parse(stripped)
          : escapeHtml(stripped);
        setMd({ loading: false, html, error: null });
      })
      .catch(e => setMd({ loading: false, html: '', error: e.message }));
  }, [type, slug, lang, indexLoading, contentPath]);

  // Load optional interactive
  React.useEffect(() => {
    if (indexLoading || !item || !item.interactive) {
      setInteractiveReady(false);
      return;
    }
    if (item.css) loadInteractiveCSS(item.css).catch(e => console.error('Failed to load interactive CSS:', e));
    const compName = interactiveComponentName(item.interactive);
    if (window[compName]) { setInteractiveReady(true); return; }
    setInteractiveReady(false);
    loadInteractive(item.interactive)
      .then(() => { setInteractiveReady(true); forceRerender(); })
      .catch(e => { console.error('Failed to load interactive:', e); });
  }, [type, slug, indexLoading, item && item.interactive]);

  if (indexLoading) {
    return <div className="notice"><p><T zh="加载中……" en="Loading..." /></p></div>;
  }
  if (!item) {
    return (
      <div className="notice">
        <p><T zh="找不到这篇作品。" en="Work not found." /></p>
        <p><a href="#/" className="underline"><T zh="返回书架" en="Back to library" /></a></p>
      </div>
    );
  }

  const title = lang === 'zh' ? item.title_zh : (item.title_en || item.title_zh);
  const enUnder = (lang === 'zh' && item.title_en) ? item.title_en : null;
  const wordCount = wordCountForLang(item, lang);

  let interactive = null;
  if (item.interactive && interactiveReady) {
    const Comp = window[interactiveComponentName(item.interactive)];
    if (Comp) {
      interactive = (
        <div className="interactive-mount">
          <Comp pov={item.pov} item={item} />
        </div>
      );
    }
  }

  return (
    <main className="reader">
      <a className="back-link" href="#/">← <T zh="书架" en="Library" /></a>
      <header>
        <h1>{title || item.slug}</h1>
        {enUnder && <p className="reader-en-title">{enUnder}</p>}
        <div className="reader-meta">
          <PovBadge pov={item.pov} />
          {item.publish_date && <span className="num">{item.publish_date}</span>}
          {wordCount > 0 && (
            <span className="num">{(wordCount / 1000).toFixed(1)}k</span>
          )}
        </div>
      </header>

      {interactive}

      {md.loading && <p className="reader-body"><T zh="加载中……" en="Loading..." /></p>}
      {md.error && <p className="reader-body"><T zh="加载失败：" en="Failed: " />{md.error}</p>}
      {!md.loading && !md.error && (
        <div className="reader-body" dangerouslySetInnerHTML={{ __html: md.html }} />
      )}
    </main>
  );
}

/* Strip the first "# Title" line so we don't render the title twice
   (we render the title from item.title_zh/en in the header). */
function stripFirstH1(text) {
  return text.replace(/^\s*#\s+[^\n]*\n+/, '');
}

function escapeHtml(s) {
  return s.replace(/[&<>"']/g, c => ({
    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
  }[c]));
}

Object.assign(window, { PageReader });
