import { tick } from 'svelte';

const LINE_PREFIX = /^line\[\d+\]\./i;

/** Strip `line[N].` prefix so the caller gets a plain suffix like `quantity.quantity`. */
export function normalizeLineItemFieldPath(raw: string): string {
	return (raw || '').replace(LINE_PREFIX, '').replace(/^body\./i, '').trim();
}

export type ItemSheetTabValue =
	| 'generales'
	| 'continuacion'
	| 'series'
	| 'etiquetado'
	| 'identificadores';

interface FieldMapping {
	id: string;
	tab: ItemSheetTabValue;
}

/** Maps API field-path suffixes (after stripping `line[N].`) to focusable DOM elements. */
export const FIELD_PATH_TO_DOM_ID: Record<string, FieldMapping> = {
	class_id: { id: 'clase', tab: 'generales' },
	unit_of_measure: { id: 'um', tab: 'generales' },
	'quantity.quantity': { id: 'cantidad', tab: 'generales' },
	'quantity.net_weight': { id: 'peso_neto', tab: 'generales' },
	'quantity.gross_weight': { id: 'peso_bruto', tab: 'generales' },
	'financial.unit_cost_capture': { id: 'costo_unitario', tab: 'generales' },
	'customs.fraction': { id: 'fraccion', tab: 'generales' },
	'customs.fraction_type': { id: 'tipo_tarifa', tab: 'generales' },
	'customs.origin_country': { id: 'pais_origen', tab: 'generales' },
	'customs.american_fraction': { id: 'fraccion_americana', tab: 'generales' },
	'description.description_spanish': { id: 'desc_espanol', tab: 'generales' },
	'description.description_english': { id: 'desc_ingles', tab: 'generales' },
	'fa_data.subitem_number': { id: 'subitem_number', tab: 'generales' },
};

/**
 * Switches to the right sheet tab (if needed) and focuses the field that maps to `fieldPath`.
 * `fieldPath` should be the normalized suffix (e.g. `quantity.quantity`), not the raw API path.
 * Returns `true` when focus succeeded, `false` when the path is unknown or element not found.
 */
export async function focusItemSheetField(
	fieldPath: string,
	setActiveTab?: (tab: ItemSheetTabValue) => void
): Promise<boolean> {
	const mapping = FIELD_PATH_TO_DOM_ID[fieldPath];
	if (!mapping) return false;

	if (setActiveTab) {
		setActiveTab(mapping.tab);
		await tick();
		await new Promise<void>((r) => requestAnimationFrame(() => r()));
	}

	const root = document.querySelector('[data-invoice-item-sheet="fixed_asset"]');
	const el = root
		? root.querySelector<HTMLElement>(`#${mapping.id}`)
		: (document.getElementById(mapping.id) as HTMLElement | null);
	if (!el) return false;

	el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });
	try {
		el.focus({ preventScroll: true });
	} catch {
		try {
			el.focus();
		} catch {
			/* non-focusable element */
		}
	}

	return true;
}
