import { useMemo } from 'react'
import { Link } from 'react-router-dom'
import { viewRouteMeta } from '../lib/viewRouteMeta.generated'
import { registryKeyToAppPath } from '../lib/viewRouteLookup'

export function ViewRouteSitemapPage() {
  const grouped = useMemo(() => {
    const groups = new Map<string, { key: string; title: string }[]>()
    for (const key of Object.keys(viewRouteMeta).sort()) {
      const top = key.includes('/') ? key.slice(0, key.indexOf('/')) : key
      const title = viewRouteMeta[key]?.title ?? key
      const list = groups.get(top) ?? []
      list.push({ key, title })
      groups.set(top, list)
    }
    return [...groups.entries()].sort(([a], [b]) => a.localeCompare(b))
  }, [])

  return (
    <div>
      <nav aria-label="breadcrumb">
        <ol className="breadcrumb">
          <li className="breadcrumb-item">
            <Link to="/app/home">Home</Link>
          </li>
          <li className="breadcrumb-item active" aria-current="page">
            View routes
          </li>
        </ol>
      </nav>

      <p className="text-muted small mb-4">
        Generated from discovered PHP view sources. Each link opens the mapped route under{' '}
        <code>/app/…</code>; unimplemented screens use the section placeholder with the matching
        source view path. Regenerate: <code>npm run gen:view-meta</code>.
      </p>

      <div className="row g-4">
        {grouped.map(([section, items]) => (
          <div key={section} className="col-12 col-md-6 col-xl-4">
            <div className="border rounded bg-white shadow-sm">
              <div className="px-3 py-2 border-bottom small fw-semibold text-muted">{section}</div>
              <ul className="list-unstyled mb-0 px-2 py-2" style={{ maxHeight: 280, overflow: 'auto' }}>
                {items.map(({ key, title }) => (
                  <li key={key} className="small py-1">
                    <Link to={registryKeyToAppPath(key)}>{title}</Link>
                    <div className="text-muted" style={{ fontSize: '0.75rem' }}>
                      <code>{key.replace(/\//g, ' / ')}</code>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
