// madarX OS — Marketplace foundation (Phase 1).
//
// Single operator surface for discovering and installing agent capabilities:
// tools (40 API adapters), skills (4 instruction packs), and bundles (1 curated
// pack). Agent personas are deferred to a separate Agent Marketplace product.
//
// The page is server-rendered. Tab / search / category filtering happens
// client-side inside <MarketplaceShell> so the SSR'd list contains every kind
// at once — the test harness in tests/admin-console-pages.test.js asserts on
// markers (approval mode, toggle, secret values, skill, bundle) which are
// only present when all kinds are emitted.
//
// Toggle availability without ever exposing secret values is the same
// invariant the legacy /tools page held — the marketplace inherits it.

import { AdminShell, EmptyState } from '@/app/components/admin/admin-page.jsx';
import {
  listMarketplaceItems,
  getKindCounts,
  listCategoriesForKind,
} from '@/lib/marketplace.js';
import MarketplaceShell from './marketplace-shell.jsx';
import { toggleInstallAction, recordImportAttemptAction } from './actions.js';

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

const KIND_OPTIONS = new Set(['all', 'tool', 'skill', 'bundle', 'agent', 'connection', 'workflow']);

function resolveInitialKind(searchParams) {
  const raw = searchParams?.kind;
  if (typeof raw !== 'string') return 'all';
  return KIND_OPTIONS.has(raw) ? raw : 'all';
}

export default async function MarketplacePage({ searchParams }) {
  const sp = (await Promise.resolve(searchParams)) || {};
  const initialKind = resolveInitialKind(sp);

  const items = listMarketplaceItems();
  const counts = getKindCounts();
  const categoriesByKind = {
    tool: listCategoriesForKind('tool'),
    skill: listCategoriesForKind('skill'),
    bundle: listCategoriesForKind('bundle'),
    agent: listCategoriesForKind('agent'),
    connection: listCategoriesForKind('connection'),
    workflow: listCategoriesForKind('workflow'),
  };

  return (
    <AdminShell
      kicker="Marketplace · madarX OS"
      title="Marketplace"
      description="Discover and install the tools, skills, and bundles your agents need. Toggle availability without ever exposing secret values. Risk tier and approval mode surface on every row so destructive actions stay human-gated."
    >
      {items.length ? (
        <MarketplaceShell
          items={items}
          counts={counts}
          categoriesByKind={categoriesByKind}
          toggleAction={toggleInstallAction}
          importAction={recordImportAttemptAction}
          initialKind={initialKind}
        />
      ) : (
        <EmptyState title="No marketplace items registered">
          Tool, skill, and bundle definitions will appear after registry initialization.
        </EmptyState>
      )}
    </AdminShell>
  );
}
