"use client"; import { useEffect, useRef, useState, type ReactNode } from "react"; import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react"; import { Button } from "@/app/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "@/app/components/ui/card"; import { Input } from "@/app/components/ui/input"; import { Label } from "@/app/components/ui/label"; import { ErrorState } from "@/app/components/ui/states"; import { FieldError } from "@/app/components/catalog-setup/FieldError"; import { parseServerError, type FieldErrors } from "@/app/lib/catalogSetup"; import { MENU_TITLES, menuBody, moveAt, type MenuHandle, type MenuItem } from "@/app/lib/menus"; import { getMenu, saveMenu } from "@/app/lib/services/adminMenus"; import { ApiError } from "@/app/lib/clientApi"; import { useT } from "@/app/lib/i18n/MessagesProvider"; // One storefront menu (add-storefront-menus): top-level items, each with links under it. Rows carry // stable keys so moves keep their inputs. export interface LinkOption { label: string; url: string; } interface Row { key: number; label: string; url: string; children: Row[]; } const SELECT_CLASS = "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm disabled:cursor-not-allowed disabled:opacity-50"; /** Server error paths shown under a field; anything else goes to the summary alert. */ const RENDERED = /^(items|items\[\d+\]\.(label|url|children)|items\[\d+\]\.children\[\d+\]\.(label|url))$/; function Field({ id, label, error, children }: { id: string; label: string; error?: string; children: ReactNode }) { return (
{children}
); } export function MenuEditor({ handle, options }: { handle: MenuHandle; options: LinkOption[] }) { const t = useT(); const title = MENU_TITLES[handle]; const nextKey = useRef(0); const toRows = (items: MenuItem[]): Row[] => items.map((i) => ({ key: ++nextKey.current, label: i.label, url: i.url ?? "", children: toRows(i.children ?? []) })); const [rows, setRows] = useState([]); const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(null); const [errors, setErrors] = useState({}); const [summary, setSummary] = useState(null); const [notice, setNotice] = useState(null); const [saving, setSaving] = useState(false); useEffect(() => { let cancelled = false; getMenu(handle) .then((view) => { if (!cancelled) setRows(toRows(view.items ?? [])); }) .catch((err: unknown) => { if (!cancelled) setLoadError(err instanceof Error ? err.message : "MnuLoadFailed"); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps -- load once per handle }, [handle]); // Errors are keyed by position, so any reorder or removal clears them. const reorder = (next: Row[]) => { setErrors({}); setRows(next); }; const updateRow = (key: number, patch: Partial) => setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch } : r))); const updateChild = (parent: number, key: number, patch: Partial) => setRows((rs) => rs.map((r) => (r.key === parent ? { ...r, children: r.children.map((c) => (c.key === key ? { ...c, ...patch } : c)) } : r))); const newRow = (): Row => ({ key: ++nextKey.current, label: "", url: "", children: [] }); async function save() { setErrors({}); setSummary(null); setNotice(null); setSaving(true); try { const toItems = (rs: Row[]): MenuItem[] => rs.map((r) => ({ label: r.label, url: r.url, children: toItems(r.children) })); await saveMenu(handle, menuBody(toItems(rows))); setNotice("MnuSaved"); } catch (err) { const message = err instanceof Error ? err.message : "MnuSaveFailed"; const { path, message: fieldMessage } = parseServerError(message); if (err instanceof ApiError && err.status === 422 && path && RENDERED.test(path)) setErrors({ [path]: fieldMessage }); else setSummary(message); } finally { setSaving(false); } } const linkFields = (prefix: string, idBase: string, row: Row, onChange: (patch: Partial) => void) => (
onChange({ label: e.target.value })} /> onChange({ url: e.target.value })} />
); return ( {t(title)} {loadError ? ( ) : loading ? null : ( <> {summary &&

{t(summary)}

} {notice &&

{t(notice)}

} {rows.map((row, i) => (
{t("MnuItemN", { n: i + 1 })}
{linkFields(`items[${i}]`, `menu-${handle}-${row.key}`, row, (patch) => updateRow(row.key, patch))} {row.children.map((c, j) => (
{t("MnuLinkN", { n: j + 1 })}
{linkFields(`items[${i}].children[${j}]`, `menu-${handle}-${row.key}-${c.key}`, c, (patch) => updateChild(row.key, c.key, patch))}
))}
))}
)}
); }