import { notFound } from 'next/navigation';
import { AdminShell } from '@/app/components/admin/admin-page.jsx';
import { getArticle } from '@/lib/help/articles.js';
import { HELP_ARTICLE_META, SETTING_ACTIONS, helpCategories } from '@/lib/help/registry.js';
import HelpMarkdown from '../help-markdown.jsx';
import HelpSetButton from '../help-set-button.jsx';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export function generateStaticParams() {
  return HELP_ARTICLE_META.map((a) => ({ slug: a.slug }));
}

export default async function HelpArticlePage({ params }) {
  const { slug } = await params;
  const article = getArticle(slug);
  if (!article) notFound();

  // Settings this article documents → render "Set this now" affordances.
  const actions = SETTING_ACTIONS.filter((a) => a.docSlug === slug);
  // Related articles (resolve metadata).
  const related = (article.related || [])
    .map((rel) => HELP_ARTICLE_META.find((a) => a.slug === rel))
    .filter(Boolean);

  const categories = helpCategories();

  return (
    <AdminShell
      kicker="Help"
      title={article.title}
      description={article.summary}
      hideProjectSwitcher
    >
      <div className="help-article-layout">
        <aside className="help-article-rail" aria-label="Help categories">
          <a className="help-article-back" href="/help">← Help Center</a>
          {categories.map((cat) => (
            <div key={cat} className="help-article-rail-group">
              <span className="help-article-rail-label">{cat}</span>
              <ul>
                {HELP_ARTICLE_META.filter((a) => a.category === cat).map((a) => (
                  <li key={a.slug}>
                    <a href={`/help/${a.slug}`} className={a.slug === slug ? 'is-active' : ''}>{a.title}</a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
        </aside>

        <article className="help-article">
          {actions.length ? (
            <div className="help-article-actions">
              {actions.map((a) => (
                <HelpSetButton key={a.id} actionId={a.id} label={a.title} />
              ))}
            </div>
          ) : null}

          <div className="help-article-prose">
            <HelpMarkdown>{article.body}</HelpMarkdown>
          </div>

          {related.length ? (
            <footer className="help-article-related">
              <span className="help-article-related-label">Related</span>
              <div className="help-article-related-grid">
                {related.map((r) => (
                  <a key={r.slug} className="help-article-related-card" href={`/help/${r.slug}`}>
                    <b>{r.title}</b>
                    <p>{r.summary}</p>
                  </a>
                ))}
              </div>
            </footer>
          ) : null}
        </article>
      </div>
    </AdminShell>
  );
}
