import { useMemo } from 'react'
import { Link, useParams } from 'react-router-dom'
import PublicLayout from '../../components/PublicLayout.jsx'
import { Loading, ErrorState } from '../../components/PageState.jsx'
import { useAsync } from '../../lib/useAsync.js'
import { longDate } from '../../lib/format.js'
import { api } from '../../api/client.js'

function slugify(text) {
  return text
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '')
}

// Parse the stored body HTML: assign ids to <h2> headings and collect a TOC.
function buildArticle(body) {
  if (!body) return { html: '', toc: [] }
  if (typeof window === 'undefined' || !window.DOMParser) return { html: body, toc: [] }
  const doc = new DOMParser().parseFromString(body, 'text/html')
  const toc = []
  doc.querySelectorAll('h2').forEach((h, i) => {
    const id = slugify(h.textContent || '') || `section-${i}`
    h.id = id
    toc.push({ id, label: h.textContent })
  })
  return { html: doc.body.innerHTML, toc }
}

export default function WikiArticle() {
  const { slug } = useParams()
  const { loading, error, data: page } = useAsync(() => api.wikiPage(slug), [slug])
  const { html, toc } = useMemo(() => buildArticle(page?.body), [page])

  return (
    <PublicLayout section="wiki">
      <div className="shell page-body" style={{ paddingTop: 40 }}>
        {loading && <Loading />}
        {error && (
          <ErrorState message={error.status === 404 ? 'That wiki page could not be found.' : 'Could not load this page.'} />
        )}
        {page && (
          <div className={toc.length ? 'wiki-grid' : ''}>
            {toc.length > 0 && (
              <aside
                style={{
                  position: 'sticky',
                  top: 90,
                  border: '1px solid var(--line)',
                  borderRadius: 10,
                  padding: 20,
                  background: 'rgba(11,22,48,0.32)',
                }}
              >
                <p
                  className="sans"
                  style={{ margin: '0 0 12px', color: 'var(--accent)', fontSize: '0.66rem', fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase' }}
                >
                  On this page
                </p>
                <nav style={{ display: 'flex', flexDirection: 'column', gap: 9, fontFamily: 'var(--sans)', fontSize: '0.9rem' }}>
                  {toc.map((t) => (
                    <a
                      key={t.id}
                      href={`#${t.id}`}
                      style={{ color: 'var(--text)', textDecoration: 'none', borderLeft: '2px solid var(--line)', paddingLeft: 12 }}
                    >
                      {t.label}
                    </a>
                  ))}
                </nav>
              </aside>
            )}

            <article style={!toc.length ? { maxWidth: 760, margin: '0 auto' } : undefined}>
              <p className="sans" style={{ margin: '0 0 12px', display: 'flex', gap: 8, color: 'var(--dim)', fontSize: '0.82rem' }}>
                <Link to="/wiki" style={{ color: 'var(--accent)', textDecoration: 'none' }}>
                  Wiki
                </Link>
                <span>/</span>
                <span>{page.title}</span>
              </p>
              <h1 className="display" style={{ margin: 0, fontSize: 'clamp(2.2rem,5vw,3.2rem)', lineHeight: 1.05, color: 'var(--head)' }}>
                {page.title}
              </h1>
              <p className="sans" style={{ margin: '18px 0 0', color: 'var(--dim)', fontSize: '0.78rem', letterSpacing: '0.04em' }}>
                Last updated {longDate(page.updated_at) || '—'}
              </p>
              <div style={{ height: 1, background: 'var(--line)', margin: '30px 0' }} />
              {html ? (
                <div className="prose" dangerouslySetInnerHTML={{ __html: html }} />
              ) : (
                <p className="muted">This page has no content yet.</p>
              )}

              <nav style={{ display: 'flex', justifyContent: 'flex-start', marginTop: 40 }}>
                <Link to="/wiki" className="pill">
                  ← All wiki pages
                </Link>
              </nav>
            </article>
          </div>
        )}
      </div>
    </PublicLayout>
  )
}
