// `/docs` — the user-facing guide.
//
// Sibling of Philosophy.jsx: same chrome, same data path, different
// source file. Renders DOCS.md verbatim with light chrome around it.
// Reachable anonymously, same as `/philosophy`, so a visitor can read
// the guide before deciding to sign in.

import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import MarkdownPreview from './MarkdownPreview.jsx'
import { getDocs } from '../api.js'

export default function Docs({ authenticated }) {
  const [body, setBody] = useState('')
  const [error, setError] = useState(null)
  const [loading, setLoading] = useState(true)
  const navigate = useNavigate()

  useEffect(() => {
    let active = true
    getDocs()
      .then(r => { if (active) setBody(r.body || '') })
      .catch(e => { if (active) setError(e.message || String(e)) })
      .finally(() => { if (active) setLoading(false) })
    return () => { active = false }
  }, [])

  return (
    <div className="philosophy-page">
      <header className="philosophy-header">
        <button
          className="philosophy-back"
          onClick={() => (history.length > 1 ? navigate(-1) : navigate('/'))}
        >
          ← Back
        </button>
        <span className="philosophy-title">User guide</span>
        {!authenticated && (
          <Link className="philosophy-signin" to="/">Home</Link>
        )}
      </header>
      <article className="philosophy-body">
        {loading && <p className="muted">Loading…</p>}
        {error && <p className="error">Could not load the guide: {error}</p>}
        {!loading && !error && (
          <MarkdownPreview content={body} />
        )}
      </article>
    </div>
  )
}
