1
0
Fork 0
polaris-task-force/src/app/(frontend)/intelligence/factions/[id]/page.tsx
Z8MB1E 7428efe6aa fix(intelligence): grow negative relation meters left of zero
The two meters on a faction dossier shared a centered track, but a negative
score grew to the right and a positive one to the left, so the side a bar sat
on said the opposite of what it meant. Negative now extends left of the zero
line and positive right.

The labels also read badly side by side: "They see us" and "We see them" each
start with the party being looked at, which invites reading them the wrong way
round. "How they see us" and "How we see them" name the direction first.
2026-11-20 03:03:29 -05:00

573 lines
23 KiB
TypeScript

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<string, string> = {
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<string, string> = {
playerFaction: "Player Faction",
majorFaction: "Major Faction",
minorFaction: "Minor Faction",
corporation: "Corporation",
special: "Special",
};
const campaignStatusColors: Record<string, string> = {
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 (
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between gap-2 text-xs">
<span className="text-muted-foreground">{label}</span>
<span className={`font-mono ${tone.text}`}>
{formatScore(value)} · {tone.label}
</span>
</div>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${tone.bar}`}
style={{ left: value < 0 ? `${50 - width}%` : "50%", width: `${width}%` }}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
</div>
);
}
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 (
<div className="flex flex-col">
<header className="relative min-h-[500px] w-full overflow-hidden bg-background">
<div className="absolute top-0 left-0 px-5 pt-5 pb-3 z-10">
<Link
href="/intelligence/factions"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to Factions
</Link>
</div>
{coverImageUrl ? (
<img
src={coverImageUrl}
alt=""
fetchPriority="high"
className="absolute inset-0 size-full object-cover opacity-70"
/>
) : (
<div className="absolute inset-0 bg-gradient-to-b from-muted/40 to-background" />
)}
<div className="absolute inset-0 bg-gradient-to-b from-black/50 via-black/40 to-background" />
<div className="absolute inset-0 bg-gradient-to-r from-black/30 via-transparent to-black/40" />
<div className="absolute top-4 right-4 z-20 flex gap-2">
<span
className={`rounded-md border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider backdrop-blur-sm ${typeColors[faction.type] ?? "bg-muted text-muted-foreground"}`}
>
{typeLabels[faction.type] ?? faction.type}
</span>
{!redacted && (
<span
className={`rounded-md border border-white/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-wider backdrop-blur-sm ${reputationTone(reputation)}`}
>
{reputationLabel(reputation)} · {reputation >= 0 ? `+${reputation}` : reputation}
</span>
)}
</div>
<div className="absolute inset-0 flex flex-col items-center justify-center p-6 md:p-10 lg:p-12 text-center">
<h1
id="faction-title"
className="text-5xl font-bold tracking-tight text-white drop-shadow-2xl md:text-6xl"
>
{faction.name}
</h1>
<p className="mt-3 max-w-3xl text-lg leading-relaxed text-white/80">{heroSubtitle}</p>
{redacted ? (
<div className="mt-6 flex items-center gap-2 text-sm text-white/70">
<EyeOffIcon className="size-4 text-white/60" />
<span>No intelligence available</span>
</div>
) : (
<div className="mt-6 flex items-center gap-2 text-sm text-white/70">
<ShieldIcon className="size-4 text-white/60" />
<span>{typeLabels[faction.type] ?? faction.type}</span>
{faction.playableFaction && (
<>
<span className="text-white/30">·</span>
<span>Playable</span>
</>
)}
{faction.startingFaction && (
<>
<span className="text-white/30">·</span>
<span>Starting</span>
</>
)}
</div>
)}
</div>
</header>
<div className="p-5 flex flex-col gap-6 max-w-[96rem] mx-auto w-full">
{redacted ? (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<EyeOffIcon className="size-4 text-muted-foreground" />
<ItemTitle>No Intelligence Available</ItemTitle>
</div>
<span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
Classification: Unknown
</span>
</ItemHeader>
<ItemContent>
<p className="text-sm text-muted-foreground">
Nothing is known about this faction. No description, standing, relationships,
finances or campaign activity has been recorded yet.
</p>
</ItemContent>
</Item>
) : (
<div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
{/* ── Main Content (2/3) ──────────────────────────── */}
<div className="xl:col-span-2 flex flex-col gap-6">
{faction.description && (
<Item variant="outline">
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent>
<RichTextView data={faction.description} />
</ItemContent>
</Item>
)}
{relationRows.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Relationships</ItemTitle>
</div>
<Link
href="/intelligence/factions/relations"
className="py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
All relations
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-3">
{relationRows.map(({ faction: other, inbound, outbound }) => (
<div
key={other.id}
className="flex flex-col gap-2 rounded-md border border-border/50 p-3"
>
<Link
href={`/intelligence/factions/${other.id}`}
className="flex w-fit items-center gap-2 py-1 text-sm font-medium transition-colors hover:text-primary"
>
<ShieldIcon className="size-4 text-muted-foreground" />
<span>{other.name}</span>
</Link>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
<RelationMeter label="How they see us" value={inbound} />
<RelationMeter label="How we see them" value={outbound} />
</div>
</div>
))}
</div>
</ItemContent>
</Item>
)}
{developments.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Recent Developments</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<ul className="divide-y divide-border/50">
{developments.map((row) => {
const tone = relationshipTone(row.delta);
return (
<li
key={row.id}
className="flex flex-col gap-1 py-2 first:pt-0 last:pb-0"
>
<div className="flex items-center justify-between gap-2 text-xs">
<span className="text-muted-foreground">
{formatOccurred(row.occurredAt)} ·{" "}
{relationCategoryLabel(row.category)}
</span>
<span className={`shrink-0 font-mono ${tone.text}`}>
{formatScore(row.delta)}
</span>
</div>
<p className="text-sm">{row.summary}</p>
</li>
);
})}
</ul>
</ItemContent>
</Item>
)}
{missions.length > 0 && (
<section className="flex flex-col gap-3">
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Missions
</h2>
<span className="text-xs text-muted-foreground">
{missions.length} mission{missions.length !== 1 ? "s" : ""}
</span>
</div>
<div className="flex flex-col gap-2">
{missions.map((mission) => (
<MissionCard key={mission.id} mission={mission} showFullDetails={false} />
))}
</div>
</section>
)}
</div>
{/* ── Right Sidebar (1/3) ─────────────────────────── */}
<div className="flex flex-col gap-4">
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Standing</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-2">
<div className="flex justify-between text-sm">
<span className="text-muted-foreground">Reputation</span>
<span className={`font-mono ${reputationTone(reputation).split(" ")[1]}`}>
{reputation >= 0 ? `+${reputation}` : reputation}
</span>
</div>
<div className="relative h-2 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${reputationTone(reputation).split(" ")[0]}`}
style={{
left:
reputation < 0
? "50%"
: `${50 - Math.min(Math.abs(reputation), 100) / 2}%`,
width: `${Math.min(Math.abs(reputation), 100) / 2}%`,
}}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
<p className="text-xs text-muted-foreground pt-1">
{reputationLabel(reputation)} standing in the world.
</p>
</div>
</ItemContent>
</Item>
{bankAccount && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<LandmarkIcon className="size-4 text-muted-foreground" />
<ItemTitle>Bank Balance</ItemTitle>
</div>
<Link
href={`/logistics/banking/${bankAccount.id}`}
className="py-1 text-xs text-muted-foreground hover:text-primary transition-colors"
>
View
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1">
<span className="text-lg font-semibold font-mono">
<CurrencyAmount
value={bankAccount.balance ?? 0}
currency={currencyConfig}
/>
</span>
<span className="text-xs text-muted-foreground">{bankAccount.name}</span>
{bankAccount.status !== "open" && (
<span className="text-[10px] font-semibold uppercase tracking-wider px-1.5 py-0.5 rounded w-fit bg-amber-500/20 text-amber-400">
{bankAccount.status}
</span>
)}
</div>
</ItemContent>
</Item>
)}
{campaigns.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<FlagIcon className="size-4 text-muted-foreground" />
<ItemTitle>Associated Campaigns</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-1.5">
{campaigns.map((c) => {
const campaign = c as {
id: number;
name: string;
status?: string;
summary?: string;
};
return (
<Link
key={campaign.id}
href={`/intelligence/campaigns/${campaign.id}`}
className="flex items-center gap-3 p-1.5 rounded-md hover:bg-muted/50 transition-colors group"
>
<FlagIcon className="size-4 text-muted-foreground shrink-0" />
<div className="flex flex-col gap-0.5 min-w-0 flex-1">
<span className="text-sm font-medium truncate group-hover:text-primary transition-colors">
{campaign.name}
</span>
{campaign.summary && (
<span className="text-xs text-muted-foreground line-clamp-1">
{campaign.summary}
</span>
)}
</div>
{campaign.status && (
<span
className={`text-[10px] font-semibold uppercase tracking-wider px-1 py-0.5 rounded shrink-0 ${campaignStatusColors[campaign.status] ?? "bg-muted text-muted-foreground"}`}
>
{campaign.status === "inProgress"
? "In Progress"
: campaign.status === "onHold"
? "On Hold"
: campaign.status.charAt(0).toUpperCase() +
campaign.status.slice(1)}
</span>
)}
<ChevronRightIcon className="size-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity shrink-0" />
</Link>
);
})}
</div>
</ItemContent>
</Item>
)}
</div>
</div>
)}
</div>
</div>
);
}