// DocsSessionTranscript.jsx — v0.19.0 / roadmap item #30.
//
// Per-transcript view at `/docs/sessions/:nnnn/:filename`. Fetches the
// transcript body via the backend mediator and renders it through the
// shared MarkdownPreview.
//
// Empty-state contract:
//   404 → "This transcript isn't published yet" with a link back to
//         the parent session index
//   502 → "Couldn't reach the session-history repo" + retry button

import { useEffect, useState, useCallback } from 'react'
import { Link, useParams } from 'react-router-dom'
import MarkdownPreview from './MarkdownPreview.jsx'
import { getSessionTranscript } from '../api.js'
import { EVENTS, track } from '../lib/analytics'

export default function DocsSessionTranscript() {
  const { nnnn, filename } = useParams()
  const [body, setBody] = useState('')
  const [status, setStatus] = useState('loading') // loading | ok | notfound | error
  const [reloadTick, setReloadTick] = useState(0)

  useEffect(() => {
    track(EVENTS.DOC_VIEWED, { section: `sessions/${nnnn}/${filename}` })
  }, [nnnn, filename])

  useEffect(() => {
    let active = true
    setStatus('loading')
    getSessionTranscript(nnnn, filename)
      .then(text => {
        if (!active) return
        setBody(text || '')
        setStatus('ok')
      })
      .catch(e => {
        if (!active) return
        if (e.status === 404) {
          setStatus('notfound')
        } else {
          setStatus('error')
        }
      })
    return () => { active = false }
  }, [nnnn, filename, reloadTick])

  const retry = useCallback(() => setReloadTick(t => t + 1), [])

  return (
    <article className="docs-article">
      <div className="docs-breadcrumbs">
        <Link
          to={`/docs/sessions/${nnnn}`}
          aria-label={`Back to session ${nnnn} index`}
          data-amp-track-name="Docs Transcript Back To Index"
        >
          ← Session {nnnn}
        </Link>
      </div>
      {status === 'loading' && <p className="muted">Loading…</p>}
      {status === 'notfound' && (
        <div className="docs-empty">
          <p>This transcript isn't published yet.</p>
          <p>
            <Link
              to={`/docs/sessions/${nnnn}`}
              aria-label={`Back to session ${nnnn}`}
              data-amp-track-name="Docs Transcript Back To Session"
            >
              ← Back to session {nnnn}
            </Link>
          </p>
        </div>
      )}
      {status === 'error' && (
        <div className="docs-error" role="alert">
          <p>Couldn't reach the session-history repo.</p>
          <button
            type="button"
            onClick={retry}
            aria-label="Retry"
            data-amp-track-name="Docs Transcript Retry"
          >
            Try again
          </button>
        </div>
      )}
      {status === 'ok' && (
        <div className="philosophy-body">
          <MarkdownPreview content={body} />
        </div>
      )}
    </article>
  )
}
