/**
 * Affiliate Tracker - Frontend checkout integration.
 *
 * Persists the affiliate code in localStorage and passes it through to the
 * AJAX checkout session creation endpoint.
 *
 * Expects `strpSubAffiliateTracker` to be provided via wp_localize_script().
 */
( function () {
	var cfg          = window.strpSubAffiliateTracker || {};
	var affiliateRef = cfg.affiliateRef || '';
	var debug        = false;

	function showBtnNotice( btn, msg ) {
		var existing = btn.parentNode.querySelector( '.strp-sub-inline-error' );
		if ( existing ) {
			existing.remove();
		}
		var el       = document.createElement( 'div' );
		el.className = 'strp-sub-inline-error';
		el.style.cssText = 'color:#991b1b;background:#fef2f2;border:1px solid #fecaca;padding:8px 12px;border-radius:4px;margin-top:8px;font-size:14px;';
		el.textContent   = msg;
		btn.parentNode.insertBefore( el, btn.nextSibling );
		setTimeout( function () {
			el.remove();
		}, 6000 );
	}

	// Persist affiliate code in localStorage when available.
	if ( affiliateRef ) {
		try {
			localStorage.setItem( 'strp_sub_affiliate_backup', affiliateRef );
			if ( debug ) {
				console.log( '[Affiliate] Stored code in localStorage:', affiliateRef );
			}
		} catch ( e ) {} // eslint-disable-line no-empty
	}

	document.addEventListener( 'click', function ( e ) {
		var btn = e.target.closest( '.strp-sub-subscribe-button' );
		if ( ! btn ) {
			return;
		}
		e.preventDefault();

		var productId        = btn.dataset.productId;
		var priceId          = btn.dataset.priceId;
		var subscriptionType = btn.dataset.subscriptionType;

		var ref = '';
		try {
			var wasCleared = localStorage.getItem( 'strp_sub_affiliate_cleared' );
			if ( wasCleared === 'true' ) {
				ref = '';
			} else {
				ref = localStorage.getItem( 'strp_sub_affiliate_backup' ) || affiliateRef;
			}
		} catch ( e ) {
			ref = affiliateRef;
		}

		var originalText = btn.innerHTML;
		btn.disabled  = true;
		btn.innerHTML = cfg.i18n.loading;

		fetch( cfg.ajaxUrl, {
			method:  'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body:    new URLSearchParams( {
				action:            'strp_sub_create_checkout_session',
				product_id:        productId,
				price_id:          priceId,
				subscription_type: subscriptionType,
				affiliate_ref:     ref,
				nonce:             cfg.nonce
			} )
		} )
		.then( function ( r ) {
			return r.json();
		} )
		.then( function ( data ) {
			if ( debug ) {
				console.log( '[Affiliate] Response:', data );
			}
			if ( data.success && data.data.url ) {
				window.location.href = data.data.url;
			} else {
				var errMsg = ( data.data && data.data.message ) ? data.data.message : cfg.i18n.error;
				showBtnNotice( btn, errMsg );
				btn.disabled  = false;
				btn.innerHTML = originalText;
			}
		} )
		.catch( function ( err ) {
			if ( debug ) {
				console.error( '[Affiliate] Error:', err );
			}
			showBtnNotice( btn, cfg.i18n.networkError );
			btn.disabled  = false;
			btn.innerHTML = originalText;
		} );
	} );
} )();
