/* eslint-disable no-undef */
// get the sticky element
const stickyDetector = document.querySelector( '#navbar-sticky-detector' );
const stickyElement = document.querySelector( '.navbar-main' );

const observer = new IntersectionObserver(
	( [ e ] ) => {
		stickyElement.classList.toggle( 'stuck', ! e.isIntersecting );
	},
	{
		rootMargin: '0px',
		threshold: [ 0.1 ],
	}
);

if ( stickyDetector ) {
	observer.observe( stickyDetector );
}

jQuery( function () {
	jQuery( '.show-leaflet' ).on( 'click', function () {
		const lat = jQuery( '.show-leaflet' ).data( 'lat' );
		const lon = jQuery( '.show-leaflet' ).data( 'lon' );
		const zoom = jQuery( '.show-leaflet' ).data( 'zoom' );

		showLeaflet( lat, lon, zoom );
	} );

	jQuery( '#privacy_policy_url' ).attr(
		'href',
		sunflower.privacy_policy_url
	);

	jQuery( '.show-search' ).on( 'click', function () {
		jQuery( '.topmenu .search input' ).toggleClass( 'active' );
		jQuery( '.topmenu .search input' ).trigger( 'focus' );
	} );

	jQuery( '.show-contrast' ).on( 'click', function () {
		jQuery( 'html' ).toggleClass( 'theme--contrast' );
		jQuery( 'html' ).toggleClass( 'theme--default' );
		localStorage.setItem(
			'theme--contrast',
			jQuery( 'html' ).hasClass( 'theme--contrast' )
		);
	} );

	if ( localStorage.getItem( 'theme--contrast' ) === 'true' ) {
		jQuery( 'html' ).addClass( 'theme--contrast' );
		jQuery( 'html' ).removeClass( 'theme--default' );
	}

	addRssReadMore();

	// mailto unscrambler
	jQuery( '[data-unscramble]' ).on( 'click', function () {
		const text = jQuery( this )
			.data( 'unscramble' )
			.split( '' )
			.reverse()
			.join( '' );
		window.location.href = 'MAILTO:' + text;

		return false;
	} );

	const IMG_EXT = /\.(jpe?g|png|gif|webp|svg)$/i;

	// add lightbox2 attributes to gallery blocks and remove them from linked images
	jQuery( '.wp-block-gallery figure' ).each( function () {
		// Fetch caption text, if available
		const $caption = jQuery( 'figcaption', this );
		const caption = $caption.length ? $caption.text().trim() : '';

		// Find first <a> in the figure, if it exists
		const $link = jQuery( 'a', this ).first();

		// If there's no link, this is a plain image without a lightbox, so we can skip it
		if ( ! $link.length ) {
			return;
		}

		// Fetch href attribute of the link to check if it points to an image file
		const href = $link.attr( 'href' );
		const isImage = href && IMG_EXT.test( href );

		// Skip lightbox setup if the link doesn't point to an image
		const hasExternalTarget =
			$link.attr( 'target' ) === '_blank' ||
			$link.attr( 'rel' )?.includes( 'external' );

		if ( isImage && ! hasExternalTarget ) {
			$link.attr( 'data-lightbox', 'sunflower-gallery' );

			if ( caption ) {
				$link.attr( 'data-title', caption );
			}
		} else {
			// Do not apply lightbox attributes to non-image links, but also remove them if they were added by mistake
			$link.removeAttr( 'data-lightbox' ).removeAttr( 'data-title' );
		}
	} );

	lightbox.option( {
		albumLabel: sunflower.texts.lightbox2.imageOneOf,
	} );
} );

function getIcon() {
	return L.icon( {
		iconUrl: sunflower.maps_marker,
		iconSize: [ 25, 41 ], // size of the icon
		shadowSize: [ 0, 0 ], // size of the shadow
		iconAnchor: [ 12, 41 ], // point of the icon which will correspond to marker's location
		shadowAnchor: [ 0, 0 ], // the same for the shadow
		popupAnchor: [ 0, -41 ], // point from which the popup should open relative to the iconAnchor
	} );
}

function showLeaflet( lat, lon, zoom ) {
	const leaflet = L.map( 'leaflet' ).setView( [ lat, lon ], zoom );
	L.tileLayer( 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		maxZoom: 19,
		attribution:
			'&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>',
	} ).addTo( leaflet );

	L.marker( [ lat, lon ], { icon: getIcon() } ).addTo( leaflet );
}

jQuery( '.show-leaflet-all' ).on( 'click', function showLeafletAll() {
	const leaflet = L.map( 'leaflet' ).setView(
		[ map.center.lat, map.center.lon ],
		map.center.zoom
	);
	L.tileLayer( 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
		maxZoom: 19,
		attribution:
			'&copy; <a href="https://openstreetmap.org/copyright">OpenStreetMap contributors</a>',
	} ).addTo( leaflet );

	map.marker.forEach( ( marker ) =>
		L.marker( [ marker.lat, marker.lon ], { icon: getIcon() } )
			.addTo( leaflet )
			.bindPopup( marker.content )
	);
} );

jQuery( '#sunflower-contact-form' ).on( 'submit', function ( e ) {
	e.preventDefault();

	jQuery
		.ajax( {
			url: sunflower.ajaxurl,
			method: 'POST',
			data: {
				action: 'sunflower_contact_form',
				_wpnonce: jQuery( '#_wpnonce' ).val(),
				message: jQuery( '#message' ).val(),
				name: jQuery( '#name' ).val(),
				mail: jQuery( '#mail' ).val(),
				phone: jQuery( '#phone' ).val(),
				title: jQuery( '#contact-form-title' ).html(),
				captcha: jQuery( '#captcha' ).val(),
				captcha_token: jQuery( 'input[name="captcha_token"]' ).val(),
				sendCopy: jQuery( '#send-copy' ).val(),
				postId: jQuery( '#post-id' ).val(),
			},
		} )
		.done( function ( response ) {
			response = JSON.parse( response );

			if ( response.code === 500 ) {
				const errorbox = jQuery(
					'#sunflower-contact-form #form-error'
				);
				errorbox.html( response.text );
				errorbox.show();

				const button = jQuery( '#submit' );
				button.hide();

				// show some progress
				const interval = setInterval( function () {
					errorbox.append( ' . ' );
				}, 500 );

				// show submit button after 5 seconds again and hide error message
				setTimeout( function () {
					clearInterval( interval );
					button.prop( 'disabled', false );
					button.css( 'opacity', 1 );
					button.show();
					errorbox.hide();
				}, 5000 );
				return;
			}

			jQuery( '#sunflower-contact-form' ).html( response.text );
		} );

	return false;
} );

/* add read more link to rss block items */
function addRssReadMore() {
	// loop over every title with link and add it as "read more" link
	jQuery( '.wp-block-rss .wp-block-rss__item' ).each( function () {
		const titlelink = jQuery( '.wp-block-rss__item-title a', this );
		const mydiv = jQuery( '<div class="d-flex flex-row-reverse">' );
		const moreLink = jQuery( '<a />', {
			href: titlelink.attr( 'href' ),
			class: 'continue-reading',
			rel: 'bookmark',
			text: sunflower.texts.readmore,
		} );
		jQuery( this ).append( mydiv.append( moreLink ) );

		// convert excerpt into link to have same behaviour as latest-posts
		const excerpt = jQuery( '.wp-block-rss__item-excerpt', this ).text();
		const newExcerpt = jQuery( '<div>', {
			class: 'wp-block-rss__item-excerpt entry-content',
		} );
		jQuery( '.wp-block-rss__item-excerpt', this ).replaceWith(
			newExcerpt.append( titlelink.clone().text( excerpt ) )
		);
	} );
}

// make parent item of dropdowm menu clickable which is not intended by Bootstrap
jQuery( '.dropdown .dropdown-toggle' ).on( 'click', function () {
	if ( jQuery( '.dropdown:hover' ).length !== 0 ) {
		window.location = jQuery( this ).attr( 'href' );
	}

	return false;
} );

jQuery( function () {
	jQuery( '.navbar-toggler' ).click( function () {
		if ( jQuery( '.navbar-toggler' ).hasClass( 'collapsed' ) ) {
			window.setTimeout( () => {
				jQuery( 'body' ).removeClass( 'navbar-open' );
			}, 100 );
		} else {
			jQuery( 'body' ).addClass( 'navbar-open' );
		}
	} );
} );

document.addEventListener( 'DOMContentLoaded', function () {
	// Add aria-labels to make lightbox2 WCAG2AA compliant.
	const observerLightbox = new MutationObserver( () => {
		const closeBtn = document.querySelector( ".lb-close[role='button']" );
		const cancelBtn = document.querySelector( ".lb-cancel[role='button']" );
		const nextBtn = document.querySelector( ".lb-next[role='button']" );
		const prevBtn = document.querySelector( ".lb-prev[role='button']" );

		if ( closeBtn ) {
			closeBtn.setAttribute(
				'aria-label',
				sunflower.texts.lightbox2.closeLightbox
			);
		}

		if ( cancelBtn ) {
			cancelBtn.setAttribute(
				'aria-label',
				sunflower.texts.lightbox2.cancelLoading
			);
		}

		if ( nextBtn ) {
			nextBtn.setAttribute(
				'aria-label',
				sunflower.texts.lightbox2.nextImage
			);
		}

		if ( prevBtn ) {
			prevBtn.setAttribute(
				'aria-label',
				sunflower.texts.lightbox2.previousImage
			);
		}
	} );

	observerLightbox.observe( document.body, {
		childList: true,
		subtree: true,
	} );
} );
/* eslint-enable no-undef */
