/**
 * AI Sales Assistant — connect / disconnect / link / API-key UI for the
 * Kwiro settings page. Each block is element-gated so this single file
 * handles all four UI states the settings page can render in (no-key,
 * key-but-not-linked, linked, claimed-recoverable).
 *
 * Strings are passed in via `kwiroAdminConnect` (wp_localize_script) — they
 * are translated in PHP so this file can stay plain JS.
 *
 * @package KwiroAISalesAgent
 */

/* global kwiroAdminConnect */
(function () {
	'use strict';

	var data = window.kwiroAdminConnect || {};
	var ajaxUrl = data.ajaxUrl;
	var nonce   = data.nonce;
	var i18n    = data.i18n || {};

	// Pre-API-key / pre-consent: grant-consent button.
	var grantBtn    = document.getElementById( 'kwiro-grant-consent' );
	var grantStatus = document.getElementById( 'kwiro-consent-status' );
	if ( grantBtn ) {
		grantBtn.addEventListener( 'click', function () {
			grantBtn.disabled = true;
			var original = grantBtn.innerText;
			grantBtn.innerText = i18n.connecting || 'Connecting…';
			if ( grantStatus ) {
				grantStatus.textContent = '';
			}

			var body = 'action=kwiro_grant_consent&nonce=' + encodeURIComponent( nonce );
			fetch( ajaxUrl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: body,
				credentials: 'same-origin'
			} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( res ) {
					if ( res && res.success ) {
						window.location.reload();
						return;
					}
					if ( grantStatus ) {
						grantStatus.textContent = ( res && res.data ) ? res.data : ( i18n.couldNotStart || 'Could not start connect flow.' );
					}
					grantBtn.disabled = false;
					grantBtn.innerText = original;
				} )
				.catch( function () {
					if ( grantStatus ) {
						grantStatus.textContent = i18n.networkError || 'Network error. Try again.';
					}
					grantBtn.disabled = false;
					grantBtn.innerText = original;
				} );
		} );

		var manualPre = document.getElementById( 'kwiro-show-manual-pre' );
		if ( manualPre ) {
			manualPre.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				var input = document.getElementById( 'kwiro_api_key' );
				if ( input ) {
					input.scrollIntoView( { behavior: 'smooth', block: 'center' } );
					input.focus();
				}
			} );
		}
	}

	// Linked state: disconnect button.
	var disconnectBtn    = document.getElementById( 'kwiro-disconnect' );
	var disconnectStatus = document.getElementById( 'kwiro-disconnect-status' );
	if ( disconnectBtn ) {
		disconnectBtn.addEventListener( 'click', function () {
			var confirmText = i18n.disconnectConfirm || 'Disconnect this store from Kwiro?';
			if ( ! window.confirm( confirmText ) ) {
				return;
			}
			disconnectBtn.disabled = true;
			var body = 'action=kwiro_disconnect&nonce=' + encodeURIComponent( nonce );
			fetch( ajaxUrl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: body,
				credentials: 'same-origin'
			} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( res ) {
					if ( res && res.success ) {
						window.location.reload();
						return;
					}
					if ( disconnectStatus ) {
						disconnectStatus.textContent = ( res && res.data ) ? res.data : ( i18n.couldNotDisconnect || 'Could not disconnect. Try again.' );
					}
					disconnectBtn.disabled = false;
				} )
				.catch( function () {
					if ( disconnectStatus ) {
						disconnectStatus.textContent = i18n.networkError || 'Network error. Try again.';
					}
					disconnectBtn.disabled = false;
				} );
		} );
	}

	// Has API key but not linked yet: connect-to-kwiro button.
	var connectBtn    = document.getElementById( 'kwiro-connect-kwiro' );
	var connectStatus = document.getElementById( 'kwiro-connect-status' );
	if ( connectBtn ) {
		connectBtn.addEventListener( 'click', function () {
			connectBtn.disabled = true;
			var original = connectBtn.innerText;
			connectBtn.innerText = i18n.opening || 'Opening Kwiro…';
			if ( connectStatus ) {
				connectStatus.textContent = '';
			}

			var body = 'action=kwiro_begin_link&nonce=' + encodeURIComponent( nonce );
			fetch( ajaxUrl, {
				method: 'POST',
				headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
				body: body,
				credentials: 'same-origin'
			} )
				.then( function ( r ) { return r.json(); } )
				.then( function ( res ) {
					if ( res && res.success && res.data && res.data.connect_url ) {
						window.location.assign( res.data.connect_url );
						return;
					}
					if ( connectStatus ) {
						connectStatus.textContent = ( res && res.data ) ? res.data : ( i18n.couldNotStart || 'Could not start connect flow.' );
					}
					connectBtn.disabled = false;
					connectBtn.innerText = original;
				} )
				.catch( function () {
					if ( connectStatus ) {
						connectStatus.textContent = i18n.networkError || 'Network error. Try again.';
					}
					connectBtn.disabled = false;
					connectBtn.innerText = original;
				} );
		} );

		var manual = document.getElementById( 'kwiro-show-manual' );
		if ( manual ) {
			manual.addEventListener( 'click', function ( e ) {
				e.preventDefault();
				var input = document.getElementById( 'kwiro_api_key' );
				if ( input ) {
					input.scrollIntoView( { behavior: 'smooth', block: 'center' } );
					input.focus();
				}
			} );
		}
	}

	// API key field — Show / Hide / Copy.
	var apiKeyInput = document.getElementById( 'kwiro_api_key' );
	var toggle      = document.getElementById( 'kwiro-toggle-api-key' );
	var copy        = document.getElementById( 'kwiro-copy-api-key' );
	if ( apiKeyInput && toggle ) {
		toggle.addEventListener( 'click', function () {
			var shown = apiKeyInput.type === 'text';
			apiKeyInput.type = shown ? 'password' : 'text';
			toggle.textContent = shown ? ( i18n.show || 'Show' ) : ( i18n.hide || 'Hide' );
			toggle.setAttribute( 'aria-pressed', shown ? 'false' : 'true' );
		} );
	}
	if ( apiKeyInput && copy ) {
		copy.addEventListener( 'click', function () {
			var prev = apiKeyInput.type;
			apiKeyInput.type = 'text';
			apiKeyInput.select();
			apiKeyInput.setSelectionRange( 0, 999 );
			var ok = false;
			try {
				ok = document.execCommand( 'copy' );
			} catch ( e ) {
				/* fall through to clipboard API */
			}
			if ( ! ok && navigator.clipboard ) {
				navigator.clipboard.writeText( apiKeyInput.value );
				ok = true;
			}
			apiKeyInput.type = prev;
			var original = copy.textContent;
			copy.textContent = ok ? ( i18n.copied || 'Copied!' ) : ( i18n.copyFailed || 'Copy failed' );
			setTimeout( function () { copy.textContent = original; }, 1600 );
		} );
	}
})();
