import { createFileRoute, Link } from "@tanstack/react-router";
import { AppShell, PageHeader } from "@/components/app-shell";
import { PublicShell } from "@/components/public-shell";
import { TombstoneCard } from "@/components/tombstone";
import { Button } from "@/components/ui/button";
import { getShellMeta } from "@/lib/server/api-core";
import { getCapstoneList } from "@/lib/server/api-hub";
import { useRoleStore } from "@/lib/role-store";

export const Route = createFileRoute("/market")({
  loader: async () => {
    const [meta, list] = await Promise.all([getShellMeta(), getCapstoneList()]);
    return { meta, list };
  },
  component: MarketPage,
});

function MarketPage() {
  const { meta, list } = Route.useLoaderData();
  const role = useRoleStore((s) => s.role);
  const canEdit = role === "staff" || role === "instructor";
  const cards = list.projects.filter((p) => p.public_card && p.publish_status === "published");
  const body = (
    <>
      <PageHeader
        kicker="Capstone · tombstone ads"
        title="Public market"
        description="These are the same public cards as the CFL homepage. View tombstone shows the ad. Super Admin and instructor can edit copy. Mark live only after the roster is full. Education — not a securities offering. CFL takes no equity."
        actions={
          role === "public" ? (
            <Button asChild variant="outline">
              <Link to="/public">Public site</Link>
            </Button>
          ) : (
            <Button asChild variant="outline">
              <Link to="/capstone">Open studio</Link>
            </Button>
          )
        }
      />
      <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
        {cards.map((p) => (
          <TombstoneCard key={p.id} project={p} canEdit={canEdit} />
        ))}
      </div>
    </>
  );

  if (role === "public") {
    return <PublicShell>{body}</PublicShell>;
  }

  return (
    <AppShell hold={meta.hold} unread={meta.unread} noticeCount={meta.noticeCount} inboxUnread={meta.inboxUnread}>
      {body}
    </AppShell>
  );
}
