import { tick } from 'svelte';

export type InvoiceEditTab = 'general' | 'observations' | 'items' | 'others' | 'continuation';

/** Normalized keys used for highlight + registry (must match DOM ids where possible). */
export const ITEMS_LINE_PLACEHOLDER = '__items_line__';

const LINE_BRACKET = /^line\[(\d+)\]\.(.+)$/i;

/**
 * Normalize API/client field paths to a focus registry key / highlight id.
 */
export function normalizeInvoiceFieldPath(raw: string | undefined | null): string {
	if (raw == null || String(raw).trim() === '') return '';
	let s = String(raw).trim().replace(/^body\./i, '');

	if (LINE_BRACKET.test(s)) {
		return ITEMS_LINE_PLACEHOLDER;
	}

	const lower = s.toLowerCase();
	if (lower.startsWith('compliance_mx.aduana')) return 'aduana';
	if (lower.startsWith('compliance_mx.pedimento_id')) return 'pedimento';
	if (lower.startsWith('logistics.')) {
		return s.slice('logistics.'.length);
	}
	if (lower.startsWith('financials.')) {
		const tail = s.slice('financials.'.length);
		if (tail === 'exchange_rate' || tail.includes('exchange_rate')) return 'currency-foreign';
		return tail;
	}

	const lastDot = s.lastIndexOf('.');
	if (lastDot !== -1) {
		s = s.slice(lastDot + 1);
	}

	return s;
}

export type FocusResolution = {
	tab: InvoiceEditTab | null;
	elementId: string;
};

const REGISTRY: Record<string, FocusResolution> = {
	operation_type: { tab: null, elementId: 'invoice-field-operation_type' },
	invoice_type: { tab: null, elementId: 'invoice-field-invoice_type' },
	invoice_number: { tab: null, elementId: 'invoice_number' },
	invoice_date: { tab: null, elementId: 'invoice_date' },
	emission_date: { tab: null, elementId: 'emission_date' },
	invoice_id: { tab: null, elementId: 'invoice_number' },
	document_type: { tab: 'general', elementId: 'document_type' },
	aduana: { tab: 'general', elementId: 'aduana' },
	trailer_num: { tab: 'general', elementId: 'trailer_num' },
	transport_type: { tab: 'general', elementId: 'transport_type' },
	provider_id: { tab: 'general', elementId: 'provider_id' },
	provider_header: { tab: 'general', elementId: 'provider_header' },
	sold_to_header: { tab: 'general', elementId: 'sold_to_header' },
	sold_to_id: { tab: 'general', elementId: 'sold_to_id' },
	shipped_to_header: { tab: 'general', elementId: 'shipped_to_header' },
	shipped_to_id: { tab: 'general', elementId: 'shipped_to_id' },
	customs_broker_id: { tab: 'general', elementId: 'customs_broker_id' },
	pedimento: { tab: null, elementId: 'pedimento' },
	pedimento_id: { tab: null, elementId: 'pedimento' },
	remesa: { tab: null, elementId: 'remesa' },
	observation_es: { tab: 'observations', elementId: 'observation_es' },
	observation_en: { tab: 'observations', elementId: 'observation_en' },
	freight: { tab: 'observations', elementId: 'freight' },
	incoterm: { tab: 'observations', elementId: 'incoterm' },
	manifest_number: { tab: 'general', elementId: 'manifest_number' },
	carrier_id: { tab: 'general', elementId: 'carrier_id' },
	transport_id: { tab: 'general', elementId: 'transport_id' },
	driver_name: { tab: 'general', elementId: 'driver_name' },
	currency_type: { tab: 'general', elementId: 'currency_type' },
	weight_type: { tab: 'general', elementId: 'weight_type' },
	iva_factor: { tab: 'general', elementId: 'iva_factor' },
	customs_broker_us_id: { tab: 'general', elementId: 'customs_broker_us_id' },
	'currency-foreign': { tab: 'general', elementId: 'currency-foreign' },
	exchange_rate: { tab: 'general', elementId: 'currency-foreign' },
	[ITEMS_LINE_PLACEHOLDER]: { tab: 'items', elementId: 'invoice-items-tab-root' }
};

export function resolveInvoiceFocusTarget(normalizedKey: string): FocusResolution | null {
	if (!normalizedKey) return null;
	const direct = REGISTRY[normalizedKey];
	if (direct) return direct;
	return null;
}

/**
 * Switches tab when needed, scrolls to and focuses the target control.
 */
export async function focusInvoiceInvalidField(
	setTab: (t: InvoiceEditTab) => void,
	fieldPath: string | undefined
): Promise<boolean> {
	const norm = normalizeInvoiceFieldPath(fieldPath || '');
	const target = resolveInvoiceFocusTarget(norm);
	if (!target) return false;

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

	const el = document.getElementById(target.elementId);
	if (!el) return false;

	el.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' });

	try {
		(el as HTMLElement).focus({ preventScroll: true });
	} catch {
		try {
			(el as HTMLElement).focus();
		} catch {
			/* non-focusable */
		}
	}

	return true;
}
