/* global pkitsSpNudge, jQuery, wp */
( function ( $ ) {
	'use strict';

	var overlay   = null;
	var modal     = null;
	var isVisible = false;
	var scheduleMode = false;

	// ----------------------------------------------------------------
	// Initialise
	// ----------------------------------------------------------------
	$( function () {
		overlay = $( '#pkits-sp-nudge-overlay' );
		modal   = overlay.find( '.pkits-sp-nudge-modal' );

		if ( ! overlay.length ) {
			return;
		}

		bindEvents();
		populateAccounts();
		preFillCopy();
		detectEditor();
	} );

	// ----------------------------------------------------------------
	// Detect which editor is active and wire publish event
	// ----------------------------------------------------------------
	function detectEditor() {
		// Gutenberg: subscribe to the store.
		if ( typeof wp !== 'undefined' && wp.data && wp.data.select( 'core/editor' ) ) {
			var unsubscribe = wp.data.subscribe( function () {
				var editor      = wp.data.select( 'core/editor' );
				var notices     = wp.data.select( 'core/notices' );
				var isSaving    = editor.isSavingPost();
				var isPublished = editor.isCurrentPostPublished();
				var isAutosave  = editor.isAutosavingPost ? editor.isAutosavingPost() : false;

				if ( window._pkitsSpAdminWasSaving && ! isSaving && ! isAutosave && isPublished && ! window._pkitsSpAdminWasPublished ) {
					window._pkitsSpAdminWasPublished = true;
					// Small delay so Gutenberg's own success notice appears first.
					setTimeout( function () {
						if ( pkitsSpNudge.hasAccounts ) {
							showModal();
						}
					}, 800 );
				}

				window._pkitsSpAdminWasSaving    = isSaving;
				window._pkitsSpAdminWasPublished = window._pkitsSpAdminWasPublished || isPublished;
			} );

		} else {
			// Classic editor: show modal on page load if transient was set.
			if ( pkitsSpNudge.showModalOnLoad && pkitsSpNudge.hasAccounts ) {
				setTimeout( showModal, 300 );
			}
		}

		// Banner button wiring (rendered server-side on subsequent edits).
		var $banner = $( '#pkits-sp-nudge-banner' );
		if ( $banner.length ) {
			$banner.find( '.pkits-sp-nudge-btn-promote' ).on( 'click', function () {
				showModal( 'post_now' );
			} );
			$banner.find( '.pkits-sp-nudge-btn-schedule' ).on( 'click', function () {
				showModal( 'schedule' );
			} );
			$banner.find( '.pkits-sp-nudge-btn-dismiss-perm' ).on( 'click', function () {
				setPromotionStatus( 'dismissed' );
				$banner.slideUp( 200 );
			} );
		}
	}

	// ----------------------------------------------------------------
	// Show modal
	// ----------------------------------------------------------------
	function showModal( mode ) {
		if ( isVisible ) {
			return;
		}

		scheduleMode = false;

		$( '#pkits-sp-nudge-no-accounts' ).hide();
		$( '#pkits-sp-nudge-compose' ).show();
		$( '#pkits-sp-nudge-success' ).hide();
		$( '#pkits-sp-nudge-result' ).hide().text( '' );
		$( '#pkits-sp-nudge-schedule-row' ).hide();

		if ( ! pkitsSpNudge.hasAccounts ) {
			$( '#pkits-sp-nudge-no-accounts' ).show();
			$( '#pkits-sp-nudge-compose' ).hide();
		}

		overlay.fadeIn( 200 );
		isVisible = true;

		// Pre-activate schedule mode if requested from banner.
		if ( mode === 'schedule' ) {
			activateScheduleMode();
		}

		// Trap focus in modal.
		setTimeout( function () {
			modal.find( 'textarea, button, input, a' ).first().trigger( 'focus' );
		}, 250 );
	}

	// ----------------------------------------------------------------
	// Close modal
	// ----------------------------------------------------------------
	function closeModal() {
		overlay.fadeOut( 150 );
		isVisible    = false;
		scheduleMode = false;
		$( '#pkits-sp-nudge-schedule-row' ).hide();
	}

	// ----------------------------------------------------------------
	// Bind modal events
	// ----------------------------------------------------------------
	function bindEvents() {
		// Close on overlay click (outside modal).
		overlay.on( 'click', function ( e ) {
			if ( $( e.target ).is( overlay ) ) {
				closeModal();
			}
		} );

		// Close button.
		overlay.on( 'click', '.pkits-sp-nudge-modal-close', closeModal );

		// ESC key.
		$( document ).on( 'keydown', function ( e ) {
			if ( isVisible && 27 === e.which ) {
				closeModal();
			}
		} );

		// Character counter.
		$( document ).on( 'input', '#pkits-sp-nudge-copy', function () {
			var len      = $( this ).val().length;
			var $counter = $( '.pkits-sp-nudge-char-count' );
			$counter.text( len );
			$counter.toggleClass( 'over-limit', len > 280 );
		} );

		// Post Now button.
		$( document ).on( 'click', '#pkits-sp-nudge-post-now', function () {
			if ( scheduleMode ) {
				confirmSchedule();
			} else {
				doPostNow();
			}
		} );

		// Schedule button.
		$( document ).on( 'click', '#pkits-sp-nudge-schedule-btn', function () {
			if ( scheduleMode ) {
				closeScheduleMode();
			} else {
				activateScheduleMode();
			}
		} );

		// Remind later.
		$( document ).on( 'click', '#pkits-sp-nudge-remind', function () {
			closeModal();
		} );

		// Never promote.
		$( document ).on( 'click', '#pkits-sp-nudge-never', function () {
			setPromotionStatus( 'dismissed' );
			closeModal();
			$( '#pkits-sp-nudge-banner' ).slideUp( 200 );
		} );
	}

	// ----------------------------------------------------------------
	// Schedule mode
	// ----------------------------------------------------------------
	function activateScheduleMode() {
		scheduleMode = true;
		var $row = $( '#pkits-sp-nudge-schedule-row' );
		var hint = pkitsSpNudge.strings.pickTime;

		// If post is scheduled, offer to sync with publish time.
		if ( pkitsSpNudge.scheduledAt ) {
			hint = pkitsSpNudge.strings.syncPublish + ': ' + pkitsSpNudge.scheduledAt;
			$( '#pkits-sp-nudge-datetime' ).val( pkitsSpNudge.scheduledAt );
		}

		$row.find( '.pkits-sp-nudge-schedule-hint' ).text( hint );
		$row.slideDown( 150 );

		$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.confirmSchedule );
		$( '#pkits-sp-nudge-schedule-btn' ).text( '← Back' );
	}

	function closeScheduleMode() {
		scheduleMode = false;
		$( '#pkits-sp-nudge-schedule-row' ).slideUp( 150 );
		$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.promoteNow );
		$( '#pkits-sp-nudge-schedule-btn' ).text( pkitsSpNudge.strings.schedule );
	}

	// ----------------------------------------------------------------
	// Post Now action
	// ----------------------------------------------------------------
	function doPostNow() {
		var copy     = $( '#pkits-sp-nudge-copy' ).val().trim();
		var accounts = getSelectedAccounts();

		if ( ! copy ) {
			showResult( 'error', pkitsSpNudge.strings.selectAccount );
			return;
		}
		if ( ! accounts.length ) {
			showResult( 'error', pkitsSpNudge.strings.selectAccount );
			return;
		}

		$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.posting ).prop( 'disabled', true );

		$.ajax( {
			url:  pkitsSpNudge.ajaxUrl,
			type: 'POST',
			data: {
				action:   'pkits_sp_post_now',
				nonce:    pkitsSpNudge.nonce,
				post_id:  pkitsSpNudge.postId,
				copy:     copy,
				accounts: accounts
			},
			success: function ( response ) {
				if ( response.success ) {
					setPromotionStatus( 'promoted' );
					showSuccess( pkitsSpNudge.strings.successPost );
					hideBanner();
				} else {
					showResult( 'error', response.data.message || 'An error occurred.' );
					$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.promoteNow ).prop( 'disabled', false );
				}
			},
			error: function () {
				showResult( 'error', 'Request failed. Please try again.' );
				$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.promoteNow ).prop( 'disabled', false );
			}
		} );
	}

	// ----------------------------------------------------------------
	// Schedule action
	// ----------------------------------------------------------------
	function confirmSchedule() {
		var copy        = $( '#pkits-sp-nudge-copy' ).val().trim();
		var accounts    = getSelectedAccounts();
		var scheduledAt = $( '#pkits-sp-nudge-datetime' ).val();

		if ( ! copy ) {
			showResult( 'error', pkitsSpNudge.strings.selectAccount );
			return;
		}
		if ( ! accounts.length ) {
			showResult( 'error', pkitsSpNudge.strings.selectAccount );
			return;
		}
		if ( ! scheduledAt ) {
			showResult( 'error', pkitsSpNudge.strings.selectTime );
			return;
		}

		$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.scheduling ).prop( 'disabled', true );

		$.ajax( {
			url:  pkitsSpNudge.ajaxUrl,
			type: 'POST',
			data: {
				action:       'pkits_sp_schedule_post',
				nonce:        pkitsSpNudge.nonce,
				post_id:      pkitsSpNudge.postId,
				copy:         copy,
				accounts:     accounts,
				scheduled_at: scheduledAt
			},
			success: function ( response ) {
				if ( response.success ) {
					setPromotionStatus( 'promoted' );
					showSuccess( pkitsSpNudge.strings.successSchedule );
					hideBanner();
				} else {
					showResult( 'error', response.data.message || 'Scheduling failed.' );
					$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.confirmSchedule ).prop( 'disabled', false );
				}
			},
			error: function () {
				showResult( 'error', 'Request failed. Please try again.' );
				$( '#pkits-sp-nudge-post-now' ).text( pkitsSpNudge.strings.confirmSchedule ).prop( 'disabled', false );
			}
		} );
	}

	// ----------------------------------------------------------------
	// Set promotion status via AJAX
	// ----------------------------------------------------------------
	function setPromotionStatus( status ) {
		$.ajax( {
			url:  pkitsSpNudge.ajaxUrl,
			type: 'POST',
			data: {
				action:  'pkits_sp_set_promotion_status',
				nonce:   pkitsSpNudge.statusNonce,
				post_id: pkitsSpNudge.postId,
				status:  status
			}
		} );
	}

	// ----------------------------------------------------------------
	// Helpers
	// ----------------------------------------------------------------
	function getSelectedAccounts() {
		var accounts = [];
		$( '#pkits-sp-nudge-accounts input[type="checkbox"]:checked' ).each( function () {
			accounts.push( $( this ).val() );
		} );
		return accounts;
	}

	function populateAccounts() {
		var $container = $( '#pkits-sp-nudge-accounts' );
		if ( ! $container.length ) {
			return;
		}

		var accounts = pkitsSpNudge.accounts || [];
		if ( ! accounts.length ) {
			return;
		}

		var platformLabels = { x: 'X', facebook: 'FB', linkedin: 'in' };

		var html = '';
		for ( var i = 0; i < accounts.length; i++ ) {
			var acc   = accounts[ i ];
			var label = platformLabels[ acc.platform ] || acc.platform.toUpperCase();
			html += '<label class="pkits-sp-account-check">';
			html += '<input type="checkbox" value="' + escAttr( acc.storage_id ) + '" checked />';
			html += '<span class="pkits-sp-platform-badge pkits-sp-badge-' + escAttr( acc.platform ) + '">' + escHtml( label ) + '</span>';
			html += '<span class="pkits-sp-account-label">' + escHtml( acc.label ) + '</span>';
			html += '</label>';
		}
		$container.html( html );
	}

	function preFillCopy() {
		var $textarea = $( '#pkits-sp-nudge-copy' );
		if ( ! $textarea.length ) {
			return;
		}
		// Use resolved template from settings if available, else fall back.
		var copy = pkitsSpNudge.copyTemplate || '';
		if ( ! copy ) {
			var title     = pkitsSpNudge.postTitle || '';
			var permalink = pkitsSpNudge.postPermalink || '';
			copy = title ? title + ( permalink ? ' ' + permalink : '' ) : '';
		}
		$textarea.val( copy ).trigger( 'input' );
	}

	function showResult( type, message ) {
		var $result = $( '#pkits-sp-nudge-result' );
		$result.removeClass( 'success error' ).addClass( type ).text( message ).show();
	}

	function showSuccess( message ) {
		$( '#pkits-sp-nudge-compose' ).hide();
		var $success = $( '#pkits-sp-nudge-success' );
		$success.find( '.pkits-sp-nudge-success-msg' ).text( message );
		$success.show();
	}

	function hideBanner() {
		$( '#pkits-sp-nudge-banner' ).slideUp( 200 );
	}

	function escHtml( str ) {
		return $( '<div>' ).text( str ).html();
	}

	function escAttr( str ) {
		return String( str ).replace( /"/g, '&quot;' ).replace( /'/g, '&#039;' ).replace( /</g, '&lt;' ).replace( />/g, '&gt;' );
	}

} )( jQuery );
