﻿find_title_for_almohad_spawn_effect = {
	if = { # The important thing is to not mess too much with players who can't resist
		limit = {
			title:c_tinmallal = {
				holder = { is_ai = yes }
				OR = {
					NOT = { exists = duchy.holder }
					duchy.holder = { is_ai = yes }
				}
			}
		}
		title:c_tinmallal = {
			save_scope_as = almohad_county
		}
	}
	else = {
		title:k_maghreb = {
			random_in_de_jure_hierarchy = {
				continue = { tier > tier_county }
				limit = {
					tier = tier_county
					holder = { is_ai = yes } # Let's not murder players
					NOT = { this = title:c_marrakesh }
					save_temporary_scope_as = potential_almohad_county
					# If someone holds k_maghreb, put the Almohads in their realm
					trigger_if = {
						limit = { exists = title:k_maghreb.holder }
						title:k_maghreb.holder = {
							OR = {
								this = scope:potential_almohad_county.holder
								any_sub_realm_county = {
									this = scope:potential_almohad_county
								}
							}
						}
					}
					# Either this should be the holder's only title, or it should NOT be their capital
					trigger_if = {
						limit = {
							holder = {
								any_sub_realm_county = { count > 1 }
							}
						}
						NOT = {
							this = holder.capital_county
						}
					}
				}
				weight = {
					base = 1
					# Prefer already Muslim counties
					modifier = {
						add = 5
						religion = religion:islam_religion
					}
					# Massively prefer to avoid a player-held Duchies if possible
					modifier = {
						factor = 0.01
						exists = duchy.holder
						duchy.holder = { is_ai = no }
					}
				}
				save_scope_as = almohad_county
			}
		}
	}

	if = { # Discard stuff from here on out
		limit = { NOT = { exists = scope:almohad_county } }
		debug_log = "No Almohad title found, Almohad's won't spawn"
	}
	# Convert the County and warn relevant people
	else = {
		set_global_variable = {
			name = spawned_almohads
			value = yes
		}
		scope:almohad_county = {
			E_kCAFG_convert_faith_in_all_county_provinces = {
				FACTOR = 0.8
				VARIANCE = 0.1
				FAITH = faith:masmudi
				MAX = 1
			}
		}
		scope:almohad_county.holder = {
			if = {
				limit = {
					is_ai = no
				}
				trigger_event = almohad.1001
			}
			every_liege_or_above = {
				limit = { is_ai = no }
				trigger_event = almohad.1001
			}
		}
		trigger_event = { # Random amount of time to convert the province or otherwise prepare
			id = almohad.0002
			days = { 400 1000 }
		}
	}
}
