// The portal shell — and the AUTH GATE. This layout wraps every page in the
// silent `(portal)` group, and its `loader` runs server-side BEFORE the pages
// render: it asks the api's `session.me` and throws RedirectError to /login for
// anyone not signed in. The pages under here are `renderMode: 'ssr'` precisely so
// this runs per request.
import type { ReactNode } from 'react'
import { RedirectError, useLoaderData, useLocation, type LoaderFn } from '@voltro/web'
import { T, useLocale, useT } from '@voltro/i18n'
import { LocaleSwitcher } from '@voltro/ui-shadcn'
import { APP_NAME } from '../../config'
import type { Identity } from '../../lib/api'

const LOCALES = [
  { code: 'en', label: 'English' },
  { code: 'de', label: 'Deutsch' },
]

interface PortalData {
  readonly tenantId: string | null
}

export const loader: LoaderFn<PortalData> = async ({ query }) => {
  if (query) {
    const me = await query<Identity>('session.me', {})
    if (me.type !== 'user') {
      throw new RedirectError('/login?from=/')
    }
    return { tenantId: me.tenantId }
  }
  return { tenantId: null }
}

export default function PortalLayout({ children }: { readonly children: ReactNode }): ReactNode {
  useLoaderData<PortalData>()
  const pathname = useLocation()
  const locale = useLocale()
  const langLabel = useT('lang.label')
  const navItem = (href: string, label: ReactNode): ReactNode => (
    <a href={href} aria-current={pathname === href ? 'page' : undefined}>{label}</a>
  )

  return (
    <div className="dash">
      <aside>
        <div className="brand">{APP_NAME}</div>
        <nav>
          {navItem('/', <T id="nav.overview" />)}
          {navItem('/billing', <T id="nav.billing" />)}
          {navItem('/invoices', <T id="nav.invoices" />)}
          {navItem('/api-keys', <T id="nav.apiKeys" />)}
          {navItem('/profile', <T id="nav.profile" />)}
        </nav>
      </aside>
      <main>
        <div className="topbar">
          <span className="spacer" />
          <LocaleSwitcher locales={LOCALES} current={locale} ariaLabel={langLabel} />
        </div>
        {children}
      </main>
    </div>
  )
}
