// Admin overview — URL `/admin`. `renderMode: 'ssr'` so the parent layout's
// auth gate runs per request. Renders one card per discovered entity, each
// linking to its CRUD page. The whole list comes from the api's capability map
// — there's no hard-coded entity list.
import type { ReactNode } from 'react'
import type { PageMeta } from '@voltro/web'
import { useCapabilityManifest, deriveEntityAdmins } from '@voltro/client'
import { T } from '@voltro/i18n'
import { getCatalog } from '../../locales'

export const renderMode = 'ssr' as const

export const meta = ({ locale }: { readonly locale: string }): PageMeta => ({
  title: getCatalog(locale)['meta.overview.title'],
})

export default function AdminOverview(): ReactNode {
  const { manifest, loading, error } = useCapabilityManifest('app')
  const entities = manifest ? deriveEntityAdmins(manifest) : []

  return (
    <section>
      <h1><T id="overview.heading" /></h1>
      <p className="muted">
        <T id="overview.intro" values={{ code: (c: ReactNode) => <code>{c}</code> }} />
      </p>

      {error ? (
        <p className="banner" style={{ marginTop: '1rem' }}>
          <T id="overview.error" />
        </p>
      ) : null}

      {loading && entities.length === 0 ? (
        <div className="cards" style={{ marginTop: '1.25rem' }} aria-hidden="true">
          <div className="skeleton" /><div className="skeleton" /><div className="skeleton" />
        </div>
      ) : (
        <div className="cards" style={{ marginTop: '1.25rem' }}>
          {entities.map((e) => {
            const ops = [
              e.list.tag && 'list',
              e.create.tag && 'create',
              e.update.tag && 'edit',
              e.delete.tag && 'delete',
            ].filter(Boolean)
            return (
              <a className="card" key={e.table} href={`/admin/${e.table}`}>
                <div className="value">{e.table}</div>
                <div className="label">
                  {/* `columns` already excludes `.serverOnly()` — the count is
                      what an admin can actually show, not what the table has. */}
                  <T id="overview.columns" values={{ count: e.columns.length }} />
                  {e.reactive ? <T id="overview.reactiveSuffix" /> : null}
                </div>
                <div className="meta">{ops.length > 0 ? ops.join(' · ') : <T id="overview.readonly" />}</div>
                {e.serverOnlyColumns.length > 0 ? (
                  <div className="meta"><T id="overview.serverOnly" values={{ count: e.serverOnlyColumns.length }} /></div>
                ) : null}
              </a>
            )
          })}
          {entities.length === 0 && !loading ? (
            <p className="muted"><T id="overview.empty" /></p>
          ) : null}
        </div>
      )}
    </section>
  )
}
