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


	// History page - clear all history
	
	// ----------------------------------------------------------------
	// Character counter
	// ----------------------------------------------------------------
	$( '#pkits-sp-copy' ).on( 'input', function () {
		var len = $( this ).val().length;
		var $counter = $( '.pkits-sp-char-counter' );
		$counter.text( len );

		// Warn if over X limit
		if ( len > 280 ) {
			$counter.addClass( 'over-limit' );
		} else {
			$counter.removeClass( 'over-limit' );
		}
	} );

	// ----------------------------------------------------------------
	// Hashtag pills - click to insert at cursor
	// ----------------------------------------------------------------
	$( document ).on( 'click', '.pkits-sp-tag-pill', function () {
		var tag  = '#' + $( this ).data( 'tag' );
		var $ta  = $( '#pkits-sp-copy' );
		var pos  = $ta[0].selectionStart;
		var val  = $ta.val();
		var before = val.substring( 0, pos );
		var after  = val.substring( pos );

		// Add a space before the hashtag if needed
		var separator = ( before.length > 0 && before.slice( -1 ) !== ' ' ) ? ' ' : '';
		var newVal = before + separator + tag + ' ' + after;
		$ta.val( newVal ).trigger( 'input' );

		// Move cursor after inserted tag
		var newPos = pos + separator.length + tag.length + 1;
		$ta[0].setSelectionRange( newPos, newPos );
		$ta.focus();
	} );

	// ----------------------------------------------------------------
	// Post Now
	// ----------------------------------------------------------------
	$( '#pkits-sp-post-now' ).on( 'click', function () {
		var $btn   = $( this );
		var postId = $( '#pkits-sp-metabox' ).data( 'post-id' );
		var copy   = $( '#pkits-sp-copy' ).val().trim();
		var accounts = [];

		$( '.pkits-sp-account-checkbox:checked' ).each( function () {
			accounts.push( $( this ).val() );
		} );

		if ( ! copy ) {
			showResult( 'error', 'Please write some copy before posting.' );
			return;
		}

		if ( accounts.length === 0 ) {
			showResult( 'error', 'Please select at least one account.' );
			return;
		}

		$btn.text( pkitsSpAdmin.strings.posting ).prop( 'disabled', true );
		clearResult();

		var imageUrl = '';
		var $imageCheck = $( '#pkits-sp-include-image' );
		if ( $imageCheck.length && $imageCheck.is( ':checked' ) ) {
			imageUrl = $imageCheck.val();
		}

		$.ajax( {
			url:  pkitsSpAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action:    'pkits_sp_post_now',
				nonce:     pkitsSpAdmin.nonce,
				post_id:   postId,
				copy:      copy,
				accounts:  accounts,
				image_url: imageUrl,
				copy_is_default: ( ( $( '#pkits-sp-copy-default' ).val() || '' ).trim() === copy ) ? '1' : ''
			},
			success: function ( response ) {
				if ( response.success && response.data.results ) {
					var messages = [];
					$.each( response.data.results, function ( i, r ) {
						var icon = r.success ? '\u2713' : '\u2717';
						messages.push( icon + ' ' + r.account + ': ' + r.message );
					} );
					var hasFailure = response.data.results.some( function ( r ) { return ! r.success; } );
					showResult( hasFailure ? 'error' : 'success', messages.join( '\n' ) );
				} else {
					showResult( 'error', response.data.message || 'An error occurred.' );
				}
			},
			error: function () {
				showResult( 'error', 'Request failed. Please try again.' );
			},
			complete: function () {
				$btn.text( 'Post Now' ).prop( 'disabled', false );
			}
		} );
	} );

	// ----------------------------------------------------------------
	// Schedule
	// ----------------------------------------------------------------
	$( '#pkits-sp-schedule' ).on( 'click', function () {
		var $btn         = $( this );
		var postId       = $( '#pkits-sp-metabox' ).data( 'post-id' );
		var copy         = $( '#pkits-sp-copy' ).val().trim();
		var scheduledAt  = $( '#pkits-sp-schedule-time' ).val();
		var accounts     = [];

		$( '.pkits-sp-account-checkbox:checked' ).each( function () {
			accounts.push( $( this ).val() );
		} );

		if ( ! copy ) {
			showResult( 'error', 'Please write some copy before scheduling.' );
			return;
		}

		if ( accounts.length === 0 ) {
			showResult( 'error', 'Please select at least one account.' );
			return;
		}

		if ( ! scheduledAt ) {
			showResult( 'error', 'Please pick a date and time.' );
			return;
		}

		$btn.text( pkitsSpAdmin.strings.scheduling ).prop( 'disabled', true );
		clearResult();

		var imageUrl = '';
		var $imgChk = $( '#pkits-sp-include-image' );
		if ( $imgChk.length && $imgChk.is( ':checked' ) ) {
			imageUrl = $imgChk.val();
		}

		$.ajax( {
			url:  pkitsSpAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action:       'pkits_sp_schedule_post',
				nonce:        pkitsSpAdmin.nonce,
				post_id:      postId,
				copy:         copy,
				accounts:     accounts,
				scheduled_at: scheduledAt,
				image_url:    imageUrl,
				copy_is_default: ( ( $( '#pkits-sp-copy-default' ).val() || '' ).trim() === copy ) ? '1' : ''
			},
			success: function ( response ) {
				if ( response.success ) {
					showResult( 'success', response.data.message );
				} else {
					showResult( 'error', response.data.message || 'Scheduling failed.' );
				}
			},
			error: function () {
				showResult( 'error', 'Request failed. Please try again.' );
			},
			complete: function () {
				$btn.text( 'Schedule' ).prop( 'disabled', false );
			}
		} );
	} );

	// ----------------------------------------------------------------
	// Cancel queue item

	// ----------------------------------------------------------------
	// Delete single queue item

	// ----------------------------------------------------------------
	// Clear failed posts for this post
	// ----------------------------------------------------------------
	$( document ).on( 'click', '.pkits-sp-clear-failed-btn', function () {
		var $btn   = $( this );
		var postId = $btn.data( 'post-id' );

		if ( ! window.confirm( 'Clear all failed posts for this article?' ) ) { return; }

		$btn.text( 'Clearing...' ).prop( 'disabled', true );

		$.ajax( {
			url:  pkitsSpAdmin.ajaxUrl,
			type: 'POST',
			data: {
				action:  'pkits_sp_clear_failed',
				nonce:   pkitsSpAdmin.nonce,
				post_id: postId
			},
			success: function ( response ) {
				if ( response.success ) {
					// Reload the page to reflect cleared items.
					window.location.reload();
				} else {
					alert( 'Error: ' + ( response.data ? response.data.message : 'Could not clear failed posts.' ) );
					$btn.text( 'Clear failed' ).prop( 'disabled', false );
				}
			},
			error: function ( xhr ) {
				alert( 'Request failed. Response: ' + xhr.responseText );
				$btn.text( 'Clear failed' ).prop( 'disabled', false );
			}
		} );
	} );

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

	function clearResult() {
		$( '#pkits-sp-result' ).hide().text( '' );
	}

	// ----------------------------------------------------------------
	// Grouped send controls (Queue panel)
	// ----------------------------------------------------------------
	function pkitsSpAdminIds( el ) {
		return String( $( el ).data( 'queue-ids' ) || '' ).split( ',' ).filter( Boolean );
	}
	function pkitsSpAdminCall( action, ids ) {
		return ids.map( function ( id ) {
			return $.ajax( {
				url:  pkitsSpAdmin.ajaxUrl,
				type: 'POST',
				data: { action: action, nonce: pkitsSpAdmin.nonce, queue_id: id }
			} );
		} );
	}

	$( document ).on( 'click', '.pkits-sp-send-cancel', function () {
		var ids = pkitsSpAdminIds( this );
		if ( ! ids.length || ! window.confirm( 'Cancel this queued send?' ) ) { return; }
		$( this ).text( pkitsSpAdmin.strings.cancelling ).prop( 'disabled', true );
		$.when.apply( $, pkitsSpAdminCall( 'pkits_sp_cancel_queue_item', ids ) ).always( function () {
			window.location.reload();
		} );
	} );

	
	

	// ----------------------------------------------------------------
	// Post History page - clear all / delete a single logged send (free).
	// ----------------------------------------------------------------
	$( document ).on( 'click', '.pkits-sp-clear-all-history-btn', function () {
		if ( ! window.confirm( 'Clear all post history? Pending scheduled posts will not be affected.' ) ) { return; }
		var $btn = $( this ).text( 'Clearing...' ).prop( 'disabled', true );
		$.ajax( {
			url: pkitsSpAdmin.ajaxUrl, type: 'POST',
			data: { action: 'pkits_sp_clear_all_history', nonce: pkitsSpAdmin.nonce },
			success: function () { window.location.reload(); },
			error: function () { $btn.text( 'Clear all history' ).prop( 'disabled', false ); }
		} );
	} );

	$( document ).on( 'click', '.pkits-sp-delete-history-row', function () {
		var $btn    = $( this );
		var queueId = $btn.data( 'queue-id' );

		if ( ! window.confirm( 'Delete this history item?' ) ) { return; }

		$.ajax( {
			url: pkitsSpAdmin.ajaxUrl, type: 'POST',
			data: { action: 'pkits_sp_delete_queue_item', nonce: pkitsSpAdmin.nonce, queue_id: queueId },
			success: function ( r ) {
				if ( r.success ) {
					$btn.closest( '.pkits-sp-send-channel' ).fadeOut( 150, function () {
						var $card = $( this ).closest( '.pkits-sp-send-card' );
						$( this ).remove();
						if ( $card.find( '.pkits-sp-send-channel' ).length === 0 ) {
							$card.remove();
						}
					} );
				}
			}
		} );
	} );

} )( jQuery );
