///
/// Checks if instance exists in selector familiy tree, falls back from current selector
///
/// @access private
///
/// @param {String} $key    - breakpoint key to search for matching instance
/// @param {String} $syntax - searches for instance using passed syntax parser
///
/// @return {String|False} instance selector
///
/// @group Internal Functions
///
@function flint-has-family-instance($key: flint-get-value("settings", "default"), $syntax: $flint-support-syntax) {
	$selector: nth(&, 1);

	@if not $key or not $selector {
		@return false;
	}

	// Check if instance result had been cached
	@if map-has-key($flint-cached-instances, "#{$selector}") {
		// Get cached instance
		$cached-instance: map-get($flint-cached-instances, "#{$selector}");
		// Return with current key
		@return "#{$cached-instance}::#{$key}";
	}

	// Check for syntax support, try to find instance using it
	@if $syntax {

		$parsed-selector: flint-use-syntax($selector);
		$length: length($parsed-selector);

		// Loop through transformed selectors
		@for $i from 1 through $length {

			// Check last selector in list
			@if map-has-key($flint-instances, "#{flint-last($parsed-selector)}::#{$key}") {

				// Cache result
				$flint-cached-instances: map-merge($flint-cached-instances, ("#{$selector}": "#{flint-last($parsed-selector)}")) !global;

				// Return the matching instance key
				@return "#{flint-last($parsed-selector)}::#{$key}";

			} @else {

				// Else, remove the last selector and loop again
				$parsed-selector: flint-remove($parsed-selector, flint-last($parsed-selector));

			}
		}

		// Search for a parent instance normally
		@return flint-has-family-instance($key, null);

	} @else {
		$selector-list: $selector;
		$length: length($selector-list);

		// Loop through length of list of selectors
		@for $i from 1 through $length {
			$selector-string: flint-list-to-str($selector-list, " ");

			// Make sure that we're not counting the current selector set
			@if map-has-key($flint-instances, "#{$selector-string}::#{$key}") and $selector != $selector-list {

				// Cache result
				$flint-cached-instances: map-merge($flint-cached-instances, ("#{$selector}": "#{$selector-string}")) !global;

				// Return the matching instance key
				@return "#{$selector-string}::#{$key}";

			} @else {

				// Else, remove the last selector and loop again
				$selector-list: flint-remove($selector-list, flint-last($selector-list));

			}
		}

		@return false;
	}
}
