/**
 * Managed AI, subscribe / poll / toggle / cancel / refund / boost flow for the
 * CloudScale DevTools Home dashboard panel. Talks to admin-ajax via the
 * csdtManagedAi localized object. All handlers fail soft (no thrown rejections).
 *
 * @package CloudScale_DevTools
 */
( function () {
	'use strict';

	if ( typeof csdtManagedAi === 'undefined' ) { return; }
	var AJAX  = csdtManagedAi.ajaxUrl;
	var NONCE = csdtManagedAi.nonce;

	/** POST an action to admin-ajax and resolve the parsed JSON (never rejects on HTTP error). */
	function post( action, extra ) {
		var params = Object.assign( { action: action, nonce: NONCE }, extra || {} );
		return fetch( AJAX, {
			method: 'POST',
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
			body: new URLSearchParams( params ).toString()
		} ).then( function ( r ) { return r.json(); } ).catch( function () { return { success: false }; } );
	}

	function byId( id ) { return document.getElementById( id ); }

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

	ready( function () {
		var panel = byId( 'cs-managed-ai-panel' );
		if ( ! panel ) { return; }

		// ── Subscribe ──────────────────────────────────────────────────────
		var subBtn = byId( 'cs-managed-ai-subscribe-btn' );
		if ( subBtn ) {
			subBtn.addEventListener( 'click', function () {
				var email = ( byId( 'cs-managed-ai-email' ) || {} ).value || '';
				var msg   = byId( 'cs-managed-ai-subscribe-msg' );
				function showMsg( color, text ) {
					if ( msg ) { msg.style.display = ''; msg.style.color = color; msg.textContent = text; }
				}
				if ( ! email ) { showMsg( '#b91c1c', 'Please enter your email address.' ); return; }
				var label = subBtn.textContent;
				subBtn.disabled = true;
				subBtn.textContent = 'Opening checkout…';
				var tab = window.open( '', '_blank' );
				post( 'csdt_managed_ai_checkout', { email: email } ).then( function ( res ) {
					subBtn.disabled = false;
					subBtn.textContent = label;
					if ( res.success && res.data && res.data.checkout_url ) {
						if ( tab ) { tab.location.href = res.data.checkout_url; }
						showMsg( '#0284c7', 'Checkout opened in a new tab. This panel updates automatically once payment confirms.' );
						setTimeout( function () { window.location.reload(); }, 4000 );
					} else if ( res.success && res.data && res.data.already_subscribed ) {
						if ( tab && res.data.manage_url ) { tab.location.href = res.data.manage_url; }
						showMsg( '#166534', 'You already have an active subscription, opening your manage page.' );
					} else {
						if ( tab ) { tab.close(); }
						showMsg( '#b91c1c', ( res.data && res.data.message ) || 'Checkout failed, please try again.' );
					}
				} );
			} );
		}

		// ── Use-Managed-AI toggle (explicit Save) ───────────────────────────
		var toggle  = byId( 'cs-managed-ai-toggle' );
		var saveBtn = byId( 'cs-managed-ai-save-toggle' );
		var saveSt  = byId( 'cs-managed-ai-save-status' );
		if ( toggle && saveBtn ) {
			saveBtn.addEventListener( 'click', function () {
				saveBtn.disabled = true;
				if ( saveSt ) { saveSt.style.color = '#6b7280'; saveSt.textContent = 'Saving…'; }
				post( 'csdt_managed_ai_set_enabled', { enabled: toggle.checked ? 1 : 0 } ).then( function ( res ) {
					saveBtn.disabled = false;
					if ( res && res.success ) {
						if ( saveSt ) { saveSt.style.color = '#15803d'; saveSt.textContent = '✓ Saved'; setTimeout( function () { saveSt.textContent = ''; }, 2500 ); }
					} else if ( saveSt ) {
						saveSt.style.color = '#ef4444'; saveSt.textContent = '⚠ Save failed';
					}
				} );
			} );
		}

		// ── Refresh status ──────────────────────────────────────────────────
		var refreshBtn = byId( 'cs-managed-ai-refresh-btn' );
		if ( refreshBtn ) {
			refreshBtn.addEventListener( 'click', function () {
				refreshBtn.disabled = true;
				post( 'csdt_managed_ai_refresh_status' ).then( function ( res ) {
					if ( res.success ) { window.location.reload(); }
					else { refreshBtn.disabled = false; }
				} );
			} );
		}

		// ── Copy key ────────────────────────────────────────────────────────
		var copyBtn = byId( 'cs-managed-ai-copy-key' );
		if ( copyBtn ) {
			copyBtn.addEventListener( 'click', function () {
				var key = copyBtn.getAttribute( 'data-key' );
				if ( key && navigator.clipboard ) {
					navigator.clipboard.writeText( key ).then( function () {
						copyBtn.textContent = 'Copied!';
						setTimeout( function () { copyBtn.textContent = 'Copy Key'; }, 2000 );
					} ).catch( function () {} );
				}
			} );
		}

		// ── Boost ───────────────────────────────────────────────────────────
		var boostBtn = byId( 'cs-managed-ai-boost-btn' );
		if ( boostBtn ) {
			boostBtn.addEventListener( 'click', function () {
				var label = boostBtn.textContent;
				boostBtn.disabled = true;
				boostBtn.textContent = 'Opening checkout…';
				var tab = window.open( '', '_blank' );
				post( 'csdt_managed_ai_boost' ).then( function ( res ) {
					boostBtn.disabled = false;
					boostBtn.textContent = label;
					if ( res.success && res.data && res.data.checkout_url ) {
						if ( tab ) { tab.location.href = res.data.checkout_url; }
					} else {
						if ( tab ) { tab.close(); }
						window.alert( ( res.data && res.data.message ) || 'Could not start the boost checkout.' );
					}
				} );
			} );
		}

		// ── Cancel (portal modal) ─────────────────────────────────────────────
		var cancelBtn = byId( 'cs-managed-ai-cancel-btn' );
		if ( cancelBtn ) {
			cancelBtn.addEventListener( 'click', function () {
				var overlay = document.createElement( 'div' );
				overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.55);z-index:100000;display:flex;align-items:center;justify-content:center;padding:16px;';
				overlay.innerHTML =
					'<div style="background:#fff;border-radius:10px;padding:28px 24px;max-width:420px;width:100%;box-shadow:0 24px 60px rgba(0,0,0,0.25);">' +
					'<div style="font-size:1.05rem;font-weight:700;color:#111827;margin-bottom:10px;">&#x1F6AB; Cancel subscription</div>' +
					'<p style="font-size:0.9rem;color:#374151;line-height:1.6;margin:0 0 20px;">This opens your subscription management portal where you can cancel, update your payment method, or view your billing history.</p>' +
					'<div style="display:flex;gap:10px;justify-content:flex-end;">' +
					'<button id="cs-cancel-modal-dismiss" type="button" style="padding:9px 20px;border-radius:6px;border:1.5px solid #d1d5db;background:#fff;color:#374151;font-size:0.875rem;font-weight:600;cursor:pointer;">Dismiss</button>' +
					'<button id="cs-cancel-modal-portal" type="button" style="padding:9px 20px;border-radius:6px;border:none;background:#dc2626;color:#fff;font-size:0.875rem;font-weight:600;cursor:pointer;">Open portal</button>' +
					'</div>' +
					'<p id="cs-cancel-modal-msg" style="display:none;font-size:0.82rem;margin:14px 0 0;text-align:center;color:#b91c1c;"></p>' +
					'</div>';
				document.body.appendChild( overlay );

				function closeModal() { if ( overlay.parentNode ) { document.body.removeChild( overlay ); } }

				overlay.addEventListener( 'click', function ( e ) { if ( e.target === overlay ) { closeModal(); } } );
				document.getElementById( 'cs-cancel-modal-dismiss' ).addEventListener( 'click', closeModal );

				document.getElementById( 'cs-cancel-modal-portal' ).addEventListener( 'click', function () {
					var btn      = this;
					var modalMsg = document.getElementById( 'cs-cancel-modal-msg' );
					btn.disabled = true;
					btn.textContent = 'Opening…';
					var tab = window.open( '', '_blank' );
					post( 'csdt_managed_ai_billing_portal' ).then( function ( res ) {
						if ( res.success && res.data && res.data.url ) {
							if ( tab ) { tab.location.href = res.data.url; }
							closeModal();
						} else {
							if ( tab ) { tab.close(); }
							btn.disabled = false;
							btn.textContent = 'Open portal';
							if ( modalMsg ) { modalMsg.style.display = 'block'; modalMsg.textContent = ( res.data && res.data.message ) || 'Could not open the billing portal.'; }
						}
					} );
				} );
			} );
		}

		// ── Refund ──────────────────────────────────────────────────────────
		var refundBtn = byId( 'cs-managed-ai-refund-btn' );
		if ( refundBtn ) {
			refundBtn.addEventListener( 'click', function () {
				if ( ! window.confirm( 'Request a full refund? Your subscription is cancelled immediately and the payment returned within 5 to 10 business days.' ) ) { return; }
				refundBtn.disabled = true;
				refundBtn.textContent = 'Processing…';
				var refundMsg = byId( 'cs-managed-ai-refund-msg' );
				post( 'csdt_managed_ai_refund' ).then( function ( res ) {
					if ( refundMsg ) { refundMsg.style.display = 'inline'; }
					if ( res.success ) {
						if ( refundMsg ) { refundMsg.style.color = '#15803d'; refundMsg.textContent = ( res.data && res.data.message ) || 'Refund processed.'; }
						refundBtn.style.display = 'none';
						setTimeout( function () { window.location.reload(); }, 3000 );
					} else {
						if ( refundMsg ) { refundMsg.style.color = '#b91c1c'; refundMsg.textContent = ( res.data && res.data.message ) || 'Refund failed. Please try again.'; }
						refundBtn.disabled = false;
						refundBtn.textContent = 'Request refund';
					}
				} );
			} );
		}

		// ── Recover toggle ──────────────────────────────────────────────────
		var recoverToggle = byId( 'cs-managed-ai-recover-toggle' );
		if ( recoverToggle ) {
			recoverToggle.addEventListener( 'click', function () {
				var form = byId( 'cs-managed-ai-recover-form' );
				if ( form ) { form.style.display = form.style.display === 'none' ? '' : 'none'; }
			} );
		}

		// ── Recover license ─────────────────────────────────────────────────
		var recoverBtn = byId( 'cs-managed-ai-recover-btn' );
		if ( recoverBtn ) {
			recoverBtn.addEventListener( 'click', function () {
				var email = ( byId( 'cs-managed-ai-recover-email' ) || {} ).value || '';
				var rmsg  = byId( 'cs-managed-ai-recover-msg' );
				recoverBtn.disabled = true;
				post( 'csdt_managed_ai_recover', { email: email } ).then( function ( res ) {
					if ( res.success ) {
						if ( rmsg ) { rmsg.style.color = '#15803d'; rmsg.textContent = ( res.data && res.data.message ) || 'Recovered.'; }
						setTimeout( function () { window.location.reload(); }, 1500 );
					} else {
						recoverBtn.disabled = false;
						if ( rmsg ) { rmsg.style.color = '#b91c1c'; rmsg.textContent = ( res.data && res.data.message ) || 'Recovery failed.'; }
					}
				} );
			} );
		}

		// ── Billing portal links ────────────────────────────────────────────
		var billingLink = byId( 'cs-managed-ai-billing-link' );
		if ( billingLink ) {
			billingLink.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				post( 'csdt_managed_ai_billing_portal' ).then( function ( res ) {
					if ( res.success && res.data && res.data.url ) { window.open( res.data.url, '_blank' ); }
					else { window.alert( ( res.data && res.data.message ) || 'Could not open the billing portal.' ); }
				} );
			} );
		}

		// ── Contact / Leave us a message ───────────────────────────────────────
		var contactToggle = byId( 'cs-managed-ai-contact-toggle' );
		if ( contactToggle ) {
			contactToggle.addEventListener( 'click', function () {
				var form = byId( 'cs-managed-ai-contact-form' );
				if ( form ) { form.style.display = form.style.display === 'none' ? '' : 'none'; }
			} );
		}

		var contactBtn = byId( 'cs-managed-ai-contact-btn' );
		if ( contactBtn ) {
			contactBtn.addEventListener( 'click', function () {
				var text = ( byId( 'cs-managed-ai-contact-text' ) || {} ).value || '';
				var cmsg = byId( 'cs-managed-ai-contact-msg' );
				if ( ! text.trim() ) {
					if ( cmsg ) { cmsg.style.color = '#b91c1c'; cmsg.textContent = 'Please type a message.'; }
					return;
				}
				contactBtn.disabled = true;
				if ( cmsg ) { cmsg.style.color = '#6b7280'; cmsg.textContent = 'Sending…'; }
				post( 'csdt_managed_ai_contact', { message: text } ).then( function ( res ) {
					contactBtn.disabled = false;
					if ( res.success ) {
						if ( cmsg ) { cmsg.style.color = '#15803d'; cmsg.textContent = ( res.data && res.data.message ) || 'Message sent!'; }
						var ta = byId( 'cs-managed-ai-contact-text' );
						if ( ta ) { ta.value = ''; }
					} else {
						if ( cmsg ) { cmsg.style.color = '#b91c1c'; cmsg.textContent = ( res.data && res.data.message ) || 'Could not send. Please try again.'; }
					}
				} );
			} );
		}

		// ── Auto-poll a pending checkout session ────────────────────────────
		var pending = byId( 'cs-managed-ai-pending-session' );
		var session = pending && pending.getAttribute( 'data-session' );
		if ( session ) {
			var count = 0;
			var timer = setInterval( function () {
				count++;
				if ( count > 40 ) { clearInterval( timer ); return; } // ~2 min max
				post( 'csdt_managed_ai_poll_session', { session_token: session } ).then( function ( res ) {
					if ( res.success && res.data && res.data.status === 'active' ) {
						clearInterval( timer );
						window.location.reload();
					}
				} );
			}, 3000 );
		}
	} );
} )();
