import config from "@payload-config"; import { getPayload } from "payload"; import { notFound } from "next/navigation"; import Link from "next/link"; import { headers as nextHeaders } from "next/headers"; import type { BankAccount, Campaign, Faction, Media, Mission } from "@/payload-types"; import { RichTextView } from "@/components/frontend/RichTextView"; import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext"; import { ArrowLeftIcon, ChevronRightIcon, EyeOffIcon, FlagIcon, LandmarkIcon, ScaleIcon, ShieldIcon, } from "lucide-react"; import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item"; import { MissionCard } from "@/components/frontend/intelligence/MissionCard"; import { getCurrencyConfig } from "@/lib/banking"; import { CurrencyAmount } from "@/components/frontend/banking/CurrencyAmount"; import { canViewUndiscoveredFactions, UNDISCOVERED_FACTION_SUMMARY, } from "@/lib/intelligence/factionDiscovery"; import { formatScore, pairKey, relationBand, relationCategoryLabel, RELATION_BAND_CLASSES, } from "@/lib/intelligence/factionRelations"; import { getRelationContext, historyFor } from "@/lib/intelligence/factionRelationLedger"; interface FactionDetailPageProps { params: Promise<{ id: string }>; } const typeColors: Record = { playerFaction: "bg-emerald-500/20 text-emerald-400 border border-emerald-500/30", majorFaction: "bg-blue-500/20 text-blue-400", minorFaction: "bg-muted text-muted-foreground", corporation: "bg-amber-500/20 text-amber-400", special: "bg-purple-500/20 text-purple-400", }; const typeLabels: Record = { playerFaction: "Player Faction", majorFaction: "Major Faction", minorFaction: "Minor Faction", corporation: "Corporation", special: "Special", }; const campaignStatusColors: Record = { concept: "bg-muted text-muted-foreground", inProgress: "bg-blue-500/20 text-blue-400", completed: "bg-emerald-500/20 text-emerald-400", }; function reputationTone(rep: number): string { if (rep >= 50) return "bg-emerald-500/20 text-emerald-400"; if (rep >= 20) return "bg-green-500/20 text-green-400"; if (rep > -20) return "bg-muted text-muted-foreground"; if (rep > -50) return "bg-amber-500/20 text-amber-400"; return "bg-red-500/20 text-red-400"; } function reputationLabel(rep: number): string { if (rep >= 50) return "Revered"; if (rep >= 20) return "Respected"; if (rep > -20) return "Neutral"; if (rep > -50) return "Disliked"; return "Reviled"; } function relationshipTone(value: number): { bar: string; text: string; label: string } { const band = relationBand(value); const classes = RELATION_BAND_CLASSES[band.key]; return { bar: classes.bar, text: classes.text, label: band.label }; } /** One labelled bar for a single direction of a relationship. */ function RelationMeter({ label, value }: { label: string; value: number }) { const tone = relationshipTone(value); const width = Math.min(Math.abs(value), 100) / 2; return (
{label} {formatScore(value)} · {tone.label}
); } function formatOccurred(value: string): string { return new Date(value).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC", }); } export default async function FactionDetailPage({ params }: FactionDetailPageProps) { const { id } = await params; const payload = await getPayload({ config }); const { user } = await payload.auth({ headers: await nextHeaders(), canSetHeaders: false, }); const faction = await payload .findByID({ collection: "factions", id: Number(id), depth: 2, user, }) .catch(() => null); if (!faction) { notFound(); } // Undiscovered factions arrive masked from the Factions afterRead hook unless // the reader is cleared for them. Render the classified stub and skip every // related lookup in that case. const redacted = faction.discovered === false && !(await canViewUndiscoveredFactions(payload, user)); const coverImage = typeof faction.coverImage === "object" && faction.coverImage !== null ? (faction.coverImage as Media) : null; const coverImageUrl = coverImage?.url ?? null; const descriptionText = faction.description ? convertLexicalToPlaintext({ data: faction.description }) : null; const heroSubtitle = redacted ? UNDISCOVERED_FACTION_SUMMARY : descriptionText && descriptionText.length > 240 ? descriptionText.slice(0, 240) + "…" : (descriptionText ?? faction.name); const reputation = faction.reputation ?? 0; // Bank account for this faction const bankRes = redacted ? { docs: [] as unknown[] } : await payload .find({ collection: "bank-accounts", where: { and: [{ ownerFaction: { equals: faction.id } }, { accountType: { equals: "faction" } }], }, depth: 1, limit: 1, }) .catch(() => ({ docs: [] })); const bankAccount = (bankRes.docs[0] as BankAccount | undefined) ?? null; // Currency emblem/label is shared across all accounts (from Game Rules), so // the bank balance renders the same emblem the banking surfaces show. const currencyConfig = await getCurrencyConfig(payload); // Missions involving this faction const missionsRes = redacted ? { docs: [] as Mission[] } : await payload .find({ collection: "missions", where: { "factionsInvolved.faction": { equals: faction.id } }, sort: "-classification.startDateTime", limit: 100, depth: 1, user, overrideAccess: false, select: { name: true, codeName: true, summary: true, operationType: true, ownershipAndStatus: true, classification: true, missionRoles: true, coverImage: true, }, }) .catch(() => ({ docs: [] as Mission[] })); const missions = missionsRes.docs as Mission[]; // Associated campaigns (faction.associatedCampaigns is populated at depth 2) const campaigns = redacted ? [] : (faction.associatedCampaigns?.filter( (c): c is Campaign => typeof c === "object" && c !== null, ) ?? []); // Relationships are computed from the relation ledger, never stored on the // faction. Redacted readers get nothing at all (the classified stub below // renders instead), so the ledger is never queried for them. const relations = redacted ? null : await getRelationContext(payload, user); const relationRows = relations ? relations.factions .filter((other) => other.id !== faction.id) .map((other) => ({ faction: other, inbound: relations.scores.get(pairKey(other.id, faction.id)) ?? 0, outbound: relations.scores.get(pairKey(faction.id, other.id)) ?? 0, hasRecords: relations.rows.some( (row) => (row.subjectId === other.id && row.targetId === faction.id) || (row.subjectId === faction.id && row.targetId === other.id), ), })) .filter((entry) => entry.inbound !== 0 || entry.outbound !== 0 || entry.hasRecords) : []; // Player-facing timeline: every live entry touching this faction, newest // first. A mutual entry appears once. const developments = (() => { if (!relations) return []; const { inbound, outbound } = historyFor(relations, faction.id); return [...inbound, ...outbound] .filter((row, index, all) => all.findIndex((candidate) => candidate.id === row.id) === index) .sort((a, b) => new Date(b.occurredAt).getTime() - new Date(a.occurredAt).getTime()) .slice(0, 8); })(); return (
Back to Factions
{coverImageUrl ? ( ) : (
)}
{typeLabels[faction.type] ?? faction.type} {!redacted && ( {reputationLabel(reputation)} · {reputation >= 0 ? `+${reputation}` : reputation} )}

{faction.name}

{heroSubtitle}

{redacted ? (
No intelligence available
) : (
{typeLabels[faction.type] ?? faction.type} {faction.playableFaction && ( <> · Playable )} {faction.startingFaction && ( <> · Starting )}
)}
{redacted ? (
No Intelligence Available
Classification: Unknown

Nothing is known about this faction. No description, standing, relationships, finances or campaign activity has been recorded yet.

) : (
{/* ── Main Content (2/3) ──────────────────────────── */}
{faction.description && ( Description )} {relationRows.length > 0 && (
Relationships
All relations
{relationRows.map(({ faction: other, inbound, outbound }) => (
{other.name}
))}
)} {developments.length > 0 && (
Recent Developments
    {developments.map((row) => { const tone = relationshipTone(row.delta); return (
  • {formatOccurred(row.occurredAt)} ·{" "} {relationCategoryLabel(row.category)} {formatScore(row.delta)}

    {row.summary}

  • ); })}
)} {missions.length > 0 && (

Missions

{missions.length} mission{missions.length !== 1 ? "s" : ""}
{missions.map((mission) => ( ))}
)}
{/* ── Right Sidebar (1/3) ─────────────────────────── */}
Standing
Reputation {reputation >= 0 ? `+${reputation}` : reputation}

{reputationLabel(reputation)} standing in the world.

{bankAccount && (
Bank Balance
View
{bankAccount.name} {bankAccount.status !== "open" && ( {bankAccount.status} )}
)} {campaigns.length > 0 && (
Associated Campaigns
{campaigns.map((c) => { const campaign = c as { id: number; name: string; status?: string; summary?: string; }; return (
{campaign.name} {campaign.summary && ( {campaign.summary} )}
{campaign.status && ( {campaign.status === "inProgress" ? "In Progress" : campaign.status === "onHold" ? "On Hold" : campaign.status.charAt(0).toUpperCase() + campaign.status.slice(1)} )} ); })}
)}
)}
); }