/**
 * Quote Form Frontend — WholesaleNode for WooCommerce
 * Mirrors the pro plugin's quote-form.js structure, stripped to free fields.
 */

( function ( $ ) {
	'use strict';

	var cfg = window.woowsnFreeQuote || {};

	/* ── Product search ─────────────────────────────────────────── */

	function initProductSearch( $form ) {
		var $selects = $form.find( '.woowsn-free-ps-select' );
		if ( ! $selects.length ) return;

		if ( $( '#woowsn-free-ps-styles' ).length === 0 ) {
			$( '<style id="woowsn-free-ps-styles">' ).text(
				'.woowsn-free-ps-wrap{position:relative;}' +
				'.woowsn-free-ps-wrap .woowsn-free-ps-input{width:100%;}' +
				'.woowsn-free-ps-results{position:absolute;z-index:9999;left:0;right:0;max-height:220px;overflow-y:auto;background:#fff;border:1px solid #ced4da;border-top:none;border-radius:0 0 4px 4px;display:none;box-shadow:0 4px 12px rgba(0,0,0,.1);}' +
				'.woowsn-free-ps-results .woowsn-free-ps-item{padding:8px 12px;cursor:pointer;font-size:14px;}' +
				'.woowsn-free-ps-results .woowsn-free-ps-item:hover{background:#f0f6fc;}' +
				'.woowsn-free-ps-results .woowsn-free-ps-no-results{padding:8px 12px;color:#6c757d;font-size:13px;}' +
				'.woowsn-free-ps-selected{display:flex;align-items:center;gap:8px;margin-top:6px;padding:6px 10px;background:#f0f6fc;border:1px solid #bee5eb;border-radius:4px;font-size:13px;}' +
				'.woowsn-free-ps-selected .woowsn-free-ps-remove{margin-left:auto;cursor:pointer;color:#dc3545;font-weight:700;font-size:16px;line-height:1;}'
			).appendTo( 'head' );
		}

		$selects.each( function () {
			var $select   = $( this );
			var fieldName = $select.attr( 'name' );
			var wasReq    = $select.prop( 'required' );

			$select.hide().removeAttr( 'required' ).prop( 'required', false );

			var $wrap     = $( '<div class="woowsn-free-ps-wrap"></div>' );
			var $input    = $( '<input type="text" class="woowsn-free-ps-input" autocomplete="off" />' )
				.attr( 'placeholder', cfg.i18n && cfg.i18n.search_product ? cfg.i18n.search_product : 'Search for a product...' );
			var $results  = $( '<div class="woowsn-free-ps-results"></div>' );
			var $selected = $( '<div class="woowsn-free-ps-selected" style="display:none;"></div>' );

			$wrap.append( $input ).append( $results ).append( $selected );
			$select.after( $wrap );

			var timer = null;

			function doSearch( term ) {
				$results.html( '<div class="woowsn-free-ps-no-results">' + ( cfg.i18n.searching || 'Searching...' ) + '</div>' ).show();
				$.ajax( {
					url: cfg.ajaxurl,
					data: { action: 'woowsn_free_product_search', nonce: cfg.product_search_nonce, term: term },
					success: function ( res ) {
						$results.empty();
						if ( res.success && res.data && res.data.length ) {
							$.each( res.data, function ( _, p ) {
								var label = p.name + ( p.sku ? ' (SKU: ' + p.sku + ')' : '' );
								$( '<div class="woowsn-free-ps-item"></div>' )
									.text( label ).attr( 'data-id', p.id ).attr( 'data-name', p.name )
									.appendTo( $results );
							} );
							$results.show();
						} else {
							$results.html( '<div class="woowsn-free-ps-no-results">' + ( cfg.i18n.no_results || 'No products found' ) + '</div>' ).show();
						}
					}
				} );
			}

			$input.on( 'input', function () {
				clearTimeout( timer );
				var term = $.trim( $( this ).val() );
				if ( term.length < 1 ) { $results.hide().empty(); return; }
				timer = setTimeout( function () { doSearch( term ); }, 300 );
			} );

			$input.on( 'focus', function () {
				if ( ! $.trim( $( this ).val() ) && ! $select.val() ) {
					doSearch( '' );
				}
			} );

			$results.on( 'click', '.woowsn-free-ps-item', function () {
				var id   = $( this ).data( 'id' );
				var name = $( this ).attr( 'data-name' );
				$select.val( id );
				$input.hide();
				$results.hide().empty();
				$selected.html(
					'<span>' + $( '<span>' ).text( name ).html() + '</span>' +
					'<span class="woowsn-free-ps-remove" title="Remove">&times;</span>'
				).show();
				$select.closest( '.woowsn-quote-field' ).removeClass( 'error' ).find( '.field-error' ).remove();
			} );

			$selected.on( 'click', '.woowsn-free-ps-remove', function () {
				$select.val( '' );
				$selected.hide().empty();
				$input.val( '' ).show().focus();
			} );

			if ( wasReq ) {
				$wrap.attr( 'data-required', '1' ).attr( 'data-field-name', fieldName );
			}

			$( document ).on( 'click', function ( e ) {
				if ( ! $( e.target ).closest( $wrap ).length ) $results.hide();
			} );
		} );
	}

	/* ── Popup open / close (same data attributes as pro) ───────── */

	$( document ).on( 'click', '[data-woowsn-popup]', function ( e ) {
		e.preventDefault();
		var id       = $( this ).data( 'woowsn-popup' );
		var $overlay = $( '#' + id + '-overlay' );
		$overlay.fadeIn( 200 );
		$( 'body' ).css( 'overflow', 'hidden' );
	} );

	$( document ).on( 'click', '[data-woowsn-popup-close]', function ( e ) {
		e.preventDefault();
		var id       = $( this ).data( 'woowsn-popup-close' );
		var $overlay = $( '#' + id + '-overlay' );
		$overlay.fadeOut( 200 );
		$( 'body' ).css( 'overflow', '' );
	} );

	$( document ).on( 'click', '.woowsn-quote-popup-overlay', function ( e ) {
		if ( $( e.target ).hasClass( 'woowsn-quote-popup-overlay' ) ) {
			$( this ).fadeOut( 200 );
			$( 'body' ).css( 'overflow', '' );
		}
	} );

	$( document ).on( 'keydown', function ( e ) {
		if ( e.key === 'Escape' ) {
			var $overlay = $( '.woowsn-quote-popup-overlay:visible' );
			if ( $overlay.length ) { $overlay.fadeOut( 200 ); $( 'body' ).css( 'overflow', '' ); }
		}
	} );

	/* ── Form submission ────────────────────────────────────────── */

	$( document ).on( 'click', '.woowsn-free-quote-form .woowsn-quote-submit', function ( e ) {
		e.preventDefault();
		e.stopPropagation();

		var $btn      = $( this );
		var $form     = $btn.closest( '.woowsn-free-quote-form' );
		var $wrapper  = $form.closest( '.woowsn-quote-form-wrapper' );
		var $messages = $wrapper.find( '.woowsn-quote-messages' );

		$messages.hide().empty().removeClass( 'success error' );
		$btn.prop( 'disabled', true ).addClass( 'loading' );

		var formData = {};
		$form.find( 'input, textarea, select' ).each( function () {
			var name = $( this ).attr( 'name' );
			if ( ! name || name === '_wp_http_referer' ) return;
			if ( $( this ).attr( 'type' ) === 'checkbox' ) {
				formData[ name ] = $( this ).is( ':checked' ) ? '1' : '';
			} else if ( $( this ).attr( 'type' ) === 'radio' ) {
				if ( $( this ).is( ':checked' ) ) formData[ name ] = $( this ).val();
			} else {
				formData[ name ] = $( this ).val();
			}
		} );

		formData.form_url = window.location.href;

		$.post( cfg.ajaxurl, formData )
			.done( function ( res ) {
				if ( res.success ) {
					$messages.addClass( 'success' ).html( res.data && res.data.message ? res.data.message : ( cfg.i18n && cfg.i18n.success ? cfg.i18n.success : 'Quote submitted!' ) ).show();
					$form.find( 'input:not([type="hidden"]), textarea' ).val( '' );
					$form.find( 'select' ).prop( 'selectedIndex', 0 );
					$form.find( '.woowsn-free-ps-selected' ).hide().empty();
					$form.find( '.woowsn-free-ps-input' ).val( '' ).show();
					var $overlay = $form.closest( '.woowsn-quote-popup-overlay' );
					if ( $overlay.length ) {
						setTimeout( function () { $overlay.fadeOut( 300 ); $( 'body' ).css( 'overflow', '' ); }, 2500 );
					}
				} else {
					var msg = res.data && res.data.message ? res.data.message : ( cfg.i18n && cfg.i18n.error ? cfg.i18n.error : 'Submission failed.' );
					$messages.addClass( 'error' ).html( msg ).show();
				}
			} )
			.fail( function () {
				$messages.addClass( 'error' ).html( cfg.i18n && cfg.i18n.error ? cfg.i18n.error : 'Submission failed.' ).show();
			} )
			.always( function () {
				$btn.prop( 'disabled', false ).removeClass( 'loading' );
			} );
	} );

	/* ── Init ───────────────────────────────────────────────────── */

	$( document ).ready( function () {
		$( '.woowsn-free-quote-form' ).each( function () {
			initProductSearch( $( this ) );
		} );
	} );

} )( jQuery );
