// DocsPage.jsx — render a repo .md file in the site shell. Used for setup guides.
// Loads via fetch, parses with marked (CDN), sanitizes with DOMPurify before injection.

const DocsPage = () => {
  useReveal();
  const route = useRoute();
  const path = route.startsWith('docs/') ? route.slice(5) : '';
  const [html, setHtml] = useState(null);
  const [err, setErr] = useState(null);

  useEffect(() => {
    if (!path) { setErr('No doc specified.'); return; }
    setHtml(null); setErr(null);
    // Only allow bare filenames (no traversal)
    if (!/^[A-Za-z0-9_.\-\/]+\.md$/i.test(path) || path.includes('..')) {
      setErr('Invalid doc path.'); return;
    }
    const base = window.DOCS_BASE || '/docs/';
    fetch(base + path, { headers: { Accept: 'text/plain' } })
      .then(r => r.ok ? r.text() : Promise.reject(new Error(`${r.status} ${r.statusText}`)))
      .then(md => {
        if (!window.marked || !window.DOMPurify) { setErr('Markdown renderer not loaded.'); return; }
        window.marked.setOptions({ breaks: false, gfm: true });
        const raw = window.marked.parse(md);
        const clean = window.DOMPurify.sanitize(raw);
        setHtml(clean);
      })
      .catch(e => setErr(String(e.message || e)));
  }, [path]);

  return (
    <>
      <section className="section" style={{ paddingTop: 48 }}>
        <div className="wrap" style={{ maxWidth: 860 }}>
          <a href="#/" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', textDecoration: 'none', letterSpacing: '0.1em' }}>
            ← HOME
          </a>
          {err && (
            <div style={{ marginTop: 20, padding: 20, border: '2px solid var(--wbbq-blood)', background: 'var(--wbbq-ink)' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 13, letterSpacing: '0.14em', color: 'var(--wbbq-blood)', textTransform: 'uppercase', marginBottom: 8 }}>Doc Error</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg2)' }}>{err}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)', marginTop: 8 }}>Looking for: {path || '(none)'}</div>
            </div>
          )}
          {!err && !html && (
            <div style={{ padding: 48, textAlign: 'center', color: 'var(--fg3)', fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.12em' }}>
              LOADING {path.toUpperCase()}…
            </div>
          )}
          {html && (
            <article className="markdown-doc" style={{ marginTop: 28, color: 'var(--fg1)' }} dangerouslySetInnerHTML={{ __html: html }} />
          )}
          <div style={{ marginTop: 64, paddingTop: 20, borderTop: '1px dashed var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 12 }}>
            <a href="#/" style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--fg3)', textDecoration: 'none', letterSpacing: '0.1em' }}>← HOME</a>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--fg3)' }}>{path}</div>
          </div>
        </div>
      </section>
    </>
  );
};

window.DocsPage = DocsPage;
