/**
 * BaseCloud Boost — Admin-bar "Boost Cache" button.
 *
 * Clears the cache via AJAX without leaving the current page, and plays a
 * rocket launch + toast animation. Works on the front end and in wp-admin,
 * anywhere the WordPress toolbar is shown. The toolbar link's href remains a
 * no-JS fallback.
 */
( function () {
	'use strict';

	var cfg = window.bcbBoostBar || {};

	// ── Inject the small CSS this button needs (scoped to our own classes). ──
	function injectStyles() {
		if ( document.getElementById( 'bcboost-boostbar-css' ) ) return;
		var css =
			'@keyframes bcboost-rocket-launch{0%{transform:translateY(0) scale(1);opacity:1}70%{opacity:1}100%{transform:translateY(-120vh) scale(.6);opacity:0}}' +
			'@keyframes bcboost-rocket-wobble{0%,100%{margin-left:0}25%{margin-left:-6px}75%{margin-left:6px}}' +
			'@keyframes bcboost-toast-in{from{transform:translateY(24px);opacity:0}to{transform:translateY(0);opacity:1}}' +
			'@keyframes bcboost-spin{to{transform:rotate(360deg)}}' +
			'.bcboost-rocket{position:fixed;z-index:2147483647;font-size:34px;line-height:1;pointer-events:none;will-change:transform;filter:drop-shadow(0 0 10px rgba(74,222,128,.7));animation:bcboost-rocket-launch 1.1s cubic-bezier(.55,0,.45,1) forwards}' +
			'.bcboost-rocket span{display:inline-block;animation:bcboost-rocket-wobble .25s ease-in-out infinite}' +
			'.bcboost-toast{position:fixed;right:22px;bottom:22px;z-index:2147483647;display:flex;align-items:center;gap:10px;padding:13px 18px;border-radius:14px;font:600 14px/1.3 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;color:#fff;background:linear-gradient(135deg,#16a34a,#22c55e);box-shadow:0 12px 34px rgba(0,0,0,.32);animation:bcboost-toast-in .4s cubic-bezier(.34,1.56,.64,1) both;max-width:340px}' +
			'.bcboost-toast--err{background:linear-gradient(135deg,#b91c1c,#ef4444)}' +
			'.bcboost-toast .bcboost-toast-spin{width:16px;height:16px;border:2px solid rgba(255,255,255,.4);border-top-color:#fff;border-radius:50%;animation:bcboost-spin .7s linear infinite}' +
			'#wp-admin-bar-bcboost-clear-cache.bcboost-bar-busy a{opacity:.7;pointer-events:none}';
		var style = document.createElement( 'style' );
		style.id = 'bcboost-boostbar-css';
		style.textContent = css;
		document.head.appendChild( style );
	}

	function launchRocket( x, y ) {
		var rocket = document.createElement( 'div' );
		rocket.className = 'bcboost-rocket';
		rocket.innerHTML = '<span>🚀</span>';
		rocket.style.left = ( x - 17 ) + 'px';
		rocket.style.top  = ( y - 17 ) + 'px';
		document.body.appendChild( rocket );
		setTimeout( function () { rocket.remove(); }, 1200 );
	}

	function toast( message, ok ) {
		var t = document.createElement( 'div' );
		t.className = 'bcboost-toast' + ( ok ? '' : ' bcboost-toast--err' );
		t.innerHTML = ( ok ? '🚀 ' : '⚠️ ' ) + '<span></span>';
		t.querySelector( 'span' ).textContent = message;
		document.body.appendChild( t );
		setTimeout( function () {
			t.style.transition = 'opacity .4s, transform .4s';
			t.style.opacity = '0';
			t.style.transform = 'translateY(16px)';
			setTimeout( function () { t.remove(); }, 420 );
		}, 3200 );
	}

	function clearCache( item, link, originX, originY ) {
		if ( item.classList.contains( 'bcboost-bar-busy' ) ) return;
		item.classList.add( 'bcboost-bar-busy' );

		var label = link ? link.querySelector( '.ab-label' ) : null;
		var prev  = label ? label.textContent : '';
		if ( label ) label.textContent = ( cfg.strings && cfg.strings.clearing ) || 'Boosting…';

		launchRocket( originX, originY );

		var body = new URLSearchParams( { action: 'BCBOOST_clear_cache', nonce: cfg.nonce || '' } );
		fetch( cfg.ajaxUrl, {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: body.toString(),
			credentials: 'same-origin',
		} )
			.then( function ( r ) { return r.json(); } )
			.then( function ( res ) {
				var msg = ( res && res.data && res.data.message ) ||
					( ( cfg.strings && cfg.strings.cleared ) || 'Cache boosted!' );
				toast( msg, !! ( res && res.success ) );
			} )
			.catch( function () {
				toast( ( cfg.strings && cfg.strings.error ) || 'Could not clear cache.', false );
			} )
			.finally( function () {
				item.classList.remove( 'bcboost-bar-busy' );
				if ( label ) label.textContent = prev;
			} );
	}

	function init() {
		var item = document.getElementById( 'wp-admin-bar-bcboost-clear-cache' );
		if ( ! item || ! cfg.ajaxUrl ) return;
		var link = item.querySelector( 'a' );
		if ( ! link ) return;

		injectStyles();

		link.addEventListener( 'click', function ( e ) {
			// Honour modifier keys (open in new tab, etc.) — fall back to navigation.
			if ( e.metaKey || e.ctrlKey || e.shiftKey || e.altKey ) return;
			e.preventDefault();
			var rect = link.getBoundingClientRect();
			clearCache( item, link, rect.left + rect.width / 2, rect.top + rect.height );
		} );
	}

	if ( document.readyState === 'loading' ) {
		document.addEventListener( 'DOMContentLoaded', init );
	} else {
		init();
	}
} )();
