﻿succession_crisis_process_vassal_loyalty_effect = {
	if = {
		limit = {
			NOT = { exists = scope:current_ruler }
		}
		scope:crisis_title = {
			holder = {
				save_scope_as = current_ruler
			}
		}
	}

	scope:current_ruler = {
		every_vassal_or_below = {
			limit = {
				# Basic Exclusions
				NOT = { this = scope:current_ruler }
				NOT = { this = scope:warleader }
				NOT = { this = scope:crisis_heir }
				NOT = { has_character_flag = pledged_to_ruler_flag }
				NOT = { has_character_flag = pledged_to_warleader_flag }

				# Performance Optimization: Only process relevant lords
				is_landed = yes
				
				# Tier-based restrictions based on crisis title
				trigger_if = {
					limit = {
						scope:crisis_title = {
							OR = {
								tier = tier_hegemony
								tier = tier_empire
							}
						}
					}
					highest_held_title_tier >= tier_duchy
				}
				trigger_if = {
					limit = {
						scope:crisis_title = {
							tier = tier_kingdom
						}
					}
					highest_held_title_tier >= tier_county
				}
				trigger_if = {
					limit = {
						scope:crisis_title = {
							tier < tier_kingdom
						}
					}
					highest_held_title_tier >= tier_county
				}
			}

			# Handle transition of temporary "pledged_to_heir" flag to permanent loyalty flags
			if = {
				limit = {
					has_character_flag = pledged_to_heir
					scope:crisis_heir = scope:current_ruler
				}
				remove_character_flag = pledged_to_heir
				add_character_flag = pledged_to_ruler_flag
			}
			else_if = {
				limit = {
					has_character_flag = pledged_to_heir
					scope:crisis_heir = scope:warleader
				}
				remove_character_flag = pledged_to_heir
				add_character_flag = pledged_to_warleader_flag
			}
			# Handle transition of temporary "pledged_to_claimant" flag to permanent loyalty flags
			# This only transitions automatically if the warleader IS the specific character they pledged to
			else_if = {
				limit = {
					has_character_flag = pledged_to_claimant
					exists = scope:crisis_special_character
					scope:crisis_special_character = scope:current_ruler
				}
				remove_character_flag = pledged_to_claimant
				add_character_flag = pledged_to_ruler_flag
			}
			else_if = {
				limit = {
					has_character_flag = pledged_to_claimant
					exists = scope:crisis_special_character
					scope:crisis_special_character = scope:warleader
				}
				remove_character_flag = pledged_to_claimant
				add_character_flag = pledged_to_warleader_flag
			}
			# If they have no valid transition (e.g., they pledged to a claimant who isn't the warleader, 
			# or they haven't pledged at all), send the event
			else = {
				trigger_event = {
					id = succession_crisis_vassal.0001
					days = { 10 30 }
				}
			}
		}
	}
}