/**
 * @file assets/js/adminjs/admin-license.js
 * License activation, deactivation, and free key registration on the Settings → License tab.
 * @package MyBookShowroom
 * @since   1.0.0
 */

(function( MBS, $, undefined ) {
	'use strict';
	var __ = wp.i18n.__;

	MBS.License = {

		init: function() {
			this.bindActivate();
			this.bindDeactivate();
			this.bindRegisterFreeLink();
			this.bindShowKeyInput();
			this.bindRegisterFreeSubmit();
			this.bindCopyKey();
		},

		// ── Activate ────────────────────────────────────────────────────────

		bindActivate: function() {
			$( document ).on( 'click', '#mbs-activate-btn', function() {
				const key = $( '#mbs_license_key' ).val().trim();
				if ( ! key ) {
					alert( __( 'Please enter a license key.', 'my-book-showroom' ) );
					return;
				}

				const $btn = $( this );
				$btn.prop( 'disabled', true ).text( __( 'Activating…', 'my-book-showroom' ) );

				$.post(
					ajaxurl,
					{
						action: 'mbs_activate_license',
						key:    key,
						nonce:  MBS_License_Ajax.nonce
					},
					function( res ) {
						if ( res.success ) {
							location.reload();
						} else {
							alert( res.data || __( 'Activation failed. Please check your key and try again.', 'my-book-showroom' ) );
							$btn.prop( 'disabled', false ).text( __( 'Activate License', 'my-book-showroom' ) );
						}
					}
				).fail( function() {
					alert( __( 'Network error. Please try again.', 'my-book-showroom' ) );
					$btn.prop( 'disabled', false ).text( __( 'Activate License', 'my-book-showroom' ) );
				} );
			} );
		},

		// ── Deactivate ───────────────────────────────────────────────────────

		bindDeactivate: function() {
			$( document ).on( 'click', '#mbs-deactivate-btn', function() {
				if ( ! confirm( __( 'Deactivate this license on the current domain?', 'my-book-showroom' ) ) ) {
					return;
				}

				const $btn = $( this );
				$btn.prop( 'disabled', true ).text( __( 'Deactivating…', 'my-book-showroom' ) );

				$.post(
					ajaxurl,
					{
						action: 'mbs_deactivate_license',
						nonce:  MBS_License_Ajax.nonce
					},
					function( res ) {
						if ( res.success ) {
							location.reload();
						} else {
							alert( res.data || __( 'Deactivation failed.', 'my-book-showroom' ) );
							$btn.prop( 'disabled', false ).text( __( 'Deactivate License', 'my-book-showroom' ) );
						}
					}
				).fail( function() {
					alert( __( 'Network error. Please try again.', 'my-book-showroom' ) );
					$btn.prop( 'disabled', false ).text( __( 'Deactivate License', 'my-book-showroom' ) );
				} );
			} );
		},

		// ── Register free — open modal ────────────────────────────────────

		bindRegisterFreeLink: function() {
			$( document ).on( 'click', '#mbs-register-free', function( e ) {
				e.preventDefault();
				$( '#mbs-register-modal' ).slideDown( 150 );
				$( '#mbs-free-email' ).trigger( 'focus' );
			} );
		},

		// ── Show key-input section (keyless state) ──────────────────

		bindShowKeyInput: function() {
			$( document ).on( 'click', '#mbs-show-key-input', function( e ) {
				e.preventDefault();
				$( '#mbs-key-input-section' ).slideDown( 150 );
				$( '#mbs_license_key' ).trigger( 'focus' );
			} );
		},

		// ── Register free — submit email ─────────────────────────────────

		bindRegisterFreeSubmit: function() {
			$( document ).on( 'click', '#mbs-get-free-key-btn', function() {
				const email = $( '#mbs-free-email' ).val().trim();
				if ( ! email ) {
					alert( __( 'Please enter your email address.', 'my-book-showroom' ) );
					return;
				}

				const $btn = $( this );
				$btn.prop( 'disabled', true ).text( __( 'Sending…', 'my-book-showroom' ) );

				$.post(
					ajaxurl,
					{
						action: 'mbs_register_free_key',
						email:  email,
						nonce:  MBS_License_Ajax.nonce
					},
					function( res ) {
						if ( res.success && res.data && res.data.key ) {
							const key = res.data.key;
							$( '#mbs-free-key-display' ).text( key );
							$( '#mbs-free-key-result' ).slideDown( 150 );

							// Auto-activate the returned key so the admin doesn't
							// have to copy-paste it into the activation field.
							$.post(
								ajaxurl,
								{
									action: 'mbs_activate_license',
									key:    key,
									nonce:  MBS_License_Ajax.nonce
								},
								function( activateRes ) {
									if ( activateRes.success ) {
										location.reload();
									}
									// Even if auto-activate failed, show the key
									// so the admin can activate manually.
								}
							);
						} else {
							alert( ( res.data && res.data.message ) || res.data || __( 'Free key registration failed.', 'my-book-showroom' ) );
							$btn.prop( 'disabled', false ).text( __( 'Get My Free Key', 'my-book-showroom' ) );
						}
					}
				).fail( function() {
					alert( __( 'Network error. Please try again.', 'my-book-showroom' ) );
					$btn.prop( 'disabled', false ).text( __( 'Get My Free Key', 'my-book-showroom' ) );
				} );
			} );
		},

		// ── Copy free key to clipboard ────────────────────────────────────

		bindCopyKey: function() {
			$( document ).on( 'click', '#mbs-copy-free-key', function() {
				const keyText = $( '#mbs-free-key-display' ).text();
				if ( ! keyText ) {
					return;
				}

				const $btn = $( this );

				if ( navigator.clipboard && navigator.clipboard.writeText ) {
					navigator.clipboard.writeText( keyText ).then( function() {
						$btn.text( __( 'Copied!', 'my-book-showroom' ) );
						setTimeout( function() { $btn.text( __( 'Copy', 'my-book-showroom' ) ); }, 2000 );
					} ).catch( function() {
						MBS.License.fallbackCopy( keyText, $btn );
					} );
				} else {
					MBS.License.fallbackCopy( keyText, $btn );
				}
			} );
		},

		fallbackCopy: function( text, $btn ) {
			const $tmp = $( '<textarea>' ).val( text ).appendTo( 'body' ).select();
			try {
				document.execCommand( 'copy' );
				$btn.text( __( 'Copied!', 'my-book-showroom' ) );
				setTimeout( function() { $btn.text( __( 'Copy', 'my-book-showroom' ) ); }, 2000 );
			} catch ( e ) {
				$btn.text( __( 'Copy failed', 'my-book-showroom' ) );
			}
			$tmp.remove();
		}
	};

})( window.MBS = window.MBS || {}, jQuery );

jQuery( document ).ready( function() {
	window.MBS.License.init();
} );
