(function(window, document){
	// Klarna Payments v1 Standard Widget Flow
	// Per official Klarna documentation: https://docs.klarna.com/payments/web-payments/integrate-with-klarna-payments/integrate-via-sdk/step-2-checkout/
	//
	// CRITICAL: Customer data MUST be sent in authorize() call (Step 2), NOT in session creation (Step 1)
	// From Klarna docs: "We recommend you don't include customer details when initiating a payment session.
	// Instead, use the authorize() call to share them with Klarna at a later stage of the checkout process when the customer clicks Buy."

	window.wpgvKlarna = {
		clientToken: null,
		sessionId: null,
		purchaseCountry: null,
		lastBillingAddress: null,  // Store billing address used in authorize()
		klarnaLoaded: false,

		handleResponse: function(resp) {
			console.log('wpgvKlarna: handleResponse called with:', resp);

			if (!resp) {
				this.showError('No response from server');
				return;
			}

			// If AJAX returned an error (success: false)
			if (resp.success === false) {
				var errorMsg = (resp.data && resp.data.message) || 'An error occurred. Please try again.';
				console.error('wpgvKlarna: server error:', errorMsg);
				this.showError(errorMsg);
				return;
			}

			// WP AJAX returns success:boolean and data object
			var payload = resp.success ? (resp.data || {}) : null;
			if (!payload) {
				this.showError('Invalid response payload');
				return;
			}

			// Store session data
			this.clientToken = payload.client_token;
			this.sessionId = payload.session_id;
			this.purchaseCountry = payload.purchase_country;

			console.log('wpgvKlarna: session created:', this.sessionId);
			console.log('wpgvKlarna: client_token received');

			// Initialize Klarna widget on page
			this.initializeWidget();
		},

		initializeWidget: function() {
			console.log('wpgvKlarna: initializing Klarna widget');

			if (!this.clientToken) {
				this.showError('No client token available');
				return;
			}

			// Check if Klarna SDK is already loaded
			if (typeof window.Klarna === 'undefined' || typeof window.Klarna.Payments === 'undefined') {
				console.log('wpgvKlarna: Klarna SDK not loaded yet, will load via async callback');
				// Load SDK - it will call klarnaAsyncCallback when ready
				this.loadKlarnaSDK();
			} else {
				console.log('wpgvKlarna: Klarna SDK already loaded');
				this.setupKlarnaPayments();
			}
		},

		loadKlarnaSDK: function() {
			var self = this;
			console.log('wpgvKlarna: loading Klarna SDK from CDN');

			// Set up async callback that Klarna SDK will call when loaded
			// Per official Klarna docs
			window.klarnaAsyncCallback = function() {
				console.log('wpgvKlarna: klarnaAsyncCallback executed - SDK ready');
				self.klarnaLoaded = true;
				self.setupKlarnaPayments();
			};

			// Check if SDK script is already in DOM
			if (document.querySelector('script[src*="klarnacdn"]')) {
				console.log('wpgvKlarna: SDK script already exists in DOM');
				return;
			}

			// Add the official Klarna SDK to page
			// Per official docs: https://x.klarnacdn.net/kp/lib/v1/api.js
			var script = document.createElement('script');
			script.src = 'https://x.klarnacdn.net/kp/lib/v1/api.js';
			script.async = true;

			script.onerror = function() {
				console.error('wpgvKlarna: failed to load Klarna SDK from CDN');
				self.showError('Failed to load payment widget. Please refresh and try again.');
			};

			document.head.appendChild(script);
		},

		setupKlarnaPayments: function() {
			console.log('wpgvKlarna: setting up Klarna Payments');

			var self = this;

			if (typeof window.Klarna === 'undefined' || typeof window.Klarna.Payments === 'undefined') {
				console.error('wpgvKlarna: Klarna.Payments not available');
				this.showError('Payment widget not available');
				return;
			}

			// Initialize Klarna.Payments with client token (as per official docs)
			try {
				window.Klarna.Payments.init({
					client_token: this.clientToken
				});
				console.log('wpgvKlarna: Klarna.Payments.init() called');
			} catch (e) {
				console.error('wpgvKlarna: error initializing Klarna.Payments:', e);
				this.showError('Failed to initialize payment widget');
				return;
			}

			// Load and render payment methods in #klarna-payments-container
			var container = document.getElementById('klarna-payments-container');
			if (!container) {
				console.warn('wpgvKlarna: #klarna-payments-container not found on page');
				this.showError('Payment container not found on page');
				return;
			}

			console.log('wpgvKlarna: calling Klarna.Payments.load()');

			// Load payment methods (as per official docs - NO instance parameter)
			window.Klarna.Payments.load(
				{
					container: '#klarna-payments-container'
				},
				{},
				function(res) {
					console.log('wpgvKlarna: load() callback response:', res);

					// Check if show_form is true (as per official docs)
					if (res.show_form === true) {
						console.log('wpgvKlarna: Klarna available for this purchase');

						// Open the Klarna modal popup
						if (window.wpgvKlarnaModal && typeof window.wpgvKlarnaModal.open === 'function') {
							window.wpgvKlarnaModal.open();
							console.log('wpgvKlarna: Modal opened');
						}

						// Show pay button inside modal and attach handler
						var payBtn = document.querySelector('button[data-action="wpgv-klarna-pay"]');
						if (payBtn) {
							payBtn.style.display = 'flex';
						}
						self.attachAuthorizeHandler();
					} else if (res.show_form === false) {
						console.warn('wpgvKlarna: Klarna not available for this purchase');
						self.showError('Klarna payment is not available for this purchase');
					} else {
						console.log('wpgvKlarna: load response:', res);
					}
				}
			);
		},

		attachAuthorizeHandler: function() {
			console.log('wpgvKlarna: attaching authorize handler to pay button');

			var self = this;
			var payButton = document.querySelector('button[data-action="wpgv-klarna-pay"]');

			if (!payButton) {
				console.warn('wpgvKlarna: pay button with [data-action="wpgv-klarna-pay"] not found');
				return;
			}

			// Remove existing click handlers by cloning
			var newButton = payButton.cloneNode(true);
			payButton.parentNode.replaceChild(newButton, payButton);

			newButton.addEventListener('click', function(e) {
				e.preventDefault();
				console.log('wpgvKlarna: pay button clicked');
				newButton.disabled = true;
				self.authorizePayment(newButton);
			});
		},

		collectBillingData: function() {
			console.log('wpgvKlarna: collecting customer data per Klarna authorize() requirements');

			// Per Klarna official docs: Klarna widget collects customer info in popup
			// We only send what we have, Klarna will collect the rest

			// Don't send billing_address at all - let Klarna collect everything
			// This avoids "Vi fick inte med din adress" error
			var authData = {};

			console.log('wpgvKlarna: authorize() will be called with empty data');
			console.log('wpgvKlarna: Klarna widget will collect all customer information in popup');

			return authData;
		},

		authorizePayment: function(payButton) {
			console.log('wpgvKlarna: calling Klarna.Payments.authorize()');

			var self = this;

			if (typeof window.Klarna === 'undefined' || typeof window.Klarna.Payments === 'undefined') {
				this.showError('Payment widget not available');
				if (payButton) payButton.disabled = false;
				return;
			}

			// Collect billing address data from form if available
			var authData = this.collectBillingData();

			// Store billing address for later use in create order (Step 3)
			this.lastBillingAddress = authData.billing_address;

			console.log('wpgvKlarna: authorize() will be called with data:', authData);

			// Authorize payment (as per official docs)
			// Per Klarna docs: This opens popup where customer enters/confirms payment details
			window.Klarna.Payments.authorize(
				{},
				authData,
				function(result) {
					console.log('wpgvKlarna: authorize() callback response:', result);

					if (payButton) payButton.disabled = false;

					if (result.approved === true) {
						console.log('wpgvKlarna: authorization approved');
						console.log('wpgvKlarna: authorization_token:', result.authorization_token);

						// Send authorization token to server for order capture
						if (result.authorization_token) {
							self.confirmAuthorization(result.authorization_token);
						} else {
							self.showError('No authorization token received');
						}
					} else if (result.approved === false && result.show_form === true) {
						// Customer needs to complete the form or try again
						// Per Klarna docs: "The form is still available and the customer can retry"
						console.warn('wpgvKlarna: authorization not approved, but form still available for retry');
						console.log('wpgvKlarna: Customer can retry authorization in the Klarna popup');

						// Don't show error - the Klarna popup is still open and customer can retry
						// Only show error if there are invalid fields highlighted
						if (result.error && result.error.invalid_fields) {
							console.error('wpgvKlarna: invalid fields:', result.error.invalid_fields);
							// Klarna widget will highlight the invalid fields
						}

						// Re-enable button so customer can try again
						if (payButton) payButton.disabled = false;
					} else {
						console.error('wpgvKlarna: authorization error:', result);
						self.showError('Payment authorization failed. Please try again.');
					}
				}
			);
		},

		confirmAuthorization: function(authToken) {
			console.log('wpgvKlarna: confirming authorization with server');

			var self = this;
			var ajaxUrl = typeof wpgv_klarna_vars !== 'undefined' ? wpgv_klarna_vars.ajaxurl : '/wp-admin/admin-ajax.php';
			var nonce = typeof wpgv_klarna_vars !== 'undefined' ? wpgv_klarna_vars.nonce : '';

			// Send billing_address along with authorization_token
			// Per Klarna Step 3 docs: billing_address must match authorize() call
			jQuery.ajax({
				url: ajaxUrl,
				type: 'POST',
				data: {
					action: 'wpgv_klarna_authorize',
					session_id: this.sessionId,
					authorization_token: authToken,
					billing_address: JSON.stringify(this.lastBillingAddress),  // Send billing address used in authorize()
					nonce: nonce
				},
				success: function(response) {
					console.log('wpgvKlarna: authorization confirmed by server');
					if (response.success) {
						console.log('wpgvKlarna: order created, redirecting to success page');
						// Close modal before redirect
						if (window.wpgvKlarnaModal && typeof window.wpgvKlarnaModal.close === 'function') {
							window.wpgvKlarnaModal.close();
						}
						// Redirect to success page
						if (response.data && response.data.redirect_url) {
							window.location.href = response.data.redirect_url;
						} else {
							self.showError('Payment successful but redirect URL not available');
						}
					} else {
						console.error('wpgvKlarna: authorization confirmation failed:', response);
						self.showError(response.data && response.data.message ? response.data.message : 'Payment confirmation failed');
					}
				},
				error: function(xhr, status, error) {
					console.error('wpgvKlarna: AJAX error:', error);
					self.showError('Communication error with server');
				}
			});
		},

		showError: function(message) {
			console.error('wpgvKlarna: error -', message);

			// Create error modal
			var modal = document.getElementById('wpgv-klarna-error-modal');
			if (!modal) {
				modal = document.createElement('div');
				modal.id = 'wpgv-klarna-error-modal';
				modal.style.position = 'fixed';
				modal.style.top = '0';
				modal.style.left = '0';
				modal.style.width = '100%';
				modal.style.height = '100%';
				modal.style.background = 'rgba(0,0,0,0.7)';
				modal.style.display = 'flex';
				modal.style.alignItems = 'center';
				modal.style.justifyContent = 'center';
				modal.style.zIndex = '10000';

				var inner = document.createElement('div');
				inner.style.background = '#fff';
				inner.style.borderRadius = '8px';
				inner.style.padding = '30px';
				inner.style.maxWidth = '500px';
				inner.style.textAlign = 'center';

				var title = document.createElement('h3');
				title.style.marginTop = '0';
				title.style.color = '#d32f2f';
				title.innerText = 'Payment Error';

				var msg = document.createElement('p');
				msg.style.marginBottom = '20px';
				msg.style.fontSize = '16px';
				msg.style.lineHeight = '1.5';
				msg.style.color = '#333';
				msg.innerText = message;

				var closeBtn = document.createElement('button');
				closeBtn.type = 'button';
				closeBtn.innerText = 'Close';
				closeBtn.style.padding = '10px 20px';
				closeBtn.style.background = '#0070f3';
				closeBtn.style.color = '#fff';
				closeBtn.style.border = 'none';
				closeBtn.style.borderRadius = '4px';
				closeBtn.style.cursor = 'pointer';
				closeBtn.onclick = function(){
					modal.style.display = 'none';
					history.back();
				};

				inner.appendChild(title);
				inner.appendChild(msg);
				inner.appendChild(closeBtn);
				modal.appendChild(inner);
				document.body.appendChild(modal);
			} else {
				modal.style.display = 'flex';
			}
		}
	};

})(window, document);
