import { notFound } from "next/navigation";
import { PanelsList } from "@/components/features/panels";
import { Card, EmptyState, PageHeader } from "@/components/ui";
import { canAnywhere } from "@/lib/authz/context";
import { AuthError } from "@/lib/authz/errors";
import { requireDashboard } from "@/lib/authz/guard";
import { getActiveSiteId, listAccessibleSites } from "@/lib/data/sites";
import { listPanels } from "@/lib/services/panels";

export async function PanelsScreen() {
  const ctx = await requireDashboard("admin");
  if (!canAnywhere(ctx, "content.manage")) notFound();
  const sites = await listAccessibleSites(ctx);
  const siteId = await getActiveSiteId(sites);
  if (!siteId) {
    return (
      <>
        <PageHeader title="Panels" />
        <Card><EmptyState title="Choose a website" description="Open a website first (Edit in your website list, or the top-bar dropdown) to manage its panels." /></Card>
      </>
    );
  }
  let data;
  try {
    data = await listPanels(siteId);
  } catch (e) {
    if (e instanceof AuthError) notFound();
    throw e;
  }
  return (
    <div className="ed -m-1 rounded-3xl bg-[var(--ed-bg)] p-4 sm:p-6">
      <PanelsList key={data.site.id} siteId={data.site.id} panels={data.panels} locations={data.locations} canManage canAddDelete canEditLocations={ctx.isSuperAdmin} />
    </div>
  );
}
