"use client"; import { useState, useEffect, useRef } from "react"; import { v4 as uuidv4 } from "uuid"; import { Button } from "@/components/ui/button"; import { Field, FieldError, FieldGroup, FieldLabel, FieldSet } from "@/components/ui/field"; import { InputGroup, InputGroupInput } from "@/components/ui/input-group"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { PlusIcon, XIcon, ChevronDownIcon, ChevronUpIcon, Trash2Icon, ListOrderedIcon, CaseLowerIcon, UserCogIcon } from "lucide-react"; import { cn } from "@/lib/utils"; import Image from "next/image"; import { Merriweather } from "next/font/google"; import { ActEditorData, ActType, ArticleContent, Clause, ClauseMarkerStyle, Institution, PositionOption, Region } from "@/lib/acts/types"; import { searchCitizensAction } from "@/lib/citizenship/actions"; const documentText = Merriweather({ weight: "400" }); const documentHeading = Merriweather({ weight: "700" }); type ActEditorProps = { actTypes: ActType[]; institutions: Institution[]; regions: Region[]; positions: PositionOption[]; initial?: Partial; onChange: (data: ActEditorData) => void; errors?: { title?: string[]; issuingInstitutionId?: string[] }; }; const LETTER_MARKERS = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]; function computeMarker(style: ClauseMarkerStyle, index: number): string | null { if (style === "NONE") return null; if (style === "LETTERS") return `${LETTER_MARKERS[index] ?? index + 1})`; return `${index + 1}.`; } function makeEmptyTextClause(): Clause { return { id: uuidv4(), kind: "TEXT", text: "" }; } function makeEmptyAppointmentClause(): Clause { return { id: uuidv4(), kind: "APPOINTMENT", action: "ASSIGN", positionId: "", citizenshipId: "", citizenshipName: "" }; } function makeEmptyArticle(): ArticleContent { return { id: uuidv4(), title: "", markerStyle: "NONE", clauses: [makeEmptyTextClause()] }; } export default function ActEditor({ actTypes, institutions, regions, positions, initial, onChange, errors }: ActEditorProps) { const [issuingInstitutionId, setIssuingInstitutionId] = useState(initial?.issuingInstitutionId ?? ""); const [actTypeId, setActTypeId] = useState(initial?.actTypeId ?? ""); const [regionId, setRegionId] = useState(initial?.regionId ?? ""); const [title, setTitle] = useState(initial?.title ?? ""); const [preambleText, setPreambleText] = useState(initial?.preambleText ?? ""); const [articles, setArticles] = useState(initial?.articles ?? [makeEmptyArticle()]); const onChangeRef = useRef(onChange); useEffect(() => { onChangeRef.current = onChange; }); useEffect(() => { onChangeRef.current({ actTypeId, issuingInstitutionId, regionId, title, preambleText, articles }); }, [actTypeId, issuingInstitutionId, regionId, title, preambleText, articles]); const appointablePositions = positions.filter((p) => { const owner = institutions.find((i) => i.id === p.institutionId); const requiredIssuerId = owner?.appointedByInstitutionId ?? owner?.id; return requiredIssuerId === issuingInstitutionId; }); const selectedInstitution = institutions.find((i) => i.id === issuingInstitutionId); const availableActTypes = selectedInstitution ? actTypes.filter((t) => t.allowedIssuerKind === selectedInstitution.kind) : []; const needsRegion = selectedInstitution?.kind === "REGION"; function updateArticle(id: string, patch: Partial) { setArticles(articles.map((a) => (a.id === id ? { ...a, ...patch } : a))); } function addArticle() { setArticles([...articles, makeEmptyArticle()]); } function removeArticle(id: string) { setArticles(articles.filter((a) => a.id !== id)); } function moveArticle(from: number, to: number) { const updated = [...articles]; const [moved] = updated.splice(from, 1); updated.splice(to, 0, moved); setArticles(updated); } return (

Meta

Issuing institution {errors?.issuingInstitutionId && ({ message: m }))} />} Act type {needsRegion && ( Region )} Title setTitle(e.target.value)} /> {errors?.title && ({ message: m }))} />}
Emblem of the European Federation

{!needsRegion ? "European Federation" : regions.find((region) => region.id === regionId)?.name}

{institutions.find((i) => i.id === issuingInstitutionId)?.name}

Draft of a {actTypes.find((a) => a.id === actTypeId)?.name} {title && `“${title}”`}

setPreambleText(e.target.value)} />
{articles.map((article, index) => (
updateArticle(article.id, patch)} />
{articles.length > 1 && ( )}
))}
); } function ArticleEditor({ content, articleIndex, appointablePositions, onChange, }: { content: ArticleContent; articleIndex: number; appointablePositions: PositionOption[]; onChange: (patch: Partial) => void; }) { const clauses = content.clauses ?? [makeEmptyTextClause()]; function updateClause(id: string, patch: Partial) { onChange({ clauses: clauses.map((c) => (c.id === id ? { ...c, ...patch } as Clause : c)) }); } function addClause(afterIndex: number, clause: Clause) { const updated = [...clauses]; updated.splice(afterIndex + 1, 0, clause); onChange({ clauses: updated }); } function removeClause(id: string) { const updated = clauses.filter((c) => c.id !== id); onChange({ clauses: updated.length ? updated : [makeEmptyTextClause()] }); } return (

Article {articleIndex + 1}

onChange({ title: e.target.value })} />
{content.markerStyle !== "NONE" && ( onChange({ intro: e.target.value })} /> )}
{clauses.map((clause, i) => { const marker = computeMarker(content.markerStyle, i); return (
{marker && {marker}} {clause.kind === "APPOINTMENT" ? ( updateClause(clause.id, patch)} /> ) : ( updateClause(clause.id, { text: e.target.value })} /> )}
{clauses.length > 1 && ( )}
); })}
); } // Renders an appointment clause inline as a fill-in-the-blank sentence: // "[Appoint|Dismiss] [citizen] [to|from] [position]." function AppointmentClauseEditor({ clause, positions, onChange, }: { clause: Extract; positions: PositionOption[]; onChange: (patch: Partial) => void; }) { return (
onChange({ citizenshipId: c?.id ?? "", citizenshipName: c?.name ?? "" })} /> {clause.action === "ASSIGN" ? "to" : "from"} .
); } function CitizenshipPicker({ value, onSelect, }: { value: { id: string; name: string } | null; onSelect: (value: { id: string; name: string } | null) => void; }) { const [query, setQuery] = useState(""); const [results, setResults] = useState<{ id: string; firstName: string; secondName: string }[]>([]); useEffect(() => { if (!query.trim()) { setResults([]); return; } const timeout = setTimeout(async () => { const result = await searchCitizensAction(query); if (result.success) setResults(result.data); }, 250); return () => clearTimeout(timeout); }, [query]); if (value) { return ( {value.name} ); } return ( setQuery(e.target.value)} /> {results.length > 0 && (
{results.map((c) => ( ))}
)}
); } function AutoResizeTextarea({ value, onChange, className, placeholder }: { value: string; onChange: (e: React.ChangeEvent) => void; className?: string; placeholder?: string }) { const ref = useRef(null); useEffect(() => { if (ref.current) { ref.current.style.height = "auto"; ref.current.style.height = `${ref.current.scrollHeight}px`; } }, [value]); return