"use client"; import dynamic from "next/dynamic"; import Image from "next/image"; import { ChartNoAxesCombinedIcon, ChevronDownIcon, ChevronUpIcon, ClipboardCopyIcon, ClipboardPasteIcon, CopyIcon, GemIcon, GripVerticalIcon, HeartPulseIcon, ListOrderedIcon, PlusIcon, RefreshCcwIcon, SearchIcon, SparklesIcon, SwordIcon, TimerIcon, Trash2Icon, UserRoundIcon, XIcon, } from "lucide-react"; import { useEffect, useMemo, useState, type ReactNode } from "react"; import { toast } from "sonner"; import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors, type DragEndEvent, } from "@dnd-kit/core"; import { arrayMove, rectSortingStrategy, SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy, } from "@dnd-kit/sortable"; import { CSS } from "@dnd-kit/utilities"; import { saveArtifactSection, saveConstellationSection, saveExtraSectionList, saveTeamSection, saveWeaponSection, } from "@/app/admin/actions"; import { AutosaveStatus } from "@/components/admin/autosave-status"; import { DeleteConfirmationDialog } from "@/components/admin/delete-confirmation-dialog"; import { MediaUploader } from "@/components/admin/media-uploader"; import { SimpleTooltip } from "@/components/tooltip"; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger, } from "@/components/ui/accordion"; import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; import { Button } from "@/components/ui/button"; import { Checkbox } from "@/components/ui/checkbox"; import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, } from "@/components/ui/card"; import { Combobox, ComboboxContent, ComboboxEmpty, ComboboxInput, ComboboxItem, ComboboxList, } from "@/components/ui/combobox"; import { Field, FieldDescription, FieldGroup, FieldLabel, FieldLegend, FieldSet, } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Textarea } from "@/components/ui/textarea"; import { Skeleton } from "@/components/ui/skeleton"; import { Toggle } from "@/components/ui/toggle"; import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { useAutosave } from "@/hooks/use-autosave"; import { adminDraftKey } from "@/lib/editor/local-draft"; import { artifactSectionSchema, constellationSectionSchema, extraSectionSchema, mainStatOptions, substatOptions, talentLevelOptions, teamSectionSchema, weaponSectionSchema, } from "@/lib/guides/schemas"; import { normalizeTargetStat, recommendedStatElement, recommendedStatIconName, targetStatDefaults, targetStatIconName, targetStatOptions, } from "@/lib/guides/stats"; import { elementIconFilter } from "@/lib/catalog/element"; import { supportsWeaponType } from "@/lib/catalog/lunaris"; import { rarityGradientClass } from "@/lib/catalog/rarity"; import { applyPresetFields, applyTeamFields, findInvalidTeamCatalogReference, findUnsupportedTeamWeapon, limitPresets, parseTeamPresets, parseTeamTransfer, serializeTeamTransfer, teamTransferFileName, teamPresetCookieKey, teamPresetStorageKey, type TeamApplySelection, type TeamMemberApplyField, type TeamPreset, type TeamToolValue, } from "@/lib/guides/team-tools"; import { matchesTeamSearch, type TeamSearchTarget, } from "@/lib/guides/team-search"; import { normalizeTalentPriorities, reorderTalentPriorities, type TalentPriority, type TalentRelation, } from "@/lib/guides/talents"; import { finalizePercentInput, normalizePercentInput, } from "@/lib/guides/percent-input"; import { formatGuideValidationIssues } from "@/lib/guides/validation-messages"; import { normalizeExtraRichText } from "@/lib/rich-text"; import { cn } from "@/lib/utils"; type CatalogItem = { key: string; name: string; imageUrl: string; rarity?: number | null; weaponType?: string | null; element?: string | null; elementIconUrl?: string | null; }; type ExtraCatalogItem = { kind: "character" | "weapon" | "artifact"; key: string; }; const teamMemberApplyOptions = [ ["characterKey", "Character"], ["weaponKey", "Weapon"], ["artifactKey", "Artifact 1"], ["secondArtifactKey", "Artifact 2"], ["constellation", "C"], ["refinement", "R"], ["damage", "Damage"], ] as const satisfies readonly (readonly [TeamMemberApplyField, string])[]; type Guide = { id: string; characterKey: string; version: number; name: string; }; type WeaponValue = { id: string; weaponKey: string; refinement: number; overallPercent: string | null; personalPercent: string | null; note: string | null; weapon: CatalogItem; }; type WeaponGroupValue = { id: string; note: string | null; rows: WeaponValue[]; }; type ArtifactValue = { id: string; name: string; rows: Array<{ firstArtifactKey: string; secondArtifactKey: string | null; percent: string; note: string | null; }>; }; type ArtifactProfile = { sands: string[]; goblet: string[]; circlet: string[]; substats: string[]; targets: Array<{ stat: string; value: string }>; talents: TalentPriority[]; note: string | null; } | null; type ConstellationValue = { level: number; detail: string; cumulativePercent: string; isGreat: boolean; }; type ConstellationGroupValue = { id: string; note: string | null; rows: ConstellationValue[]; }; type CatalogConstellation = { level: number; name: string; description: string; iconUrl: string | null; }; type CatalogTalent = { type: "NA" | "E" | "Q"; name: string; iconUrl: string | null; }; type TeamValue = { id: string; title: string; rotationSeconds: string; combo: string; members: Array<{ characterKey: string; weaponKey: string | null; artifactKey: string | null; secondArtifactKey: string | null; constellation: number; refinement: number; damage: string; }>; }; let clientIdCounter = 0; const DEFAULT_EXTRA_BACKGROUND_COLOR = "#24232C"; const DEFAULT_EXTRA_TEXT_COLOR = "#FAFAFA"; const RichTextEditor = dynamic( () => import("@/components/rich-text-editor").then((module) => module.RichTextEditor), { ssr: false, loading: () => , }, ); function createClientId(prefix: string): string { const browserCrypto = globalThis.crypto; if (typeof browserCrypto?.randomUUID === "function") return `${prefix}-${browserCrypto.randomUUID()}`; clientIdCounter += 1; return `${prefix}-${Date.now()}-${clientIdCounter}`; } function parseEditorDraft( value: unknown, arrayKeys: string[], stringKeys: string[] = [], ): Draft | null { if (!value || typeof value !== "object") return null; const record = value as Record; if (arrayKeys.some((key) => !Array.isArray(record[key]))) return null; if (stringKeys.some((key) => typeof record[key] !== "string")) return null; return value as Draft; } function hasIssuePrefix( issues: readonly { path: readonly PropertyKey[] }[], ...path: (string | number)[] ): boolean { return issues.some((issue) => path.every((part, index) => issue.path[index] === part)); } export interface GuideSectionEditorProps { section: "weapon" | "artifact" | "constellations" | "team" | "extra"; guide: Guide; weapons: CatalogItem[]; artifacts: CatalogItem[]; characters: CatalogItem[]; catalogConstellations: CatalogConstellation[]; catalogTalents: CatalogTalent[]; initial: { sectionNote: string | null; weaponGroups: WeaponGroupValue[]; artifactGroups: ArtifactValue[]; artifactProfile: ArtifactProfile; constellationGroups: ConstellationGroupValue[]; teams: TeamValue[]; extras: Array<{ id: string; title: string; rows: Array<{ id: string; mediaId: string | null; heading: string; body: string; percent: string | null; backgroundColor: string | null; textColor: string | null; catalogItems: ExtraCatalogItem[]; highlights: Array<{ text: string; color: string }>; imageUrl: string | null; imageWidth: number | null; imageHeight: number | null; }>; }>; }; } const SELECTED_TOGGLE_CLASS = "aria-pressed:border-primary aria-pressed:ring-2 aria-pressed:ring-primary/30"; function CatalogPicker({ items, value, onChange, placeholder, rarityBackground = false, showSelectedImage = false, invalid = false, }: { items: CatalogItem[]; value: string; onChange: (value: string) => void; placeholder: string; rarityBackground?: boolean; showSelectedImage?: boolean; invalid?: boolean; }) { const selected = items.find((item) => item.key === value) ?? null; return (
{showSelectedImage && selected ? (
) : null}
onChange(next?.key ?? "")} itemToStringLabel={(item) => item.name} itemToStringValue={(item) => item.key} autoHighlight > ไม่พบรายการ {(item) => (
{item.name}
)}
); } function StatSelect({ label, options, value, max, onChange, elementIconUrls, }: { label: string; options: readonly string[]; value: string[]; max: number; onChange: (value: string[]) => void; elementIconUrls: Record; }) { return ( {label} เลือกได้สูงสุด {max} ค่า ); } function StatIcons({ values, elementIconUrls = {}, }: { values: readonly string[]; elementIconUrls?: Record; }) { const icons = values.flatMap((value) => { const element = recommendedStatElement(value); if (element && elementIconUrls[element]) { return [{ name: element, src: elementIconUrls[element], element }]; } const targetIcon = targetStatIconName(value); if (targetIcon) { return [{ name: targetIcon, src: `/icon/stats/${targetIcon}.webp` }]; } const recommendedIcon = recommendedStatIconName(value); return recommendedIcon ? [{ name: recommendedIcon, src: `/icon/stats/${recommendedIcon}.${recommendedIcon === "elemental-bonus" ? "svg" : "webp"}`, }] : []; }); if (!icons.length) return null; return ( ); } function StatIcon({ name, src, element, }: { name: string; src: string; element?: string; }) { const [hasError, setHasError] = useState(false); if (hasError) { const PlaceholderIcon = name === "healing-bonus" ? HeartPulseIcon : SparklesIcon; return (