import { useMemo } from 'react'
import { Link, useParams } from 'react-router-dom'
import DOMPurify from 'dompurify'
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: sanitize (defense in depth — the server also
// sanitizes on save), assign ids to <h2> headings and collect a TOC, and mark
// internal links to pages that don't exist as "red links".
function buildArticle(body, missing) {
  if (!body) return { html: '', toc: [] }
  if (typeof window === 'undefined' || !window.DOMParser) return { html: '', toc: [] }
  const safe = DOMPurify.sanitize(body)
  const doc = new DOMParser().parseFromString(safe, '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 })
  })
  doc.querySelectorAll('a[href^="/wiki/"]').forEach((a) => {
    const target = a.getAttribute('href').replace(/^\/wiki\//, '').replace(/[#?].*$/, '')
    a.removeAttribute('target') // internal links stay in-app
    if (missing.has(target)) {
      a.classList.add('wiki-red-link')
      a.setAttribute('title', 'This page does not exist yet')
    }
  })
  return { html: doc.body.innerHTML, toc }
}

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

  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>
                {page.category_title && (
                  <>
                    <span>/</span>
                    <Link
                      to={`/wiki?category=${page.category_slug}`}
                      style={{ color: 'var(--accent)', textDecoration: 'none' }}
                    >
                      {page.category_title}
                    </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>
              {page.tags && page.tags.length > 0 && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 14 }}>
                  {page.tags.map((t) => (
                    <Link key={t.slug} to={`/wiki?tag=${t.slug}`} className="wiki-tag">
                      #{t.label}
                    </Link>
                  ))}
                </div>
              )}
              <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>
              )}

              {page.backlinks && page.backlinks.length > 0 && (
                <section
                  style={{ marginTop: 40, borderTop: '1px solid var(--line)', paddingTop: 22 }}
                >
                  <p
                    className="sans"
                    style={{ margin: '0 0 12px', color: 'var(--accent)', fontSize: '0.66rem', fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase' }}
                  >
                    Linked from
                  </p>
                  <ul style={{ margin: 0, paddingLeft: 18, fontFamily: 'var(--sans)', fontSize: '0.92rem' }}>
                    {page.backlinks.map((b) => (
                      <li key={b.slug} style={{ marginBottom: 6 }}>
                        <Link to={`/wiki/${b.slug}`} style={{ color: 'var(--accent)', textDecoration: 'none' }}>
                          {b.title}
                        </Link>
                      </li>
                    ))}
                  </ul>
                </section>
              )}

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