@import '@financial-times/math';
@import 'src/scss/variables';

@mixin oLazyLoad($opts: (
	'placeholder': true,
	'placeholder-ratios': $_o-lazy-load-placholder-ratios,
	'transition': true,
)) {
	/// Add a fade-in transition effect, works best for <img> or <picture> elements
	@if map-get($opts, 'transition') {
		.o-lazy-load--transition {
			opacity: 0;
			transition: opacity 0.25s;
			will-change: opacity;

			&[data-o-lazy-load] {
				opacity: 1;
			}
		}
	}

	/// Creates a placeholder to preserve space for lazy loaded content
	@if map-get($opts, 'placeholder') {
		.o-lazy-load-placeholder {
			position: relative;

			.o-lazy-load {
				position: absolute;
				top: 0;
				left: 0;
				// Images have implicit sizes so this forces them to fit the placeholder
				width: 100%;
				height: 100%;
				// IntersectionObserver requires a non-zero height
				min-height: 1px;
			}

			&:after {
				content: '';
				display: block;
			}
		}

		$ratios: map-get($opts, 'placeholder-ratios');
		$ratios: if($ratios, $ratios, ());
		@each $ratio in $ratios {
			$ratioX: nth($ratio, 1);
			$ratioY: nth($ratio, 2);

			.o-lazy-load-placeholder--#{$ratioX}x#{$ratioY} {
				&:after {
					padding-bottom: percentage(div(1, $ratioX) * $ratioY);
				}
			}
		}
	}
}

@if ($o-lazy-load-is-silent == false) {
	@include oLazyLoad();
	// Set to silent again to avoid being output twice
	$o-lazy-load-is-silent: true !global;
}
