import React, { useCallback, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { TemplateSampleSetting } from "@/user-management/services/TemplateConfiguration/types/templateTypes";
import type { PageMarginValue } from "./PageMarginEditor";
import {
	LetterAssetsPlacementCanvas,
	normalizeAbsoluteAssetOrder,
	type LetterAbsoluteAssetKey,
} from "./LetterAssetsPlacementCanvas";
import {
	normalizeLayoutPositionValue,
	toAbsolutePayloadPosition,
	buildDefaultPositionsByLanguage,
	type LayoutPositionValue,
	type LetterLanguage,
} from "./layout-position";

export const LAYOUT_CONFIG_SETTING_CODE = "letter-layout-config";

export type LetterLayoutSectionKey =
	| "reference"
	| "receivers"
	| "sender"
	| "subject"
	| "body"
	| "closing"
	| "cc"
	| "forYourReference";

export type LetterLayoutHorizontalAlign = "auto" | "start" | "center" | "end";
export type LetterClosingAssetKey = "signatures" | "seal";
export type LetterSenderAssetKey = "signature" | "stamp";
export type LetterStampPlacement = "below-last-signature" | "beside-signatures";

export type LetterClosingLanguagePositions = {
	signatures: LayoutPositionValue;
	seal: LayoutPositionValue;
	stamp: LayoutPositionValue;
};

export type LetterLayoutPositionsByLanguage = {
	am: LetterClosingLanguagePositions;
	en: LetterClosingLanguagePositions;
};

export type LetterLayoutConfigValue = {
	sectionOrder: LetterLayoutSectionKey[];
	signatures: {
		widthPt: number;
		heightPx: number;
		gapPx: number;
		align: LetterLayoutHorizontalAlign;
		position: LayoutPositionValue;
	};
	seal: { widthPx: number; heightPx: number; position: LayoutPositionValue };
	stamp: {
		widthPt: number;
		heightPx: number;
		placement: LetterStampPlacement;
		position: LayoutPositionValue;
	};
	sender: {
		align: LetterLayoutHorizontalAlign;
		assetOrder: LetterSenderAssetKey[];
		signature: LayoutPositionValue;
		stamp: LayoutPositionValue;
	};
	closingAssetOrder: LetterClosingAssetKey[];
	absoluteAssetOrder: LetterAbsoluteAssetKey[];
	positionsByLanguage: LetterLayoutPositionsByLanguage;
};

const ALL_SECTION_KEYS: LetterLayoutSectionKey[] = [
	"reference",
	"receivers",
	"sender",
	"subject",
	"body",
	"closing",
	"cc",
	"forYourReference",
];

const DEFAULT_POSITIONS_BY_LANGUAGE = buildDefaultPositionsByLanguage();

const DEFAULT_LAYOUT_CONFIG: LetterLayoutConfigValue = {
	sectionOrder: [...ALL_SECTION_KEYS],
	signatures: {
		widthPt: 96,
		heightPx: 50,
		gapPx: 20,
		align: "auto",
		position: { ...DEFAULT_POSITIONS_BY_LANGUAGE.am.signatures },
	},
	seal: {
		widthPx: 140,
		heightPx: 140,
		position: { ...DEFAULT_POSITIONS_BY_LANGUAGE.am.seal },
	},
	stamp: {
		widthPt: 96,
		heightPx: 50,
		placement: "below-last-signature",
		position: { ...DEFAULT_POSITIONS_BY_LANGUAGE.am.stamp },
	},
	sender: {
		align: "auto",
		assetOrder: ["signature", "stamp"],
		signature: normalizeLayoutPositionValue(null, "senderSignature"),
		stamp: normalizeLayoutPositionValue(null, "senderStamp"),
	},
	closingAssetOrder: ["signatures", "seal"],
	absoluteAssetOrder: [
		"signatures",
		"seal",
		"stamp",
		"senderSignature",
		"senderStamp",
	],
	positionsByLanguage: DEFAULT_POSITIONS_BY_LANGUAGE,
};

const HORIZONTAL_ALIGNS: LetterLayoutHorizontalAlign[] = [
	"auto",
	"start",
	"center",
	"end",
];
const STAMP_PLACEMENTS: LetterStampPlacement[] = [
	"below-last-signature",
	"beside-signatures",
];
const CLOSING_ASSET_KEYS: LetterClosingAssetKey[] = ["signatures", "seal"];
const SENDER_ASSET_KEYS: LetterSenderAssetKey[] = ["signature", "stamp"];

function parsePositiveNumber(value: unknown, fallback: number): number {
	if (typeof value === "number" && Number.isFinite(value) && value > 0) {
		return value;
	}
	if (typeof value === "string") {
		const parsed = Number.parseFloat(value.trim());
		if (Number.isFinite(parsed) && parsed > 0) return parsed;
	}
	return fallback;
}

function isSectionKey(value: unknown): value is LetterLayoutSectionKey {
	return (
		typeof value === "string" &&
		ALL_SECTION_KEYS.includes(value as LetterLayoutSectionKey)
	);
}

function parseAlign(value: unknown, fallback: LetterLayoutHorizontalAlign): LetterLayoutHorizontalAlign {
	return typeof value === "string" &&
		HORIZONTAL_ALIGNS.includes(value as LetterLayoutHorizontalAlign)
		? (value as LetterLayoutHorizontalAlign)
		: fallback;
}

function parseStampPlacement(value: unknown): LetterStampPlacement {
	return typeof value === "string" &&
		STAMP_PLACEMENTS.includes(value as LetterStampPlacement)
		? (value as LetterStampPlacement)
		: DEFAULT_LAYOUT_CONFIG.stamp.placement;
}

function parseClosingAssetOrder(value: unknown): LetterClosingAssetKey[] {
	if (!Array.isArray(value)) return [...DEFAULT_LAYOUT_CONFIG.closingAssetOrder];
	const seen = new Set<LetterClosingAssetKey>();
	const order: LetterClosingAssetKey[] = [];
	for (const item of value) {
		if (
			(item === "signatures" || item === "seal") &&
			!seen.has(item as LetterClosingAssetKey)
		) {
			seen.add(item as LetterClosingAssetKey);
			order.push(item as LetterClosingAssetKey);
		}
	}
	for (const key of CLOSING_ASSET_KEYS) {
		if (!seen.has(key)) order.push(key);
	}
	return order;
}

function parseSenderAssetOrder(value: unknown): LetterSenderAssetKey[] {
	if (!Array.isArray(value)) return [...DEFAULT_LAYOUT_CONFIG.sender.assetOrder];
	const seen = new Set<LetterSenderAssetKey>();
	const order: LetterSenderAssetKey[] = [];
	for (const item of value) {
		if (
			(item === "signature" || item === "stamp") &&
			!seen.has(item as LetterSenderAssetKey)
		) {
			seen.add(item as LetterSenderAssetKey);
			order.push(item as LetterSenderAssetKey);
		}
	}
	for (const key of SENDER_ASSET_KEYS) {
		if (!seen.has(key)) order.push(key);
	}
	return order;
}

function parseClosingLanguagePositions(
	raw: unknown,
	language: LetterLanguage,
	fallback: LetterClosingLanguagePositions,
	flatFallback?: Partial<LetterClosingLanguagePositions>,
): LetterClosingLanguagePositions {
	const record =
		raw != null && typeof raw === "object" && !Array.isArray(raw)
			? (raw as Record<string, unknown>)
			: {};
	return {
		signatures: toAbsolutePayloadPosition(
			normalizeLayoutPositionValue(
				record.signatures ??
					flatFallback?.signatures ??
					fallback.signatures,
				"signatures",
				undefined,
				language,
			),
		) as unknown as LayoutPositionValue,
		seal: toAbsolutePayloadPosition(
			normalizeLayoutPositionValue(
				record.seal ?? flatFallback?.seal ?? fallback.seal,
				"seal",
				undefined,
				language,
			),
		) as unknown as LayoutPositionValue,
		stamp: toAbsolutePayloadPosition(
			normalizeLayoutPositionValue(
				record.stamp ?? flatFallback?.stamp ?? fallback.stamp,
				"stamp",
				undefined,
				language,
			),
		) as unknown as LayoutPositionValue,
	};
}

function parsePositionsByLanguage(
	record: Record<string, unknown>,
	flat: LetterClosingLanguagePositions,
): LetterLayoutPositionsByLanguage {
	const defaults = buildDefaultPositionsByLanguage();
	const raw = record.positionsByLanguage;
	if (raw != null && typeof raw === "object" && !Array.isArray(raw)) {
		const byLang = raw as Record<string, unknown>;
		return {
			am: parseClosingLanguagePositions(byLang.am, "am", defaults.am),
			en: parseClosingLanguagePositions(byLang.en, "en", defaults.en),
		};
	}
	return {
		am: parseClosingLanguagePositions(undefined, "am", defaults.am, flat),
		en: parseClosingLanguagePositions(undefined, "en", defaults.en),
	};
}

export function normalizeLayoutConfigValue(
	value: unknown,
): LetterLayoutConfigValue {
	if (value == null || typeof value !== "object" || Array.isArray(value)) {
		return {
			sectionOrder: [...DEFAULT_LAYOUT_CONFIG.sectionOrder],
			signatures: { ...DEFAULT_LAYOUT_CONFIG.signatures },
			seal: { ...DEFAULT_LAYOUT_CONFIG.seal },
			stamp: { ...DEFAULT_LAYOUT_CONFIG.stamp },
			sender: {
				...DEFAULT_LAYOUT_CONFIG.sender,
				signature: { ...DEFAULT_LAYOUT_CONFIG.sender.signature },
				stamp: { ...DEFAULT_LAYOUT_CONFIG.sender.stamp },
			},
			closingAssetOrder: [...DEFAULT_LAYOUT_CONFIG.closingAssetOrder],
			absoluteAssetOrder: [...DEFAULT_LAYOUT_CONFIG.absoluteAssetOrder],
			positionsByLanguage: buildDefaultPositionsByLanguage(),
		};
	}

	const record = value as Record<string, unknown>;
	const seen = new Set<LetterLayoutSectionKey>();
	const order: LetterLayoutSectionKey[] = [];

	if (Array.isArray(record.sectionOrder)) {
		for (const item of record.sectionOrder) {
			if (!isSectionKey(item) || seen.has(item)) continue;
			seen.add(item);
			order.push(item);
		}
	}

	for (const key of ALL_SECTION_KEYS) {
		if (!seen.has(key)) order.push(key);
	}

	const signatures =
		record.signatures != null &&
		typeof record.signatures === "object" &&
		!Array.isArray(record.signatures)
			? (record.signatures as Record<string, unknown>)
			: {};
	const seal =
		record.seal != null &&
		typeof record.seal === "object" &&
		!Array.isArray(record.seal)
			? (record.seal as Record<string, unknown>)
			: {};
	const stamp =
		record.stamp != null &&
		typeof record.stamp === "object" &&
		!Array.isArray(record.stamp)
			? (record.stamp as Record<string, unknown>)
			: {};
	const sender =
		record.sender != null &&
		typeof record.sender === "object" &&
		!Array.isArray(record.sender)
			? (record.sender as Record<string, unknown>)
			: {};

	const flatFromRecord: LetterClosingLanguagePositions = {
		signatures: toAbsolutePayloadPosition(
			normalizeLayoutPositionValue(signatures.position, "signatures"),
		) as unknown as LayoutPositionValue,
		seal: toAbsolutePayloadPosition(
			normalizeLayoutPositionValue(seal.position, "seal"),
		) as unknown as LayoutPositionValue,
		stamp: toAbsolutePayloadPosition(
			normalizeLayoutPositionValue(stamp.position, "stamp"),
		) as unknown as LayoutPositionValue,
	};
	const positionsByLanguage = parsePositionsByLanguage(record, flatFromRecord);

	return {
		sectionOrder: order,
		signatures: {
			widthPt: parsePositiveNumber(
				signatures.widthPt,
				DEFAULT_LAYOUT_CONFIG.signatures.widthPt,
			),
			heightPx: parsePositiveNumber(
				signatures.heightPx,
				DEFAULT_LAYOUT_CONFIG.signatures.heightPx,
			),
			gapPx: parsePositiveNumber(
				signatures.gapPx,
				DEFAULT_LAYOUT_CONFIG.signatures.gapPx,
			),
			align: parseAlign(
				signatures.align,
				DEFAULT_LAYOUT_CONFIG.signatures.align,
			),
			position: { ...positionsByLanguage.am.signatures },
		},
		seal: {
			widthPx: parsePositiveNumber(
				seal.widthPx,
				DEFAULT_LAYOUT_CONFIG.seal.widthPx,
			),
			heightPx: parsePositiveNumber(
				seal.heightPx,
				DEFAULT_LAYOUT_CONFIG.seal.heightPx,
			),
			position: { ...positionsByLanguage.am.seal },
		},
		stamp: {
			widthPt: parsePositiveNumber(
				stamp.widthPt,
				DEFAULT_LAYOUT_CONFIG.stamp.widthPt,
			),
			heightPx: parsePositiveNumber(
				stamp.heightPx,
				DEFAULT_LAYOUT_CONFIG.stamp.heightPx,
			),
			placement: parseStampPlacement(stamp.placement),
			position: { ...positionsByLanguage.am.stamp },
		},
		sender: {
			align: parseAlign(sender.align, DEFAULT_LAYOUT_CONFIG.sender.align),
			assetOrder: parseSenderAssetOrder(sender.assetOrder),
			signature: toAbsolutePayloadPosition(
				normalizeLayoutPositionValue(sender.signature, "senderSignature"),
			) as unknown as LayoutPositionValue,
			stamp: toAbsolutePayloadPosition(
				normalizeLayoutPositionValue(sender.stamp, "senderStamp"),
			) as unknown as LayoutPositionValue,
		},
		closingAssetOrder: parseClosingAssetOrder(record.closingAssetOrder),
		absoluteAssetOrder: normalizeAbsoluteAssetOrder(record.absoluteAssetOrder),
		positionsByLanguage,
	};
}

export function isLayoutConfigSetting(code: string): boolean {
	return code.trim().toLowerCase() === LAYOUT_CONFIG_SETTING_CODE;
}

interface LayoutConfigEditorProps {
	setting: TemplateSampleSetting;
	isDefault: boolean;
	onToggleDefault: (settingId: string) => void;
	value: LetterLayoutConfigValue;
	onChange: (value: LetterLayoutConfigValue) => void;
	appliesTo?: { en: string; am: string };
	pageMargin?: PageMarginValue;
	placementLanguage?: LetterLanguage;
	placementFocusNonce?: number;
	/** Record override panel: inherit unit values but keep controls enabled. */
	editorMode?: "template" | "record";
	/** Larger canvas when embedded in record preview dialog. */
	canvasLayoutMode?: "default" | "preview";
}

export const LayoutConfigEditor: React.FC<LayoutConfigEditorProps> = ({
	setting,
	isDefault,
	onToggleDefault,
	value,
	onChange,
	appliesTo,
	pageMargin,
	placementLanguage = "am",
	placementFocusNonce = 0,
	editorMode = "template",
	canvasLayoutMode = "default",
}) => {
	const { t, i18n } = useTranslation();
	const displayLang = i18n.language?.startsWith("am") ? "am" : "en";
	const isRecordMode = editorMode === "record";
	const controlsDisabled = isDefault && !isRecordMode;

	const sectionLabels = useMemo(
		(): Record<LetterLayoutSectionKey, string> => ({
			reference: t("template.sectionReference", "Reference & date"),
			receivers: t("template.sectionReceivers", "Receivers"),
			sender: t("template.sectionSender", "Sender"),
			subject: t("template.sectionSubject", "Subject"),
			body: t("template.sectionBody", "Body"),
			closing: t("template.sectionClosing", "Closing & signatures"),
			cc: t("template.sectionCc", "CC"),
			forYourReference: t(
				"template.sectionForYourReference",
				"For your reference",
			),
		}),
		[t],
	);

	const moveSection = useCallback(
		(index: number, direction: -1 | 1) => {
			const nextIndex = index + direction;
			if (nextIndex < 0 || nextIndex >= value.sectionOrder.length) return;
			const order = [...value.sectionOrder];
			const [item] = order.splice(index, 1);
			order.splice(nextIndex, 0, item);
			onChange({ ...value, sectionOrder: order });
		},
		[value, onChange],
	);

	const alignLabels = useMemo(
		(): Record<LetterLayoutHorizontalAlign, string> => ({
			auto: t("template.alignAuto", "Auto (language default)"),
			start: t("template.alignStart", "Start (left)"),
			center: t("template.alignCenter", "Center"),
			end: t("template.alignEnd", "End (right)"),
		}),
		[t],
	);

	const updateNumber = useCallback(
		(
			group: "signatures" | "seal" | "stamp",
			field: string,
			raw: string,
		) => {
			const parsed = Number.parseFloat(raw);
			const num = Number.isNaN(parsed) ? 1 : Math.max(1, parsed);
			onChange({
				...value,
				[group]: {
					...value[group],
					[field]: num,
				},
			});
		},
		[value, onChange],
	);

	return (
		<div
			className={
				isRecordMode
					? "min-w-0 flex flex-col flex-1 min-h-0"
					: "mt-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600 space-y-6"
			}
		>
			{!isRecordMode && (
			<div className="flex items-center justify-between gap-4">
				<div>
					<h4 className="text-sm font-medium text-gray-700 dark:text-gray-200">
						{t("template.letterLayout", "Letter Layout")}
					</h4>
					{appliesTo && (
						<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
							{t("template.appliesTo", "Applies to")}: {appliesTo[displayLang]}
						</p>
					)}
					<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
						{t(
							"template.letterLayoutHint",
							"Place signatures, seal, and stamp on the page canvas first, then adjust sizes and section order below.",
						)}
					</p>
				</div>
				<label className="flex items-center gap-2 cursor-pointer shrink-0">
					<input
						type="checkbox"
						checked={isDefault}
						onChange={() => onToggleDefault(setting.id)}
						className="w-4 h-4 rounded border-gray-300 dark:border-gray-500"
					/>
					<span className="text-xs font-medium text-gray-600 dark:text-gray-300">
						{isDefault
							? t("template.useGlobalDefault", "Use template default")
							: t("template.unitOverride", "Unit override")}
					</span>
				</label>
			</div>
			)}

			<fieldset
				disabled={controlsDisabled}
				className={`border-0 p-0 m-0 min-w-0 ${controlsDisabled ? "opacity-60" : ""} ${
					isRecordMode
						? "flex flex-col flex-1 min-h-0 space-y-3"
						: "space-y-6"
				}`}
			>
				{!isRecordMode && (
					<div className="flex flex-wrap items-center gap-2">
						<span className="text-xs text-gray-600 dark:text-gray-300">
							{t("template.placementLanguage", "Placement language")}:{" "}
							<strong>
								{placementLanguage === "am"
									? t("template.languageAm", "Amharic")
									: t("template.languageEn", "English")}
							</strong>
						</span>
						<button
							type="button"
							disabled={controlsDisabled}
							onClick={() =>
								onChange({
									...value,
									positionsByLanguage: {
										...value.positionsByLanguage,
										en: { ...value.positionsByLanguage.am },
									},
								})
							}
							className="px-2 py-1 text-xs rounded border border-gray-300 dark:border-gray-500 disabled:opacity-40"
						>
							{t("template.copyAmToEnPositions", "Copy Amharic → English")}
						</button>
					</div>
				)}

				<LetterAssetsPlacementCanvas
					value={value}
					onChange={onChange}
					disabled={controlsDisabled}
					pageMargin={pageMargin}
					placementLanguage={placementLanguage}
					placementFocusNonce={placementFocusNonce}
					layoutMode={
						canvasLayoutMode !== "default"
							? canvasLayoutMode
							: isRecordMode
								? "preview"
								: "default"
					}
				/>

				{!isRecordMode && (
				<>
				<div className="border-t border-gray-200 pt-6 dark:border-gray-600">
					<h5 className="mb-1 text-xs font-semibold uppercase tracking-wide text-gray-600 dark:text-gray-300">
						{t("template.layoutOptions", "Layout options")}
					</h5>
					<p className="mb-4 text-xs text-gray-500 dark:text-gray-400">
						{t(
							"template.layoutOptionsHint",
							"Optional: reorder letter sections and fine-tune asset dimensions.",
						)}
					</p>
				</div>
				<div>
					<h5 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-2 uppercase tracking-wide">
						{t("template.sectionOrder", "Section order")}
					</h5>
					<ul className="space-y-2">
						{value.sectionOrder.map((key, index) => (
							<li
								key={key}
								className="flex items-center justify-between gap-2 px-3 py-2 bg-white dark:bg-gray-800 rounded border border-gray-200 dark:border-gray-600"
							>
								<span className="text-sm text-gray-700 dark:text-gray-200">
									{index + 1}. {sectionLabels[key]}
								</span>
								<div className="flex gap-1 shrink-0">
									<button
										type="button"
										onClick={() => moveSection(index, -1)}
										disabled={index === 0}
										className="px-2 py-1 text-xs rounded border border-gray-300 dark:border-gray-500 disabled:opacity-40"
										aria-label={t("template.moveUp", "Move up")}
									>
										↑
									</button>
									<button
										type="button"
										onClick={() => moveSection(index, 1)}
										disabled={index === value.sectionOrder.length - 1}
										className="px-2 py-1 text-xs rounded border border-gray-300 dark:border-gray-500 disabled:opacity-40"
										aria-label={t("template.moveDown", "Move down")}
									>
										↓
									</button>
								</div>
							</li>
						))}
					</ul>
				</div>

				<div className="grid grid-cols-2 gap-4">
					<div className="col-span-2">
						<h5 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-2 uppercase tracking-wide">
							{t("template.signatures", "Signatures")}
						</h5>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.signatureWidth", "Width (pt)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.signatures.widthPt}
							onChange={(e) =>
								updateNumber("signatures", "widthPt", e.target.value)
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.signatureHeight", "Height (px)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.signatures.heightPx}
							onChange={(e) =>
								updateNumber("signatures", "heightPx", e.target.value)
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.signatureGap", "Gap (px)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.signatures.gapPx}
							onChange={(e) =>
								updateNumber("signatures", "gapPx", e.target.value)
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
					<div className="col-span-2">
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.closingAlign", "Closing block horizontal position")}
						</label>
						<select
							value={value.signatures.align}
							onChange={(e) =>
								onChange({
									...value,
									signatures: {
										...value.signatures,
										align: e.target.value as LetterLayoutHorizontalAlign,
									},
								})
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						>
							{HORIZONTAL_ALIGNS.map((align) => (
								<option key={align} value={align}>
									{alignLabels[align]}
								</option>
							))}
						</select>
					</div>
				</div>

				<div className="grid grid-cols-2 gap-4">
					<div className="col-span-2">
						<h5 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-2 uppercase tracking-wide">
							{t("template.seal", "Seal")}
						</h5>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.sealWidth", "Width (px)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.seal.widthPx}
							onChange={(e) => updateNumber("seal", "widthPx", e.target.value)}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.sealHeight", "Height (px)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.seal.heightPx}
							onChange={(e) =>
								updateNumber("seal", "heightPx", e.target.value)
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
				</div>

				<div className="grid grid-cols-2 gap-4">
					<div className="col-span-2">
						<h5 className="text-xs font-semibold text-gray-600 dark:text-gray-300 mb-2 uppercase tracking-wide">
							{t("template.stamp", "Stamp (teeter)")}
						</h5>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.stampWidth", "Width (pt)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.stamp.widthPt}
							onChange={(e) =>
								updateNumber("stamp", "widthPt", e.target.value)
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
					<div>
						<label className="block text-xs font-medium text-gray-600 dark:text-gray-300 mb-1">
							{t("template.stampHeight", "Height (px)")}
						</label>
						<input
							type="number"
							min={1}
							value={value.stamp.heightPx}
							onChange={(e) =>
								updateNumber("stamp", "heightPx", e.target.value)
							}
							className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:text-gray-100 rounded-lg text-sm"
						/>
					</div>
				</div>
				</>
				)}
			</fieldset>
		</div>
	);
};
