/* =============================================================================
 * Storzen — Quick Checkout (frontend)
 *
 * Flow:
 *   1. User clicks .storzen-qc-btn → AJAX `prep` fetches form HTML
 *   2. Modal opens with form
 *   3. User fills + submits → AJAX `place` creates order + processes payment
 *   4. Redirect to thank-you (or stay/custom)
 *
 * Variable products gracefully fall back to the full checkout URL.
 * ========================================================================== */
(function ($) {
	'use strict';

	if (typeof szQuickCheckout === 'undefined') { return; }

	var QC = {
		ajaxUrl: szQuickCheckout.ajaxUrl,
		nonce:   szQuickCheckout.nonce,
		i18n:    szQuickCheckout.i18n || {},

		init: function () {
			this.bindButton();
			this.bindModal();
			this.bindFormSubmit();
		},

		// ── Buy Now button click ────────────────────────────────────────
		bindButton: function () {
			var self = this;
			$(document).on('click', '.storzen-qc-btn', function (e) {
				e.preventDefault();
				var $btn = $(this);
				var pid  = parseInt($btn.data('product-id'), 10);
				var type = $btn.data('product-type');
				if (!pid) return;

				// Variable products: redirect to single product page where
				// variations can be picked, not directly into the quick modal.
				if (type === 'variable') {
					self.toast(self.i18n.variableNote || 'Choose variations on the product page.');
					return;
				}

				self.openWithProduct(pid);
			});
		},

		openWithProduct: function (productId) {
			var self = this;
			var $body = $('#storzen-qc-modal [data-storzen-qc-body]');
			$body.html('<div class="storzen-qc-loading">' + (self.i18n.loading || 'Loading…') + '</div>');
			self.openModal();

			$.post(self.ajaxUrl, {
				action:     'storzen_qc_prep',
				nonce:      self.nonce,
				product_id: productId
			})
				.done(function (res) {
					if (res && res.success && res.data && res.data.html) {
						$body.html(res.data.html);
					} else {
						var msg = (res && res.data && res.data.message) || self.i18n.errorGeneric;
						var fallbackUrl = (res && res.data && res.data.fallback_url) || '';
						var html = '<div class="storzen-qc-error">' + msg + '</div>';
						if (fallbackUrl) {
							html += '<p style="text-align:center;margin-top:12px"><a href="' + fallbackUrl + '">' + self.i18n.fullCheckout + '</a></p>';
						}
						$body.html(html);
					}
				})
				.fail(function () {
					$body.html('<div class="storzen-qc-error">' + self.i18n.errorGeneric + '</div>');
				});
		},

		// ── Modal open/close ────────────────────────────────────────────
		bindModal: function () {
			var self = this;
			$(document).on('click', '[data-storzen-qc-close]', function (e) {
				e.preventDefault();
				self.closeModal();
			});
			$(document).on('keydown', function (e) {
				if (e.key === 'Escape' && $('#storzen-qc-modal').hasClass('is-open')) {
					self.closeModal();
				}
			});
		},

		openModal: function () {
			$('#storzen-qc-modal').addClass('is-open').attr('aria-hidden', 'false');
			$('body').addClass('storzen-qc-modal-open');
		},

		closeModal: function () {
			$('#storzen-qc-modal').removeClass('is-open').attr('aria-hidden', 'true');
			$('body').removeClass('storzen-qc-modal-open');
		},

		// ── Form submission ─────────────────────────────────────────────
		bindFormSubmit: function () {
			var self = this;
			$(document).on('submit', '[data-storzen-qc-form]', function (e) {
				e.preventDefault();
				var $form  = $(this);
				var $err   = $form.find('[data-storzen-qc-error]');
				var $btn   = $form.find('.storzen-qc-submit');

				$err.hide().text('');

				// HTML5 validation
				var formEl = $form[0];
				if (typeof formEl.reportValidity === 'function' && !formEl.reportValidity()) {
					return;
				}

				// Collect data
				var data = {
					action:     'storzen_qc_place',
					nonce:      self.nonce,
					product_id: parseInt($form.data('product-id'), 10)
				};
				$form.serializeArray().forEach(function (f) { data[f.name] = f.value; });

				$btn.prop('disabled', true).text(self.i18n.placing || 'Placing…');

				$.post(self.ajaxUrl, data)
					.done(function (res) {
						if (res && res.success && res.data) {
							if (res.data.redirect) {
								window.location.href = res.data.redirect;
							} else {
								// "stay" mode — show inline success
								$form.replaceWith(
									'<div class="storzen-qc-success" style="text-align:center;padding:30px 20px">' +
										'<div style="font-size:40px;margin-bottom:10px">✓</div>' +
										'<p style="font-size:15px;font-weight:600;margin:0 0 6px">' +
											(self.i18n.success || 'Order placed!') +
										'</p>' +
										'<p style="font-size:13px;color:#6b7280;margin:0">' +
											'Order #' + res.data.order_id +
										'</p>' +
									'</div>'
								);
							}
						} else {
							var msg = (res && res.data && res.data.message) || self.i18n.errorGeneric;
							$err.text(msg).show();
							$btn.prop('disabled', false).text('Place Order');
						}
					})
					.fail(function (xhr) {
						var msg = self.i18n.errorGeneric;
						try {
							var r = JSON.parse(xhr.responseText);
							if (r && r.data && r.data.message) { msg = r.data.message; }
						} catch (e) { /* ignore */ }
						$err.text(msg).show();
						$btn.prop('disabled', false).text('Place Order');
					});
			});
		},

		toast: function (msg) {
			var $t = $('<div role="alert"></div>')
				.css({
					position: 'fixed', bottom: '24px', left: '50%',
					transform: 'translateX(-50%)', background: '#1f2937',
					color: '#fff', padding: '10px 18px', borderRadius: '6px',
					fontSize: '13px', zIndex: 10000
				})
				.text(msg);
			$('body').append($t);
			setTimeout(function () { $t.fadeOut(300, function () { $(this).remove(); }); }, 2500);
		}
	};

	$(function () { QC.init(); });
	window.StorzenQuickCheckout = QC;

})(jQuery);
