// §14.2 — the `/philosophy` route.
//
// Renders PHILOSOPHY.md verbatim with light app chrome around it.
// Reachable by anonymous visitors (linked from the §14.1 landing) and
// by authenticated viewers (linked from the persistent §14.3 About
// header). The chrome here is small by design: a "Back" affordance
// that goes wherever the viewer came from, and a render of the
// markdown body. The §14.4 commitment ("not pushed at returning users
// via banners or modals") is the guardrail — this route serves the
// document, nothing else.
//
// The route is also the natural read surface for anonymous reachers:
// without a sign-in they cannot navigate the catalog, but they can
// read the philosophy that animates the work.

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

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

  useEffect(() => {
    let active = true
    getPhilosophy()
      .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">Why this exists</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 philosophy: {error}</p>}
        {!loading && !error && (
          <MarkdownPreview content={body} />
        )}
      </article>
    </div>
  )
}
