/* SkyServers Sync — Setup wizard JS */
( function () {
	'use strict';

	if ( typeof window.skyemagWizard === 'undefined' ) {
		window.skyemagWizard = {};
	}

	const w = window.skyemagWizard;
	const cfg = window.skyemagWizardCfg || {};

	w.dirty = false;

	// Mark dirty on any input change so beforeunload can warn the user.
	document.addEventListener( 'input', function ( e ) {
		if ( e.target && e.target.matches( '.skyemag-wizard-content input, .skyemag-wizard-content select, .skyemag-wizard-content textarea' ) ) {
			w.dirty = true;
		}
	} );

	// beforeunload guard — only fires if user typed something.
	window.addEventListener( 'beforeunload', function ( e ) {
		if ( w.dirty ) {
			e.preventDefault();
			e.returnValue = '';
		}
	} );

	// Submitting any form on the wizard page (Back / Next / Finish — open_step_form
	// or the manual Finish form on the Done step) is a legitimate save, so clear
	// the dirty flag before the resulting navigation. wizard.js is enqueued only
	// on the wizard page so any submit here is a wizard action.
	document.addEventListener( 'submit', function () {
		w.dirty = false;
	}, true );

	// Skip modal — opens on close icon (×) and Skip footer button.
	function openSkipModal() {
		const backdrop = document.getElementById( 'skyemag-skip-modal' );
		if ( backdrop ) {
			backdrop.classList.add( 'is-open' );
			const cancel = backdrop.querySelector( '[data-skyemag-skip-cancel]' );
			if ( cancel ) {
				cancel.focus();
			}
		}
	}

	function closeSkipModal() {
		const backdrop = document.getElementById( 'skyemag-skip-modal' );
		if ( backdrop ) {
			backdrop.classList.remove( 'is-open' );
		}
	}

	document.addEventListener( 'click', function ( e ) {
		if ( e.target.closest( '[data-skyemag-wizard-skip]' ) ) {
			e.preventDefault();
			openSkipModal();
		}
		if ( e.target.matches( '[data-skyemag-skip-cancel]' ) ) {
			e.preventDefault();
			closeSkipModal();
		}
		if ( e.target.matches( '[data-skyemag-skip-confirm]' ) ) {
			e.preventDefault();
			confirmSkip();
		}
	} );

	function confirmSkip() {
		const fd = new FormData();
		fd.append( 'action', 'skyemag_setup_skip' );
		fd.append( 'nonce',  cfg.nonce || '' );

		w.dirty = false;
		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( data ) {
				if ( data && data.success && data.data && data.data.redirect ) {
					window.location = data.data.redirect;
				} else {
					window.location = cfg.settingsUrl;
				}
			} )
			.catch( function () {
				window.location = cfg.settingsUrl;
			} );
	}

	function runBootstrap() {
		const btn      = document.getElementById( 'skyemag-bootstrap-button' );
		const progress = document.getElementById( 'skyemag-bootstrap-progress' );
		const fill     = document.getElementById( 'skyemag-bootstrap-fill' );
		const status   = document.getElementById( 'skyemag-bootstrap-status' );
		const result   = document.getElementById( 'skyemag-bootstrap-result' );

		if ( btn ) btn.disabled = true;
		if ( progress ) progress.style.display = '';
		if ( fill )   fill.classList.add( 'is-indeterminate' );
		if ( status ) status.textContent = ( cfg.bootstrapImporting || 'Importing offers from eMAG…' );
		if ( result ) result.innerHTML = '';

		const fd = new FormData();
		fd.append( 'action', 'skyemag_setup_bootstrap_step' );
		fd.append( 'nonce',  cfg.nonce || '' );

		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( data ) {
				if ( fill )   fill.classList.remove( 'is-indeterminate' );
				if ( status ) status.textContent = '';

				if ( ! data || ! data.success ) {
					const msg = ( data && data.data && data.data.message ) || 'Failed';
					if ( result ) result.innerHTML = '<span style="color:#b32d2e;">✗ ' + escapeHtml( msg ) + '</span>';
					if ( btn ) btn.disabled = false;
					return;
				}

				const d = data.data || {};
				if ( fill ) fill.style.width = '100%';
				if ( result ) {
					let msg = '<span style="color:#005a32;">✓ Imported '
						+ ( d.total || 0 ) + ' offers — '
						+ ( d.matched || 0 ) + ' matched, '
						+ ( d.unmatched || 0 ) + ' unmatched</span>';
					if ( d.captured_margins && d.captured_margins > 0 ) {
						msg += '<br><span style="color:#005a32;">✓ Captured '
							+ d.captured_margins
							+ ' per-product margins from your existing eMAG prices</span>';
					}
					result.innerHTML = msg;
				}
				if ( btn ) {
					btn.disabled = false;
					btn.textContent = '✓ ' + ( cfg.bootstrapDone || 'Imported — Run again?' );
				}
			} )
			.catch( function () {
				if ( fill )   fill.classList.remove( 'is-indeterminate' );
				if ( status ) status.textContent = '';
				if ( result ) result.innerHTML = '<span style="color:#b32d2e;">✗ Network error</span>';
				if ( btn ) btn.disabled = false;
			} );
	}

	w.runBootstrap = runBootstrap;

	document.addEventListener( 'click', function ( e ) {
		if ( e.target.closest( '[data-skyemag-bootstrap-run]' ) ) {
			e.preventDefault();
			runBootstrap();
		}
	} );

	// ── IP copy ──────────────────────────────────────────────────────────
	function copyIp() {
		const el = document.getElementById( 'skyemag-server-ip' );
		if ( ! el ) return;
		const text = el.textContent.trim();
		if ( navigator.clipboard ) {
			navigator.clipboard.writeText( text );
		} else {
			const ta = document.createElement( 'textarea' );
			ta.value = text;
			document.body.appendChild( ta );
			ta.select();
			try { document.execCommand( 'copy' ); } catch ( _e ) {}
			document.body.removeChild( ta );
		}
		const btn = document.querySelector( '[data-skyemag-copy-ip]' );
		if ( btn ) {
			const original = btn.textContent;
			btn.textContent = '✓ ' + ( cfg.copiedLabel || 'Copied' );
			setTimeout( function () { btn.textContent = original; }, 1500 );
		}
	}

	// ── Test Connection ───────────────────────────────────────────────────
	function testConnection() {
		const result = document.getElementById( 'skyemag-test-result' );
		if ( result ) result.textContent = ( cfg.testingLabel || 'Testing…' );

		const fd = new FormData();
		fd.append( 'action',   'skyemag_setup_test_connection' );
		fd.append( 'nonce',    cfg.nonce || '' );
		fd.append( 'username', ( document.getElementById( 'skyemag-username' ) || {} ).value || '' );
		fd.append( 'password', ( document.getElementById( 'skyemag-password' ) || {} ).value || '' );
		fd.append( 'region',   ( document.getElementById( 'skyemag-region' )   || {} ).value || '' );

		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( data ) {
				if ( ! result ) return;
				if ( data.success && data.data && data.data.message ) {
					result.innerHTML = '<span style="color:#005a32;">✓ ' + escapeHtml( data.data.message ) + '</span>';
				} else {
					const msg = ( data.data && data.data.message ) || 'Failed';
					result.innerHTML = '<span style="color:#b32d2e;">✗ ' + escapeHtml( msg ) + '</span>';
				}
			} )
			.catch( function () {
				if ( result ) result.innerHTML = '<span style="color:#b32d2e;">✗ Network error</span>';
			} );
	}

	function escapeHtml( s ) {
		return String( s ).replace( /[&<>"']/g, function ( m ) {
			return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[ m ];
		} );
	}

	// ── Brand / EAN Detect (Step 5) ──────────────────────────────────────
	// Reuses the existing SettingsPage::ajax_detect_sources handler.
	function runDetect( kind ) {
		const inputId  = 'skyemag-' + kind;                       // skyemag-brand | skyemag-ean
		const statusId = 'skyemag-detect-' + kind + '-status';    // skyemag-detect-brand-status | …-ean-status
		const btn      = document.querySelector( '[data-skyemag-detect="' + kind + '"]' );
		const input    = document.getElementById( inputId );
		const status   = document.getElementById( statusId );
		if ( ! input || ! status ) return;

		if ( btn ) btn.disabled = true;
		status.innerHTML = '<span style="color:#646970;">' + escapeHtml( cfg.detectingLabel || 'Scanning your products…' ) + '</span>';

		const fd = new FormData();
		fd.append( 'action', 'skyemag_detect_field_sources' );
		fd.append( 'nonce',  cfg.settingsNonce || '' );

		fetch( cfg.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd } )
			.then( function ( r ) { return r.json(); } )
			.then( function ( data ) {
				if ( btn ) btn.disabled = false;
				if ( ! data || ! data.success || ! data.data ) {
					status.innerHTML = '<span style="color:#b32d2e;">' + escapeHtml( cfg.detectErrorLabel || 'Detection failed.' ) + '</span>';
					return;
				}
				const list = ( kind === 'brand' ) ? data.data.brand : data.data.ean;
				if ( ! Array.isArray( list ) || list.length === 0 ) {
					status.innerHTML = '<span style="color:#b32d2e;">' + escapeHtml( cfg.detectNoneLabel || 'No matching meta keys found.' ) + '</span>';
					return;
				}
				const keys  = list.map( function ( r ) { return r.key; } );
				const parts = list.map( function ( r ) {
					return escapeHtml( r.key ) + ' (' + ( r.count | 0 ) + ( r.sample ? ', e.g. ' + escapeHtml( r.sample ) : '' ) + ')';
				} );
				input.value = keys.join( ',' );
				status.innerHTML = '<span style="color:#005a32;">✓ ' + parts.join( ' &nbsp;·&nbsp; ' ) + '</span>';
			} )
			.catch( function () {
				if ( btn ) btn.disabled = false;
				status.innerHTML = '<span style="color:#b32d2e;">' + escapeHtml( cfg.detectErrorLabel || 'Detection failed.' ) + '</span>';
			} );
	}

	// Click delegation for IP copy, Test Connection, Detect, orders toggle.
	document.addEventListener( 'click', function ( e ) {
		if ( e.target.closest( '[data-skyemag-copy-ip]' ) ) {
			e.preventDefault();
			copyIp();
		}
		if ( e.target.closest( '[data-skyemag-test-connection]' ) ) {
			e.preventDefault();
			testConnection();
		}
		const detectBtn = e.target.closest( '[data-skyemag-detect]' );
		if ( detectBtn ) {
			e.preventDefault();
			runDetect( detectBtn.getAttribute( 'data-skyemag-detect' ) );
		}
		if ( e.target.matches( '[data-skyemag-toggle-orders]' ) ) {
			const sub = document.getElementById( 'skyemag-orders-subsection' );
			if ( sub ) sub.style.display = e.target.checked ? '' : 'none';
		}
	} );

	// Expose on namespace.
	w.copyIp         = copyIp;
	w.testConnection = testConnection;
	w.runDetect      = runDetect;

} )();
