"use client"; import { useState } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import LinkEntityModal from "@/components/LinkEntityModal"; import StatusBadge from "@/components/StatusBadge"; import { text, formatDate, deriveCompanyStatus } from "@/lib/format"; import type { YsterbaardCompany } from "@/lib/types"; interface JunctionEntry { id: string; company_id: string; company: YsterbaardCompany; } interface Props { directorId: string; directorName: string; initial: JunctionEntry[]; } export default function LinkedCompaniesList({ directorId, directorName, initial }: Props) { const router = useRouter(); const [showLinkModal, setShowLinkModal] = useState(false); const [unlinking, setUnlinking] = useState(null); const [linked, setLinked] = useState(initial); const [error, setError] = useState(null); const alreadyLinkedIds = linked.map((j) => j.company_id); async function handleUnlink(junctionId: string, companyName: string) { if (!confirm(`Remove link to "${companyName}"? The company will remain in PocketBase.`)) return; setUnlinking(junctionId); setError(null); try { const res = await fetch("/api/pb/records/link", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action: "unlink", director: directorId, company: linked.find((j) => j.id === junctionId)?.company_id, }), }); if (!res.ok) { const err = await res.json(); throw new Error(err.error ?? "Unlink failed"); } setLinked((prev) => prev.filter((j) => j.id !== junctionId)); window.location.reload(); } catch (e: unknown) { setError(e instanceof Error ? e.message : "Unlink failed"); } finally { setUnlinking(null); } } return ( <>

Linked companies

{linked.length} record{linked.length === 1 ? "" : "s"}

{error && (
{error}
)} {linked.length === 0 ? (
No companies linked to this director.
) : (
{linked.map((j) => { const c = j.company; const bucket = deriveCompanyStatus(c.enterprise_status, c.is_active); const badge = (() => { if (bucket === "active") return In business; if (bucket === "deregistered") return Deregistered; if (bucket === "in_process") return In process; return Inactive; })(); return (

{text(c.enterprise_name)}

{text(c.enterprise_no)}

{badge} {text(c.director_status) !== "—" && ( {text(c.director_status)} )}
Status: {text(c.enterprise_status)} Source: {text(c.source)} Last checked: {formatDate(c.last_checked)}
View company →
); })}
)}
setShowLinkModal(false)} onLinked={() => router.refresh()} /> ); }