import { getLocale } from '$lib/paraglide/runtime';

type VehiclesLocale = 'es' | 'en';

const MESSAGES = {
	es: {
		shortcuts_scope: 'Vehículos (transporte)',
		shortcuts_save: 'Guardar',
		page_title: 'Vehículos (Transporte)',
		page_subtitle: 'Gestión del catálogo de camiones y vehículos de transporte',
		new_vehicle: 'Nuevo Vehículo',
		vehicle_list: 'Listado de Vehículos',
		search_key: 'Clave',
		search_plate: 'Placas',
		loading_vehicles: 'Cargando vehículos...',
		showing_records: 'Mostrando {shown} de {total} registros',
		edit: 'Editar',
		delete: 'Eliminar',
		delete_confirm: '¿Estás seguro de eliminar el vehículo "{key}"?\n\nNota: No se puede eliminar si tiene registros relacionados.',
		delete_error_title: '❌ Error al eliminar:',
		delete_success: '✅ Vehículo eliminado correctamente',
		col_key: 'Clave',
		col_brand: 'Marca',
		col_year: 'Año',
		col_plate: 'Placas',
		col_transporter: 'Transportista',
		col_transport_type: 'Tipo Transporte',
		col_actions: 'Acciones',
		menu_open: 'Abrir menú',
		menu_actions: 'Acciones',
		session_expired: 'Sesión expirada. Recargando página...',
		no_company_error: '❌ Error: No hay una compañía seleccionada',
		delete_generic_error: 'Error al eliminar',
		delete_error_alert: '❌ Error: {error}',
		delete_success_item: '✅ Vehículo "{key}" eliminado correctamente',
		dialog_edit_title: 'Editar Vehículo',
		dialog_new_title: 'Nuevo Vehículo',
		dialog_edit_description: 'Modifica los datos del vehículo',
		dialog_new_description: 'Completa los datos para crear un nuevo vehículo de transporte',
		tab_general: 'Información General',
		tab_details: 'Seguro y Detalles',
		section_vehicle_identification: 'Identificación del Vehículo',
		label_vehicle_key: 'Clave del Vehículo',
		placeholder_vehicle_key: 'Ej: VH001',
		label_brand: 'Marca',
		placeholder_brand: 'Ej: Kenworth',
		label_year: 'Año',
		placeholder_year: 'YYYY',
		label_plate_number: 'Placas',
		placeholder_plate_number: 'Placas actuales',
		label_series: 'Serie / VIN',
		placeholder_series: 'Número de serie',
		section_transport_data: 'Datos de Transporte',
		label_transporter: 'Transportista',
		select_transporter: '— Seleccionar transportista —',
		empty: '— Vacío —',
		label_transport_identifier: 'ID Transporte',
		placeholder_transport_identifier: 'Identificador único',
		label_transport_type: 'Tipo de Transporte',
		optional: '— Opcional —',
		label_entity_code: 'Código de Entidad',
		no_code: '— Sin código —',
		entity_required_hint: 'Obligatorio al crear (reglas CSV)',
		label_sct_permission: 'Permiso SCT',
		placeholder_sct_permission: 'Número de permiso',
		section_insurance: 'Seguro y Otros',
		label_insurance_company: 'Aseguradora',
		placeholder_insurance_company: 'Nombre de la compañía',
		label_insurance_number: 'Póliza',
		placeholder_insurance_number: 'Número de póliza',
		label_insurance_amount: 'Monto',
		label_dot_number: 'Número DOT',
		label_country: 'País (AME)',
		label_state: 'Estado',
		select_state: '— Selecciona —',
		select_country_first: '— Primero el país —',
		label_city: 'Ciudad',
		placeholder_city: 'Ciudad/Localidad',
		label_color: 'Color',
		placeholder_color: 'Color del vehículo',
		label_container_type: 'Tipo Contenedor',
		placeholder_container_type: 'Ej: 40G',
		section_location: 'Ubicación y Detalles',
		label_additional_description: 'Descripción Adicional',
		placeholder_additional_description: 'Notas adicionales sobre el vehículo...',
		cancel: 'Cancelar',
		saving: 'Guardando...',
		update: 'Actualizar',
		create: 'Crear',
		no_company_selected: 'No hay una compañía seleccionada',
		vehicle_key_required: 'La clave del vehículo es requerida',
		save_error: 'Error al guardar el vehículo',
		transport_types: {
			AR: 'Camión Blindado',
			AU: 'Automóviles',
			BT: 'Camión de Caja',
			BU: 'Autobús',
			BV: 'Camión de Bebidas',
			BY: 'Bicicleta',
			CO: 'Vehículo de Construcción',
			EV: 'Vehículo de Emergencia',
			FE: 'Ferry',
			FM: 'Tractor Agrícola',
			GB: 'Camión de Basura',
			MC: 'Motocicleta',
			OC: 'Otro',
			PM: 'Camioneta con cabina',
			PN: 'Camión Panel',
			PU: 'Camioneta (Pick-up)',
			PV: 'Pasajero',
			RV: 'Vehículo Recreativo (RV)',
			TR: 'Tractocamión',
			TV: 'Van'
		}
	},
	en: {
		shortcuts_scope: 'Vehicles (transport)',
		shortcuts_save: 'Save',
		page_title: 'Vehicles (Transport)',
		page_subtitle: 'Transport trucks and vehicles catalog management',
		new_vehicle: 'New Vehicle',
		vehicle_list: 'Vehicle List',
		search_key: 'Key',
		search_plate: 'Plates',
		loading_vehicles: 'Loading vehicles...',
		showing_records: 'Showing {shown} of {total} records',
		edit: 'Edit',
		delete: 'Delete',
		delete_confirm: 'Are you sure you want to delete vehicle "{key}"?\n\nNote: It cannot be deleted if it has related records.',
		delete_error_title: '❌ Error deleting:',
		delete_success: '✅ Vehicle deleted successfully',
		col_key: 'Key',
		col_brand: 'Brand',
		col_year: 'Year',
		col_plate: 'Plates',
		col_transporter: 'Transporter',
		col_transport_type: 'Transport Type',
		col_actions: 'Actions',
		menu_open: 'Open menu',
		menu_actions: 'Actions',
		session_expired: 'Session expired. Reloading page...',
		no_company_error: '❌ Error: No company selected',
		delete_generic_error: 'Error deleting',
		delete_error_alert: '❌ Error: {error}',
		delete_success_item: '✅ Vehicle "{key}" deleted successfully',
		dialog_edit_title: 'Edit Vehicle',
		dialog_new_title: 'New Vehicle',
		dialog_edit_description: 'Modify vehicle data',
		dialog_new_description: 'Complete the data to create a new transport vehicle',
		tab_general: 'General Information',
		tab_details: 'Insurance and Details',
		section_vehicle_identification: 'Vehicle Identification',
		label_vehicle_key: 'Vehicle Key',
		placeholder_vehicle_key: 'Eg: VH001',
		label_brand: 'Brand',
		placeholder_brand: 'Eg: Kenworth',
		label_year: 'Year',
		placeholder_year: 'YYYY',
		label_plate_number: 'Plates',
		placeholder_plate_number: 'Current plates',
		label_series: 'Series / VIN',
		placeholder_series: 'Serial number',
		section_transport_data: 'Transport Data',
		label_transporter: 'Transporter',
		select_transporter: '— Select transporter —',
		empty: '— Empty —',
		label_transport_identifier: 'Transport ID',
		placeholder_transport_identifier: 'Unique identifier',
		label_transport_type: 'Transport Type',
		optional: '— Optional —',
		label_entity_code: 'Entity Code',
		no_code: '— No code —',
		entity_required_hint: 'Required on create (CSV rules)',
		label_sct_permission: 'SCT Permit',
		placeholder_sct_permission: 'Permit number',
		section_insurance: 'Insurance and Others',
		label_insurance_company: 'Insurance Company',
		placeholder_insurance_company: 'Company name',
		label_insurance_number: 'Policy',
		placeholder_insurance_number: 'Policy number',
		label_insurance_amount: 'Amount',
		label_dot_number: 'DOT Number',
		label_country: 'Country (AME)',
		label_state: 'State',
		select_state: '— Select —',
		select_country_first: '— Select country first —',
		label_city: 'City',
		placeholder_city: 'City/Location',
		label_color: 'Color',
		placeholder_color: 'Vehicle color',
		label_container_type: 'Container Type',
		placeholder_container_type: 'Eg: 40G',
		section_location: 'Location and Details',
		label_additional_description: 'Additional Description',
		placeholder_additional_description: 'Additional notes about the vehicle...',
		cancel: 'Cancel',
		saving: 'Saving...',
		update: 'Update',
		create: 'Create',
		no_company_selected: 'No company selected',
		vehicle_key_required: 'Vehicle key is required',
		save_error: 'Error saving vehicle',
		transport_types: {
			AR: 'Armored Truck',
			AU: 'Automobiles',
			BT: 'Box Truck',
			BU: 'Bus',
			BV: 'Beverage Truck (Refer or not)',
			BY: 'Bicycle',
			CO: 'Construction Vehicle (general)',
			EV: 'Emergency Vehicle (general)',
			FE: 'Ferry',
			FM: 'Farm Tractor',
			GB: 'Garbage Truck',
			MC: 'Motorcycle',
			OC: 'Other',
			PM: 'Pick-up Truck w/camper',
			PN: 'Panel Truck',
			PU: 'Pickup Truck',
			PV: 'Passenger',
			RV: 'Recreation Vehicle (RV)',
			TR: 'Semi Tracker',
			TV: 'Van'
		}
	}
} as const;

export type VehiclesMessageKey = Exclude<keyof (typeof MESSAGES)['es'], 'transport_types'>;

function activeLocale(): VehiclesLocale {
	if (typeof window !== 'undefined') {
		const htmlLang = document.documentElement?.lang?.toLowerCase() || '';
		if (htmlLang.startsWith('es')) return 'es';
		if (htmlLang.startsWith('en')) return 'en';

		const storedLocaleCandidates = [
			window.localStorage.getItem('locale'),
			window.localStorage.getItem('lang'),
			window.localStorage.getItem('language')
		]
			.filter(Boolean)
			.map((value) => String(value).toLowerCase());

		if (storedLocaleCandidates.some((value) => value.startsWith('es'))) return 'es';
		if (storedLocaleCandidates.some((value) => value.startsWith('en'))) return 'en';
	}

	return getLocale().startsWith('es') ? 'es' : 'en';
}

export function tv(key: VehiclesMessageKey, vars?: Record<string, string | number>): string {
	const locale = activeLocale();
	let text = MESSAGES[locale][key] as string;
	if (!vars) return text;
	for (const [name, value] of Object.entries(vars)) {
		text = text.replaceAll(`{${name}}`, String(value));
	}
	return text;
}

export function tvTransportType(code?: string, fallback?: string): string {
	const normalizedCode = (code || '').trim().toUpperCase();
	if (!normalizedCode) return fallback || '';
	const locale = activeLocale();
	return MESSAGES[locale].transport_types[normalizedCode as keyof (typeof MESSAGES)['es']['transport_types']] || fallback || '';
}
