/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

export default function attachPermalinkListener() {
	const projectVersionElement = document.querySelector( 'meta[name=project-version]' );
	const projectSlugElement = document.querySelector( 'meta[name=project-slug]' );

	if ( !projectVersionElement || !projectSlugElement ) {
		return;
	}

	const permalinkDisableDomainsElement = document.querySelector( 'meta[name=permalink-disable-domains]' );

	if ( permalinkDisableDomainsElement ) {
		const permalinkDisableDomains = permalinkDisableDomainsElement.getAttribute( 'content' ).split( ',' );

		if ( permalinkDisableDomains.includes( location.hostname ) ) {
			return;
		}
	}

	const projectVersion = projectVersionElement.getAttribute( 'content' );
	const projectSlug = projectSlugElement.getAttribute( 'content' );

	document.addEventListener( 'keypress', event => {
		if ( event.metaKey ) {
			return;
		}

		if ( event.shiftKey ) {
			return;
		}

		if ( event.key.toUpperCase() !== 'Y' ) {
			return;
		}

		const latestRegexp = new RegExp( `/${ projectSlug }/latest/` );

		if ( !latestRegexp.test( location.href ) ) {
			return;
		}

		const newUrl = location.href.replace( latestRegexp, `/${ projectSlug }/${ projectVersion }/` );

		history.replaceState( history.state, document.title, newUrl );
	} );
}
