/**
 * AI Sales Assistant — Admin settings page scripts.
 *
 * @package KwiroAISalesAgent
 */

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

	var $testBtn    = $( '#kwiro-test-connection' );
	var $syncBtn    = $( '#kwiro-trigger-sync' );
	var $status     = $( '#kwiro-connection-status' );
	var $syncStatus = $( '#kwiro-sync-status' );
	var syncPollTimer = null;

	$testBtn.on( 'click', function () {
		$testBtn.prop( 'disabled', true ).text( 'Testing…' );
		$status.text( '' ).css( 'color', '' );

		var apiKey = $( '#kwiro_api_key' ).val();

		$.post( kwiroAdmin.ajaxUrl, {
			action:  'kwiro_test_connection',
			nonce:   kwiroAdmin.nonce,
			api_key: apiKey,
		} )
		.done( function ( response ) {
			if ( response.success ) {
				$status.text( '✓ ' + response.data ).css( 'color', '#00a32a' );
			} else {
				$status.text( '✗ ' + ( response.data || 'Connection failed' ) ).css( 'color', '#d63638' );
			}
		} )
		.fail( function () {
			$status.text( '✗ Request failed — check your server.' ).css( 'color', '#d63638' );
		} )
		.always( function () {
			$testBtn.prop( 'disabled', false ).text( 'Test Connection' );
		} );
	} );

	$syncBtn.on( 'click', function () {
		$syncBtn.prop( 'disabled', true ).text( 'Starting…' );
		$syncStatus.text( '' );

		$.post( kwiroAdmin.ajaxUrl, {
			action: 'kwiro_trigger_sync',
			nonce:  kwiroAdmin.nonce,
		} )
		.done( function ( response ) {
			if ( response.success ) {
				$syncStatus.text( 'Sync started…' ).css( 'color', '#00a32a' );
				startSyncPolling();
			} else {
				$syncStatus.text( response.data || 'Sync failed' ).css( 'color', '#d63638' );
				$syncBtn.prop( 'disabled', false ).text( 'Sync Now' );
			}
		} )
		.fail( function () {
			$syncStatus.text( 'Sync request failed.' ).css( 'color', '#d63638' );
			$syncBtn.prop( 'disabled', false ).text( 'Sync Now' );
		} );
	} );

	function startSyncPolling() {
		if ( syncPollTimer ) clearInterval( syncPollTimer );

		syncPollTimer = setInterval( function () {
			$.post( kwiroAdmin.ajaxUrl, {
				action: 'kwiro_sync_progress',
				nonce:  kwiroAdmin.nonce,
			} )
			.done( function ( response ) {
				if ( ! response.success ) return;

				var d = response.data;
				if ( d.status === 'syncing' ) {
					var text = d.total > 0
						? 'Syncing… ' + d.products_count + ' / ' + d.total + ' products (' + Math.round( ( d.products_count / d.total ) * 100 ) + '%)'
						: 'Syncing… ' + d.products_count + ' products so far';
					$syncStatus.text( text ).css( 'color', '#2271b1' );
				} else if ( d.status === 'complete' ) {
					$syncStatus.text( '✓ Sync complete — ' + d.products_count + ' products synced.' ).css( 'color', '#00a32a' );
					$( '.kwiro-status-value' ).text( 'Complete' ).attr( 'class', 'kwiro-status-value kwiro-status-complete' );
					stopSyncPolling();
				} else if ( d.status === 'error' ) {
					$syncStatus.text( '✗ Sync error: ' + ( d.error_message || 'Unknown error' ) ).css( 'color', '#d63638' );
					$( '.kwiro-status-value' ).text( 'Error' ).attr( 'class', 'kwiro-status-value kwiro-status-error' );
					stopSyncPolling();
				}
			} );
		}, 3000 );
	}

	function stopSyncPolling() {
		if ( syncPollTimer ) { clearInterval( syncPollTimer ); syncPollTimer = null; }
		$syncBtn.prop( 'disabled', false ).text( 'Sync Now' );
	}

	if ( $( '.kwiro-status-syncing' ).length ) {
		$syncBtn.prop( 'disabled', true ).text( 'Syncing…' );
		startSyncPolling();
	}

})( jQuery );
