/**
 * Saved & Abandoned Carts — storefront save / share / resume.
 *
 * RESUME is cookieless-CDN-safe: the server restores the saved cart into the
 * real WooCommerce session and returns the session cookie value; we set it via
 * document.cookie (a BROWSER-set cookie, which the CDN can't strip — unlike a
 * server Set-Cookie) and reload. On the next request WC loads that exact
 * session for the block cart, the classic cart, the checkout AND the side-cart,
 * and the wp_woocommerce_session_* cookie also flips nginx skip_cache on.
 */
( function () {
	'use strict';

	var cfg = window.aieoCarts || {};
	var i18n = cfg.i18n || {};

	function closest( el, sel ) {
		while ( el && el.nodeType === 1 ) {
			if ( el.matches && el.matches( sel ) ) {
				return el;
			}
			el = el.parentElement;
		}
		return null;
	}

	function getParam( name ) {
		try {
			return new URLSearchParams( window.location.search ).get( name );
		} catch ( e ) {
			return null;
		}
	}

	function cleanUrl() {
		try {
			window.history.replaceState( {}, '', window.location.pathname );
		} catch ( e ) {}
	}

	/* ------------------------------------------------------------------ */
	/* Resume a shared cart (?aieo_cart=<token>)                          */
	/* ------------------------------------------------------------------ */

	function overlay( msg ) {
		if ( document.getElementById( 'aieo-cart-overlay' ) ) {
			return;
		}
		var d = document.createElement( 'div' );
		d.id = 'aieo-cart-overlay';
		d.setAttribute( 'style', 'position:fixed;inset:0;z-index:99999;background:rgba(255,255,255,.93);display:flex;align-items:center;justify-content:center;text-align:center;padding:1em;font:600 16px/1.5 system-ui,sans-serif;color:#111;' );
		d.innerHTML = '<div>' + ( msg || 'Loading…' ) + '</div>';
		( document.body || document.documentElement ).appendChild( d );
	}
	function hideOverlay() {
		var d = document.getElementById( 'aieo-cart-overlay' );
		if ( d && d.parentNode ) {
			d.parentNode.removeChild( d );
		}
	}

	function setSessionCookie( ck ) {
		// Encode the value: PHP url-decodes $_COOKIE, matching how WC's own
		// setcookie() round-trips the value (handles +, /, $, | in the hash).
		var c = ck.name + '=' + encodeURIComponent( ck.value )
			+ '; path=/; max-age=' + ( ck.maxAge || 172800 ) + '; samesite=lax';
		if ( window.location.protocol === 'https:' ) {
			c += '; secure';
		}
		document.cookie = c;
	}

	function resumeSharedCart() {
		var token = getParam( 'aieo_cart' );
		if ( ! token ) {
			return;
		}
		var doneKey = 'aieoCartDone_' + token;
		if ( sessionStorage.getItem( doneKey ) === '1' ) {
			// Guard against a reload loop if URL cleanup ever fails.
			cleanUrl();
			return;
		}

		overlay( i18n.loading || 'Loading the shared cart…' );

		var body = new FormData();
		body.append( 'action', 'aieo_resume_cart' );
		body.append( 'nonce', cfg.nonce || '' );
		body.append( 'token', token );

		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( res ) {
				if ( res && res.success && res.data && res.data.cookie ) {
					setSessionCookie( res.data.cookie );
					try {
						sessionStorage.setItem( doneKey, '1' );
					} catch ( e ) {}
					cleanUrl();
					window.location.reload();
				} else {
					hideOverlay();
					if ( window.console && console.error ) {
						console.error( '[aieo cart restore]', res && res.data );
					}
				}
			} )
			.catch( function ( e ) {
				hideOverlay();
				if ( window.console && console.error ) {
					console.error( '[aieo cart restore]', e );
				}
			} );
	}

	/* ------------------------------------------------------------------ */
	/* Save / share button                                                 */
	/* ------------------------------------------------------------------ */

	function panelFor( btn ) {
		var ops = closest( btn, '.aieo-cart-ops' );
		return ops ? ops.querySelector( '.aieo-cart-share' ) : null;
	}

	function setMsg( btn, text, isError ) {
		var panel = panelFor( btn );
		if ( ! panel ) {
			if ( isError ) {
				window.alert( text );
			}
			return;
		}
		var msg = panel.querySelector( '.aieo-cart-share-msg' );
		if ( msg ) {
			msg.textContent = text;
		}
		panel.classList.toggle( 'is-error', !! isError );
	}

	function showShare( btn, data ) {
		var panel = panelFor( btn );
		if ( ! panel ) {
			return;
		}
		var input = panel.querySelector( '.aieo-cart-share-url' );
		if ( input ) {
			input.value = data.url || '';
		}
		setMsg( btn, data.message || '', false );
		panel.hidden = false;
		panel.classList.add( 'is-open' );
		if ( input ) {
			input.focus();
			input.select();
		}
	}

	// Side-cart / narrow contexts: no inline panel — auto-copy the link + offer
	// native share, with brief button feedback.
	function quickShare( btn, data ) {
		var url = data.url || '';
		if ( navigator.clipboard && navigator.clipboard.writeText ) {
			navigator.clipboard.writeText( url ).catch( function () {} );
		}
		if ( navigator.share ) {
			navigator.share( { url: url } ).catch( function () {} );
		}
		var orig = btn.getAttribute( 'data-label' ) || btn.textContent;
		btn.textContent = i18n.copied || 'Copied!';
		setTimeout( function () { btn.textContent = orig; }, 1800 );
	}

	function resetBtn( btn ) {
		btn.disabled = false;
		var label = btn.getAttribute( 'data-label' );
		if ( label ) {
			btn.textContent = label;
		}
	}

	function save( btn ) {
		if ( btn.disabled ) {
			return;
		}
		btn.setAttribute( 'data-label', btn.textContent );
		btn.disabled = true;
		btn.textContent = i18n.saving || 'Saving…';

		var body = new FormData();
		body.append( 'action', 'aieo_save_cart' );
		body.append( 'nonce', cfg.nonce || '' );
		body.append( 'source', btn.getAttribute( 'data-source' ) || 'cart_button' );

		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( res ) {
				resetBtn( btn );
				if ( res && res.success && res.data ) {
					if ( btn.getAttribute( 'data-quick' ) === '1' ) {
						quickShare( btn, res.data );
					} else {
						showShare( btn, res.data );
					}
				} else {
					setMsg( btn, ( res && res.data && res.data.message ) || i18n.error || 'Error', true );
					var p = panelFor( btn );
					if ( p ) {
						p.hidden = false;
					}
				}
			} )
			.catch( function () {
				resetBtn( btn );
				setMsg( btn, i18n.error || 'Error', true );
				var p = panelFor( btn );
				if ( p ) {
					p.hidden = false;
				}
			} );
	}

	function copyUrl( copyBtn ) {
		var panel = closest( copyBtn, '.aieo-cart-share' );
		var input = panel ? panel.querySelector( '.aieo-cart-share-url' ) : null;
		if ( ! input ) {
			return;
		}
		var done = function () {
			var orig = copyBtn.textContent;
			copyBtn.textContent = i18n.copied || 'Copied!';
			setTimeout( function () { copyBtn.textContent = orig; }, 1500 );
		};
		if ( navigator.clipboard && navigator.clipboard.writeText ) {
			navigator.clipboard.writeText( input.value ).then( done, function () { legacyCopy( input ); done(); } );
		} else {
			legacyCopy( input );
			done();
		}
		if ( navigator.share ) {
			navigator.share( { url: input.value } ).catch( function () {} );
		}
	}

	function legacyCopy( input ) {
		input.focus();
		input.select();
		try {
			document.execCommand( 'copy' );
		} catch ( e ) {}
	}

	/* ------------------------------------------------------------------ */
	/* Block-cart button injection                                         */
	/* ------------------------------------------------------------------ */

	function cartHost() {
		return document.querySelector( '.wp-block-woocommerce-cart, .wc-block-cart' );
	}
	function checkoutHost() {
		return document.querySelector( '.wp-block-woocommerce-checkout, .wc-block-checkout' );
	}

	function opsWrap( source ) {
		var wrap = document.createElement( 'div' );
		wrap.className = 'aieo-cart-ops aieo-cart-ops--block';
		wrap.innerHTML =
			'<button type="button" class="aieo-save-cart wp-element-button" data-source="' + source + '"></button>' +
			'<div class="aieo-cart-share" hidden>' +
			'<p class="aieo-cart-share-msg"></p>' +
			'<div class="aieo-cart-share-row">' +
			'<input type="text" class="aieo-cart-share-url" readonly />' +
			'<button type="button" class="aieo-cart-share-copy">' + ( i18n.copy || 'Copy' ) + '</button>' +
			'</div></div>';
		wrap.querySelector( '.aieo-save-cart' ).textContent = i18n.save || 'Save my cart';
		return wrap;
	}

	function injectInto( host, selectors, source ) {
		if ( ! host || host.querySelector( '.aieo-save-cart' ) ) {
			return;
		}
		var target = host;
		for ( var i = 0; i < selectors.length; i++ ) {
			var el = host.querySelector( selectors[ i ] );
			if ( el ) {
				target = el;
				break;
			}
		}
		target.appendChild( opsWrap( source ) );
	}

	function injectCart() {
		injectInto( cartHost(), [ '.wc-block-cart__totals-title', '.wc-block-components-totals-wrapper', '.wc-block-cart__sidebar', '.wc-block-cart__submit' ], 'block_cart' );
	}

	function injectCheckout() {
		if ( ! ( cfg.flags && cfg.flags.checkout ) ) {
			return;
		}
		injectInto( checkoutHost(), [ '.wc-block-checkout__sidebar', '.wc-block-components-order-summary', '.wc-block-checkout__main' ], 'checkout' );
	}

	function watch( host, fn ) {
		if ( ! host || ! window.MutationObserver ) {
			return;
		}
		var pending = false;
		var obs = new MutationObserver( function () {
			if ( pending ) {
				return;
			}
			pending = true;
			window.requestAnimationFrame( function () {
				pending = false;
				fn();
			} );
		} );
		obs.observe( host, { childList: true, subtree: true } );
	}

	/* ------------------------------------------------------------------ */
	/* Wire-up                                                             */
	/* ------------------------------------------------------------------ */

	document.addEventListener( 'click', function ( e ) {
		var saveBtn = closest( e.target, '.aieo-save-cart' );
		if ( saveBtn ) {
			e.preventDefault();
			save( saveBtn );
			return;
		}
		var copyBtn = closest( e.target, '.aieo-cart-share-copy' );
		if ( copyBtn ) {
			e.preventDefault();
			copyUrl( copyBtn );
		}
	} );

	function ready( fn ) {
		if ( document.readyState !== 'loading' ) {
			fn();
		} else {
			document.addEventListener( 'DOMContentLoaded', fn );
		}
	}

	// Resume runs ASAP (it reloads the page); button wiring after DOM.
	resumeSharedCart();
	ready( function () {
		injectCart();
		injectCheckout();
		watch( cartHost(), injectCart );
		if ( cfg.flags && cfg.flags.checkout ) {
			watch( checkoutHost(), injectCheckout );
		}
	} );
} )();
