/* global rewardswpMainVars */
/* eslint-disable no-undef, no-console */
/**
 * Copy the given text to the clipboard.
 *
 * @param {string} text The text to copy.
 * @return {Promise<void>}
 */
export function copyToClipboard( text ) {
	return navigator.clipboard.writeText( text ).then( () => {
		console.log( 'Text copied to clipboard' );
	} ).catch( ( err ) => {
		console.error( 'Failed to copy text: ', err );
	} );
}

/**
 * Get the current page URL.
 *
 * @return {string} The current page URL.
 */
export function getCurrentPageUrl() {
	return window.location.href;
}

// Cache both the stylesheet and the fetch promise.
let sharedStyleSheet = null;
let stylesFetchPromise = null;

export async function loadStyles( shadowRoot ) {
	if ( typeof rewardswpMainVars === 'undefined' ) {
		throw new Error( 'rewardswpMainVars is not defined' );
	}

	try {
		// Use cached stylesheet if available.
		if ( sharedStyleSheet ) {
			shadowRoot.adoptedStyleSheets = [ sharedStyleSheet ];
			return;
		}

		// If we're already fetching, wait for that promise.
		if ( ! stylesFetchPromise ) {
			stylesFetchPromise = fetch( rewardswpMainVars.mainCssUrl )
				.then( response => response.text() )
				.then( styles => {
					sharedStyleSheet = new CSSStyleSheet();
					sharedStyleSheet.replaceSync( styles );

					return sharedStyleSheet;
				} );
		}

		// Wait for the styles to load.
		const styleSheet = await stylesFetchPromise;

		shadowRoot.adoptedStyleSheets = [ styleSheet ];
	} catch ( error ) {
		console.error( 'Failed to load styles:', error );
	}
}

export function addXCloakStyle( shadowRoot ) {
	const style = document.createElement( 'style' );
	style.textContent = '[x-cloak] { display: none !important; }';
	shadowRoot.appendChild( style );
}

/**
 * Converts a camelCase or PascalCase string to kebab-case.
 *
 * @since 1.0.0
 *
 * @param {string} key - The string to convert.
 * @return {string} - The converted kebab-case string.
 */
export function toKebabCase( key ) {
	return key.replace( /([a-z0-9])([A-Z])/g, '$1-$2' ).toLowerCase();
}
