<div class="modal fade" id="quickOrderModal" tabindex="-1" aria-labelledby="quickOrderModalLabel" aria-hidden="true">
    <link rel="stylesheet" href="catalog/view/theme/oct_promo/stylesheet/intlTelInput.css" />
    <script src="catalog/view/theme/oct_promo/js/intlTelInput.min.js"></script>
    <div class="modal-dialog modal-dialog-centered wide">
        <div class="modal-content">
            <div class="modal-header p-4 bg-grey">
                <h5 class="modal-title fsz-20 fw-700 d-flex align-items-center justify-content-between dark-text" id="quickOrderModalLabel">{{ heading_title }}</h5>
                <button type="button" class="btn-close br-8 bg-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div id="one-click-main-block" class="modal-body p-4">
                <form action="javascript:;" class="modal-body-form d-flex flex-column flex-md-row" id="oct_purchase_form" method="post">
                    <div class="modal-body-product pe-md-4 flex-grow-1 mb-4">
                        <div class="d-flex">
                            {% if thumb is defined %}
                                <div class="modal-body-product-img br-8 overflow-hidden">
                                    <img src="{{ thumb }}"  width="120" height="120" alt="{{ heading_title_product }}">
                                </div>
                            {% endif %}
                            <div class="modal-body-product-info dark-text flex-grow-1 d-flex flex-column{% if thumb is defined %} ps-3{% endif %}">
                                <div class="modal-body-product-title fw-600 fsz-14 mb-3">{{ product_name }}</div>
                                {% if price %}
                                    {% if not special %}
                                        <div class="pr-price-new fsz-20 fw-600 dark-text pb-3">{{ price }}</div>
                                    {% else %}
                                        <div class="pr-price-old light-text text-decoration-line-through fsz-14">{{ price }}</div>
                                        <div class="pr-price-new fsz-20 fw-600 dark-text pb-3">{{ special }}</div>
                                    {% endif %}
                                    {% if oct_popup_purchase_data.quantity is defined %}
                                        <div class="pr-modal-quantity buttons-quantity d-inline-flex align-items-center justify-content-start mt-auto align-self-start">
                                            <button type="button" aria-label="Minus" class="button button-light button-small pr-minus p-2 br-8" onclick="updatePurchaseValue(true, false, false);">
                                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <g>
                                                        <path d="M3.33333 7.5L12.6667 7.5C12.9427 7.5 13.1667 7.724 13.1667 8C13.1667 8.276 12.9427 8.5 12.6667 8.5L3.33333 8.5C3.05733 8.5 2.83333 8.276 2.83333 8C2.83333 7.724 3.05733 7.5 3.33333 7.5Z" fill="#25314C"></path>
                                                    </g>
                                                </svg>
                                            </button>
                                            <input type="text" id="popup-purchase-input-quantity" class="form-control number" name="quantity" value="{{ minimum }}" inputmode="numeric" aria-label="Quantity">
                                            <button type="button" aria-label="Plus" class="button button-light button-small pr-plus p-2 br-8" onclick="updatePurchaseValue(false, true, false);">
                                                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                    <g>
                                                        <path d="M2.83341 8.00009C2.83341 7.72409 3.05741 7.50009 3.33341 7.50009L7.50008 7.50009L7.50008 3.33342C7.50008 3.05742 7.72408 2.83342 8.00008 2.83342C8.27608 2.83342 8.50008 3.05742 8.50008 3.33342L8.50008 7.50009L12.6667 7.50008C12.9427 7.50008 13.1667 7.72408 13.1667 8.00008C13.1667 8.27608 12.9427 8.50008 12.6667 8.50008L8.50008 8.50009L8.50008 12.6668C8.50008 12.9428 8.27608 13.1668 8.00008 13.1668C7.72408 13.1668 7.50008 12.9428 7.50008 12.6668L7.50008 8.50009L3.33342 8.50009C3.05742 8.50009 2.83342 8.27609 2.83341 8.00009Z" fill="#25314C"></path>
                                                    </g>
                                                </svg>
                                            </button>
                                            <input type="hidden" id="popup-purchase-min-quantity" value="{{ minimum }}" name="min_quantity">
                                            <input type="hidden" id="popup-purchase-max-quantity" value="{{ max_quantity }}" name="max_quantity">
                                        </div>
                                    {% else %}
                                        <input type="hidden" id="popup-purchase-input-quantity" name="quantity" value="{{ minimum }}" />
                                    {% endif %}
                                {% endif %}
                            </div>
                        </div>
                        {% if price %}
                            {% if options %}
                                <div class="pr-product-options modal-body-options mt-4 d-flex flex-column gap-4" id="pr-purchase-options-box">
                                    {% for option in options %}
                                        {% if option.type == 'select' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-700 dark-text fsz-14 mb-2" for="input-option{{ option.product_option_id }}">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>
                                                    {% endif %}
                                                </label>
                                                <select name="option[{{ option.product_option_id }}]" id="input-option{{ option.product_option_id }}" class="form-select form-control">
                                                    <option value="">{{ text_select }}</option>
                                                    {% for option_value in option.product_option_value %}
                                                        <option value="{{ option_value.product_option_value_id }}">{{ option_value.name }}
                                                            {% if option_value.price %}
                                                                ({{ option_value.price_prefix }}{{ option_value.price }})
                                                            {% endif %}
                                                        </option>
                                                    {% endfor %}
                                                </select>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'radio' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </label>
                                                <div id="input-option{{ option.product_option_id }}" class="options-box d-flex gap-2 flex-wrap">
                                                    {% for option_value in option.product_option_value %}
                                                        <div class="radio">
                                                            <label data-bs-toggle="tooltip" data-bs-placement="top" class="option optid-{{ option.product_option_id }} not-selected {% if option_value.image %} radio-img{% else %}pr-radio{% endif %}" title="{{ option_value.name }} {% if option_value.price %}{{ option_value.price_prefix }}{{ option_value.price }}{% endif %}">
                                                                <input type="radio" name="option[{{ option.product_option_id }}]" value="{{ option_value.product_option_value_id }}" class="input-radio"/>
                                                                {% if option_value.image %}
                                                                    <img src="{{ option_value.image }}" alt="{{ option_value.name }} {% if option_value.price %} {{ option_value.price_prefix }} {{ option_value.price }} {% endif %}" width="50" height="50" />
                                                                {% else %}
                                                                    {{ option_value.name }}
                                                                {% endif %}
                                                            </label>
                                                            <script>
                                                                $(document).ready(function() {
                                                                    $(document).on('touchstart click', 'label.optid-{{ option.product_option_id }}', function(event) {
                                                                        $('label.optid-{{ option.product_option_id }}').removeClass('selected').addClass('not-selected');
                                                                        $(this).removeClass('not-selected').addClass('selected');
                                                                    });
                                                                });
                                                            </script>
                                                        </div>
                                                    {% endfor %}
                                                </div>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'checkbox' %}
                                            <div class="form-group">
                                                <div class="pr-control-label fw-500 dark-text fsz-14 mb-2">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </div>
                                                <div id="input-option{{ option.product_option_id }}">
                                                    {% for option_value in option.product_option_value %}
                                                        <div class="form-check">
                                                            <input type="checkbox" id="option[{{ option.product_option_id }}][{{ option_value.product_option_value_id }}]" name="option[{{ option.product_option_id }}][]" value="{{ option_value.product_option_value_id }}" class="form-check-input">
                                                            <label class="form-check-label d-flex align-items-center" for="option[{{ option.product_option_id }}][{{ option_value.product_option_value_id }}]">
                                                                {% if option_value.image %}<img src="{{ option_value.image }}" alt="{{ option_value.name }} {% if option_value.price %} {{ option_value.price_prefix }} {{ option_value.price }} {% endif %}" class="img-thumbnail" width="50" height="50" />{% endif %}
                                                                {{ option_value.name }}
                                                                {% if option_value.price %}
                                                                    ({{ option_value.price_prefix }}{{ option_value.price }})
                                                                {% endif %}
                                                            </label>
                                                        </div>
                                                    {% endfor %}
                                                </div>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'text' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2" for="input-option{{ option.product_option_id }}">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>
                                                    {% endif %}
                                                </label>
                                                <input type="text" name="option[{{ option.product_option_id }}]" value="{{ option.value }}" placeholder="{{ option.name }}" id="input-option{{ option.product_option_id }}" class="form-control" inputmode="text">
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'textarea' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2" for="input-option{{ option.product_option_id }}">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </label>
                                                <textarea name="option[{{ option.product_option_id }}]" rows="5" placeholder="{{ option.name }}" id="input-option{{ option.product_option_id }}" class="form-control">{{ option.value }}</textarea>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'file' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2 d-block">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </label>
                                                <button type="button" id="popup-button-upload{{ option.product_option_id }}" data-loading-text="{{ text_loading }}" class="button button-outline button-outline-primary br-7">
                                                    <i class="fa fa-upload me-2"></i>
                                                    {{ button_upload }}</button>
                                                <input type="hidden" name="option[{{ option.product_option_id }}]" value="" id="input-option{{ option.product_option_id }}"/>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'date' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2" for="input-option{{ option.product_option_id }}">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </label>
                                                <div class="input-group date">
                                                    <input type="date" name="option[{{ option.product_option_id }}]" value="{{ option.value }}" id="input-option{{ option.product_option_id }}" class="form-control"/>
                                                </div>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'datetime' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2" for="input-option{{ option.product_option_id }}">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </label>
                                                <div class="input-group datetime">
                                                    <input type="datetime-local" name="option[{{ option.product_option_id }}]" value="{{ option.value }}" id="input-option{{ option.product_option_id }}" class="form-control"/>
                                                </div>
                                            </div>
                                        {% endif %}
                                        {% if option.type == 'time' %}
                                            <div class="form-group">
                                                <label class="pr-control-label fw-500 dark-text fsz-14 mb-2" for="input-option{{ option.product_option_id }}">{{ option.name }}
                                                    {% if option.required %}
                                                        <span class="required"> *</span>{% endif %}
                                                </label>
                                                <div class="input-group time">
                                                    <input type="time" name="option[{{ option.product_option_id }}]" value="{{ option.value }}" id="input-option{{ option.product_option_id }}" class="form-control"/>
                                                </div>
                                            </div>
                                        {% endif %}
                                    {% endfor %}
                                </div>
                            {% endif %}
                        {% endif %}
                        <div class="pr-modal-text text-center fsz-14 fw-500 mt-4 pt-4 border-top">
                            <div class="dark-text">{{ enter_text_title }}</div>
                            <div class="light-text mt-3">{{ enter_text }}</div>
                        </div>
                    </div>
                    <div class="modal-body-inputs flex-grow-1">
                        {% if oct_popup_purchase_data.firstname %}
                            <div class="input-group">
                                <span class="input-group-text" id="usernamePopupPurchaseIcon">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18" fill="none">
                                        <path d="M8.73803 10.9984H5.11457C2.84216 10.9984 1 12.8405 1 15.1129C1 15.4917 1.30703 15.7987 1.68576 15.7987H6.647M13.4308 10.8284L15.571 12.9685M10.8007 4.79794C10.8007 6.67584 9.27834 8.19817 7.40044 8.19817C5.52254 8.19817 4.00021 6.67584 4.00021 4.79794C4.00021 2.92004 5.52254 1.39771 7.40044 1.39771C9.27834 1.39771 10.8007 2.92004 10.8007 4.79794ZM11.546 16.3612L10.1232 16.5983C9.93373 16.6299 9.76942 16.4656 9.80101 16.2761L10.0381 14.8533C10.1204 14.3599 10.3547 13.9044 10.7085 13.5507L14.5084 9.75083C14.977 9.28216 15.7369 9.28216 16.2055 9.75083L16.6485 10.1938C17.1172 10.6625 17.1172 11.4223 16.6485 11.891L12.8486 15.6909C12.4949 16.0446 12.0395 16.279 11.546 16.3612Z" stroke="#5C6168" stroke-linecap="round" stroke-linejoin="round"></path>
                                    </svg>
                                </span>
                                <div class="form-floating">
                                    <input type="text" name="name" value="{{ user_name }}" class="form-control" id="inputPurchaseName" placeholder="{{ enter_firstname }}" inputmode="text" aria-label="Username" aria-describedby="usernamePopupPurchaseIcon">
                                    <label class="px-3 secondary-text fsz-14" for="inputPurchaseName">{{ enter_firstname }}</label>
                                </div>
                            </div>
                        {% endif %}
                        {% if oct_popup_purchase_data.telephone %}
                            <div class="input-group mt-4">
                                <span class="input-group-text" id="telPopupPurchaseIcon">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="12" height="18" viewBox="0 0 12 18" fill="none">
                                        <path d="M5.20005 2.9C4.92391 2.9 4.70005 3.12386 4.70005 3.4C4.70005 3.67614 4.92391 3.9 5.20005 3.9L5.20005 2.9ZM6.80005 3.9C7.07619 3.9 7.30005 3.67614 7.30005 3.4C7.30005 3.12386 7.07619 2.9 6.80005 2.9L6.80005 3.9ZM8.40005 16.5L3.60005 16.5L3.60005 17.5L8.40005 17.5L8.40005 16.5ZM1.70005 14.6L1.70005 3.4L0.70005 3.4L0.700049 14.6L1.70005 14.6ZM3.60005 1.5L8.40005 1.5L8.40005 0.5L3.60005 0.499999L3.60005 1.5ZM10.3001 3.4L10.3 14.6L11.3 14.6L11.3001 3.4L10.3001 3.4ZM8.40005 1.5C9.44939 1.5 10.3001 2.35066 10.3001 3.4L11.3001 3.4C11.3001 1.79837 10.0017 0.5 8.40005 0.5L8.40005 1.5ZM1.70005 3.4C1.70005 2.35066 2.55071 1.5 3.60005 1.5L3.60005 0.499999C1.99842 0.499999 0.70005 1.79837 0.70005 3.4L1.70005 3.4ZM3.60005 16.5C2.55071 16.5 1.70005 15.6493 1.70005 14.6L0.700049 14.6C0.700049 16.2016 1.99842 17.5 3.60005 17.5L3.60005 16.5ZM8.40005 17.5C10.0017 17.5 11.3 16.2016 11.3 14.6L10.3 14.6C10.3 15.6493 9.44939 16.5 8.40005 16.5L8.40005 17.5ZM5.20005 3.9L6.80005 3.9L6.80005 2.9L5.20005 2.9L5.20005 3.9Z" fill="#5C6168"></path>
                                    </svg>
                                </span>
                                <div class="form-floating">
                                    <input type="tel" inputmode="numeric" class="form-control" id="inputPurchasePhone" name="mask_telephone_display" value="{{ user_telephone }}" placeholder="" aria-label="Telephone" aria-describedby="telPopupPurchaseIcon">
                                    <input type="hidden" id="full_telephone" name="telephone" value="{{ user_telephone }}">
                                </div>
                            </div>
                        {% endif %}
                        {% if oct_popup_purchase_data.email %}
                            <div class="input-group mt-4">
                                <span class="input-group-text" id="emailPopupPurchaseIcon">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="14" viewBox="0 0 18 14" fill="none">
										<path d="M17 3.0001V11.0001C17 12.3256 15.9255 13.4001 14.6 13.4001H3.4C2.07452 13.4001 1 12.3256 1 11.0001V3.0001M17 3.0001C17 1.67461 15.9255 0.600098 14.6 0.600098H3.4C2.07452 0.600098 1 1.67461 1 3.0001M17 3.0001V3.25406C17 3.83757 16.6823 4.37481 16.1711 4.65601L10.1566 7.96396C9.43641 8.36007 8.56359 8.36007 7.8434 7.96396L1.82893 4.65601C1.31765 4.37481 1 3.83757 1 3.25406V3.0001" stroke="#5C6168" stroke-linecap="round" stroke-linejoin="round"></path>
									</svg>
                                </span>
                                <div class="form-floating">
                                    <input type="email" name="email" value="{{ user_email }}" class="form-control" id="inputPurchaseMail" placeholder="{{ enter_email }}" inputmode="email" aria-label="email" aria-describedby="emailPopupPurchaseIcon">
                                    <label class="px-3 secondary-text fsz-14" for="inputPurchaseMail">{{ enter_email }}</label>
                                </div>
                            </div>
                        {% endif %}
                        {% if oct_popup_purchase_data.comment %}
                            <div class="form-group pt-4">
                                <textarea name="comment" class="form-control" id="inputPurchaseComment" placeholder="{{ enter_comment }}" rows="11"></textarea>
                            </div>
                        {% endif %}
                        <input type="hidden" name="product_id" value="{{ product_id }}"/>
                        <input type="hidden" name="popup_csrf_token" value="{{ popup_csrf_token }}"/>
                        {% if text_agree %}
                            <div class="form-check d-flex align-items-center gap-2 py-3">
                                <input id="agreePurchaseCheck" type="checkbox" class="form-check-input" name="agree">
                                <label class="form-check-label d-flex align-items-center fsz-12 dark-text" for="agreePurchaseCheck">
                                    {{ text_agree }}
                                </label>
                            </div>
                        {% endif %}
                        {{ captcha }}
                        <button id="button_checkout" type="submit" class="button button-primary button-large w-100 py-3 fsz-14{% if not text_agree %} mt-4{% endif %}">{{ button_checkout }}</button>
                    </div>
                </form>
                <div class="pr-popup-success d-none flex-column align-items-center text-center">
                    <div id="pr-popup-success-text"></div>
                    <div class="d-flex align-items-center justify-content-center mb-4">
                        <svg xmlns="http://www.w3.org/2000/svg" width="164" height="164" viewBox="0 0 164 164" fill="none" class="oct-success-svg">
                            <rect class="oct-outer-circle" width="164" height="164" rx="82" fill="#E0FFE5"/>
                            <rect class="oct-inner-circle" x="32" y="32" width="100" height="100" rx="50" fill="#4CD964"/>
                            <path class="oct-checkmark" d="M100.04 68.6039L97.6421 66.6739C96.4601 65.7239 95.7731 65.7349 94.7611 66.9849L77.3321 88.4939L69.2211 81.7549C68.1021 80.8149 67.4021 80.8649 66.4821 82.0149L64.6311 84.4249C63.6921 85.6069 63.8121 86.2779 64.9221 87.2049L76.4821 96.7669C77.6721 97.7669 78.3421 97.6639 79.2621 96.5449L100.341 71.4839C101.331 70.2939 101.271 69.5829 100.04 68.6039Z" fill="white"/>
                        </svg>
                    </div>
					<button type="button" class="button button-primary button-large w-100 py-3 fsz-14" data-bs-dismiss="modal">{{ text_continue }}</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="smsVerificationModalPopup" tabindex="-1" aria-labelledby="smsModalLabelPopup" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered">
		<div class="modal-content">
            <div class="modal-header p-4 bg-grey">
				<h5 class="modal-title fsz-20 fw-700 d-flex align-items-center justify-content-between dark-text" id="smsModalLabelPopup">{{ text_sms_verify_title }}</h5>
				<button type="button" class="btn-close br-8 bg-white" data-bs-dismiss="modal" aria-label="Close"></button>
			</div>
			<div class="modal-body">
				<p class="mb-3 dark-text">{{ text_sms_verify_desc }}</p>
				<div class="mb-3">
					<input type="text" 
						id="sms-code-input-popup" 
						class="form-control text-center fs-4" 
						maxlength="4" 
						placeholder="0000" 
						inputmode="numeric" 
						pattern="[0-9]*" 
						autocomplete="one-time-code"
						aria-label="{{ text_sms_code }}">
				</div>
				<div id="sms-error-popup" class="alert alert-danger d-none"></div>
				<div id="sms-timer-popup" class="text-center grey-text fsz-14 mb-3">
					{{ text_resend_in }} <span id="timer-seconds-popup" class="fw-600 text-danger mx-1">60</span> {{ text_seconds }}
				</div>
			</div>
			<div class="modal-footer">
				<button type="button" class="button button-primary button-large w-100 py-3 fsz-14" id="btn-verify-sms-popup">{{ button_verify }}</button>
				<button type="button" class="button button-secondary w-100 mt-2" id="btn-resend-sms-popup" disabled>{{ button_resend }}</button>
			</div>
		</div>
	</div>
</div>

<script>
if (typeof purchaseIti === 'undefined') {
	var purchaseIti = null;
}

if (typeof purchasePhoneMasks === 'undefined') {
	var purchasePhoneMasks = {};
	try {
		const phoneMasksJson = {{ phone_masks|raw }};
		if (phoneMasksJson && typeof phoneMasksJson === 'object') {
			purchasePhoneMasks = phoneMasksJson;
		}
	} catch (e) {
		console.warn('Failed to parse phone masks:', e);
	}
}

if (typeof purchaseAllowedCountries === 'undefined') {
	var purchaseAllowedCountries = [];
	try {
		const allowedCountriesJson = {{ allowed_countries|raw }};
		if (allowedCountriesJson && Array.isArray(allowedCountriesJson)) {
			purchaseAllowedCountries = allowedCountriesJson;
		}
	} catch (e) {
		console.warn('Failed to parse allowed countries:', e);
	}
}

if (typeof defaultPurchaseCountry === 'undefined') {
	var defaultPurchaseCountry = '{{ default_phone_country|default("ua") }}';
}

if (typeof initPurchaseIntlTelInput === 'undefined') {
	function initPurchaseIntlTelInput() {
		const telInput = document.querySelector('#inputPurchasePhone');
		if (telInput && !telInput.classList.contains('iti__tel-input')) {
			if (purchaseIti) {
				purchaseIti.destroy();
			}

			const itiOptions = {
				initialCountry: defaultPurchaseCountry,
				geoIpLookup: function(callback) {
					callback(defaultPurchaseCountry);
				},
				separateDialCode: true,
				nationalMode: true,
				formatOnDisplay: false,
				strictMode: false,
				allowDropdown: true,
				useFullscreenPopup: false,
				containerClass: "input-group"
			};

			if (purchaseAllowedCountries.length > 0) {
				itiOptions.onlyCountries = purchaseAllowedCountries;
				
				if (purchaseAllowedCountries.length === 1) {
					itiOptions.allowDropdown = false;
				}
			}

			purchaseIti = window.intlTelInput(telInput, itiOptions);

			const applyPurchaseInputMask = function() {
				if (typeof $.fn.inputmask === 'undefined') {
					console.warn('Inputmask not loaded yet');
					return;
				}
				
				const countryData = purchaseIti.getSelectedCountryData();
				let maskData = purchasePhoneMasks[countryData.iso2];
				let mask = null;
				
				if (maskData && typeof maskData === 'object' && maskData.mask) {
					mask = maskData.mask;
				} else if (typeof maskData === 'string') {
					mask = maskData;
				}
				
				if (!mask) {
					const defaultMasks = {
						'ua': '99 999 99 99',
						'pl': '999 999 999',
						'us': '(999) 999-9999',
						'ca': '(999) 999-9999',
						'gb': '99999 999999',
						'de': '9999 99999999',
						'fr': '9 99 99 99 99',
						'it': '999 999 9999',
						'es': '999 99 99 99',
						'ru': '(999) 999-99-99',
						'by': '(99) 999-99-99',
					};
					mask = defaultMasks[countryData.iso2];
				}
				
				if (!mask) {
					const dialCodeLength = countryData.dialCode.length;
					if (dialCodeLength === 1) {
						mask = '(999) 999-9999';
					} else if (dialCodeLength === 2) {
						mask = '99 999 99 99';
					} else {
						mask = '999 999 9999';
					}
				}
				
				if ($(telInput).inputmask) {
					$(telInput).inputmask('remove');
				}
				
				$(telInput).inputmask({
					mask: mask,
					clearMaskOnLostFocus: false,
					showMaskOnHover: false,
					placeholder: '_',
					onincomplete: function() {
						updatePurchaseHiddenPhoneField();
					},
					oncomplete: function() {
						updatePurchaseHiddenPhoneField();
					},
					oncleared: function() {
						updatePurchaseHiddenPhoneField();
					}
				});
				
				const placeholderText = mask.replace(/9/g, '_');
				telInput.setAttribute('placeholder', placeholderText);
			};
			
			setTimeout(function() {
				applyPurchaseInputMask();
			}, 300);

			telInput.addEventListener('input', function(e) {
				updatePurchaseHiddenPhoneField();
			});

			telInput.addEventListener('paste', function(e) {
				setTimeout(function() {
					updatePurchaseHiddenPhoneField();
				}, 10);
			});

			telInput.addEventListener('countrychange', function() {
				applyPurchaseInputMask();
				updatePurchaseHiddenPhoneField();
			});

			telInput.addEventListener('blur', function() {
				updatePurchaseHiddenPhoneField();
			});
		}
	}
}

function getPurchaseFullPhoneNumber() {
	if (!purchaseIti) return '';
	
	const telInput = document.querySelector('#inputPurchasePhone');
	if (!telInput) return '';
	
	const selectedCountryData = purchaseIti.getSelectedCountryData();
	const dialCode = selectedCountryData.dialCode || '';
	let rawValue = telInput.value.replace(/\D/g, '');
	
	if (rawValue.length > 15) {
		rawValue = rawValue.substring(0, 15);
	}
	
	return rawValue ? '+' + dialCode + rawValue : '';
}

function updatePurchaseHiddenPhoneField() {
	const fullNumber = getPurchaseFullPhoneNumber();
	const hiddenField = document.querySelector('#full_telephone');
	if (hiddenField) {
		hiddenField.value = fullNumber;
	}
}

$('#quickOrderModal').off('shown.bs.modal').on('shown.bs.modal', function () {
	setTimeout(initPurchaseIntlTelInput, 300);
});

$("#inputPurchasePhone").off("change paste keyup").on("change paste keyup", function() {
	$(this).removeClass('error_style');
});
</script>

<script>
if (typeof purchaseUrls === 'undefined') {
	var purchaseUrls = {
		updatePrices: '{{ ajax_update_prices_url|raw }}',
		verifySms: '{{ ajax_verify_sms_url|raw }}',
		resendSms: '{{ ajax_resend_sms_url|raw }}',
		makeOrder: '{{ ajax_make_order_url|raw }}',
		upload: '{{ ajax_upload_url|raw }}'
	};
}

$(document).ready(function() {
    $('body').children('#smsVerificationModalPopup').remove();
	$('#smsVerificationModalPopup').appendTo('body');
});

function updatePurchaseValue(minus, plus, manual) {
	let min = parseInt($('#popup-purchase-input-quantity').val());
	let currentMinimum = parseInt($('#popup-purchase-min-quantity').val());
	let max = parseInt($('#popup-purchase-max-quantity').val());
	let use_minimum_step = {{ use_minimum_step ?? 0 }};
	let step = use_minimum_step ? currentMinimum : 1;

	if (isNaN(min)) {
		$('#popup-purchase-input-quantity').val(currentMinimum);
		if (typeof updatePurchasePrice === 'function') {
			updatePurchasePrice();
		}
		return;
	}

	if (max === 0)
		return;

	if (minus && min > currentMinimum) {
		if (min - step < currentMinimum) {
			$('#popup-purchase-input-quantity').val(currentMinimum);
			if (typeof updatePurchasePrice === 'function') {
				updatePurchasePrice();
			}
			return;
		} else if (min > max) {
			$('#popup-purchase-input-quantity').val(max);
			if (typeof updatePurchasePrice === 'function') {
				updatePurchasePrice();
			}
			return;
		}

		$('#popup-purchase-input-quantity').val(~~ $('#popup-purchase-input-quantity').val() - step);
	}

	if (plus) {
		if (max && min + step > max) {
			$('#popup-purchase-input-quantity').val(max);
			if (typeof updatePurchasePrice === 'function') {
				updatePurchasePrice();
			}
			return;
		} else if (min < currentMinimum) {
			$('#popup-purchase-input-quantity').val(currentMinimum);
			if (typeof updatePurchasePrice === 'function') {
				updatePurchasePrice();
			}
			return;
		}

		$('#popup-purchase-input-quantity').val(~~ $('#popup-purchase-input-quantity').val() + step);
	}

	if (manual) {
		if (min <= currentMinimum) {
			$('#popup-purchase-input-quantity').val(currentMinimum);
			if (typeof updatePurchasePrice === 'function') {
				updatePurchasePrice();
			}
			return;
		} else if (min > max) {
			$('#popup-purchase-input-quantity').val(max);
			if (typeof updatePurchasePrice === 'function') {
				updatePurchasePrice();
			}
			return;
		}

		if (use_minimum_step && currentMinimum > 1) {
			let remainder = min % currentMinimum;
			if (remainder !== 0) {
				let roundedValue = min - remainder + currentMinimum;
				if (max && roundedValue > max) {
					roundedValue = max;
				}
				$('#popup-purchase-input-quantity').val(roundedValue);
			}
		}
	}

	if (typeof updatePurchasePrice === 'function') {
		updatePurchasePrice();
	}
}

function updatePurchasePrice() {
	let priceOld = document.querySelector('#quickOrderModal .pr-price-old');
	let priceNew = document.querySelector('#quickOrderModal .pr-price-new');
	let youSaveOrder = document.querySelector('#popup-quickorder-product-you-save');

	$.ajax({
		type: 'post',
		url: purchaseUrls.updatePrices,
		data: $('#quickOrderModal input[type=\'text\'], #quickOrderModal input[type=\'hidden\'], #quickOrderModal input[type=\'radio\']:checked, #quickOrderModal input[type=\'checkbox\']:checked, #quickOrderModal select'),
		dataType: 'json',
		cache: false,
		success: function(json) {
			{% if special %}
			animatePrice(json['price'], priceOld);
			animatePrice(json['special'], priceNew);
			{% else %}
			animatePrice(json['price'], priceNew);
			{% endif %}

			{% if oct_sticker_you_save and you_save %}
			animatePrice(json['you_save_price'], youSaveOrder);
			{% endif %}

			{% if tax %}
			$('.pr-product-center-price-tax > span').html(json['tax']);
			{% endif %}
		}
	});
}

(function() {
	let smsTimerInterval;

	function startSmsTimer(seconds, isBlocking = false) {
		clearInterval(smsTimerInterval);
		let remaining = seconds;

		if (isBlocking) {
			$('#sms-timer-popup').hide();
			$('#btn-verify-sms-popup').prop('disabled', true);
			$('#btn-resend-sms-popup').prop('disabled', true);
			$('#sms-code-input-popup').prop('disabled', true).val('');
			$('#sms-error-popup').removeClass('d-none alert-danger').addClass('alert-warning');
		}

		smsTimerInterval = setInterval(function() {
			if (isBlocking) {
				$('#sms-error-popup').html('{{ error_sms_max_attempts|escape('js') }}'.replace('%s', '<strong>' + remaining + '</strong>'));
			} else {
				$('#timer-seconds-popup').text(remaining);
			}
			
			remaining--;

			if (remaining <= 0) {
				clearInterval(smsTimerInterval);
				smsTimerInterval = null;
				
				if (isBlocking) {
					$('#sms-error-popup').addClass('d-none');
				} else {
					$('#sms-timer-popup').hide();
					$('#sms-error-popup').addClass('d-none');
				}
				
				$('#btn-resend-sms-popup').prop('disabled', false);
				$('#btn-verify-sms-popup').prop('disabled', false);
				$('#sms-code-input-popup').prop('disabled', false).val('').focus();
			}
		}, 1000);
	}

	$('#smsVerificationModalPopup').on('shown.bs.modal', function () {
		$('#sms-code-input-popup').val('').prop('disabled', false);
		$('#btn-verify-sms-popup').prop('disabled', false);
		$('#sms-error-popup').addClass('d-none');
		
		setTimeout(function() {
			const input = document.getElementById('sms-code-input-popup');
			if (input) {
				input.focus();
				if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
					input.setSelectionRange(0, 0);
				}
			}
		}, 400);
		
		const timerValue = parseInt($('#timer-seconds-popup').text()) || 60;
		if (timerValue > 0 && !smsTimerInterval) {
			startSmsTimer(timerValue, false);
		}
	});

	$('#smsVerificationModalPopup').on('hidden.bs.modal', function () {
		clearInterval(smsTimerInterval);
		smsTimerInterval = null;
		
		if (!$('.pr-popup-success').is(':visible')) {
			$('#quickOrderModal').modal('show');
		}
	});

	$(document).on('click', '#btn-verify-sms-popup', function() {
		const code = $('#sms-code-input-popup').val().trim();
		
		if (code.length !== 4) {
			$('#sms-error-popup').removeClass('d-none alert-warning').addClass('alert-danger').text('{{ error_sms_code_length|escape('js') }}');
			return;
		}
		
		$.ajax({
			url: purchaseUrls.verifySms,
			type: 'post',
			data: {
				sms_code: code,
				popup_csrf_token: $('input[name="popup_csrf_token"]').val()
			},
			dataType: 'json',
			beforeSend: function() {
				$('#btn-verify-sms-popup').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
			},
			success: function(json) {
				$('#btn-verify-sms-popup').html('{{ button_verify|escape('js') }}');
				
				if (json.error) {
					if (json.attempts_exceeded && json.retry_after) {
						startSmsTimer(json.retry_after, true);
					} else {
						$('#btn-verify-sms-popup').prop('disabled', false);
						$('#sms-error-popup').removeClass('d-none alert-warning').addClass('alert-danger').text(json.error);
					}
					return;
				}
				
				if (json.success) {
					$('#btn-verify-sms-popup').prop('disabled', false);
					$('#smsVerificationModalPopup').modal('hide');
					
					$("#pr-popup-success-text").html(json.success);
					$("#one-click-main-block").html($(".pr-popup-success"));
					$(".pr-popup-success").removeClass("d-none");
					$('#quickOrderModal .modal-dialog').removeClass('wide');

					{% if oct_analytics_google_ecommerce is defined and oct_analytics_google_ecommerce is not empty %}
					if (typeof gtag != 'undefined' && json.ecommerce) {
						gtag('event', 'purchase', json.ecommerce);
					}
					{% endif %}
				}
			}
		});
	});

	$(document).on('click', '#btn-resend-sms-popup', function() {
		$.ajax({
			url: purchaseUrls.resendSms,
			type: 'post',
			data: {
				popup_csrf_token: $('input[name="popup_csrf_token"]').val()
			},
			dataType: 'json',
			beforeSend: function() {
				$('#btn-resend-sms-popup').prop('disabled', true);
			},
			success: function(json) {
				if (json.error) {
					$('#sms-error-popup').removeClass('d-none').addClass('alert-danger').text(json.error);
					$('#btn-resend-sms-popup').prop('disabled', false);
					return;
				}
				
				if (json.success) {
					$('#sms-error-popup').addClass('d-none');
					$('#sms-code-input-popup').val('').focus();
					prNotify('success', json.success);
					startSmsTimer(60, false);
				}
			}
		});
	});

	$(document).on('input', '#sms-code-input-popup', function() {
		this.value = this.value.replace(/[^0-9]/g, '');
		
		if (this.value.length === 4) {
			setTimeout(function() {
				$('#btn-verify-sms-popup').trigger('click');
			}, 300);
		}
	});

	$("#inputPurchaseName, #inputPurchasePhone, #inputPurchaseMail, #inputPurchaseComment, #agreePurchaseCheck").on("change paste keyup", function() {
		$(this).removeClass('error_style');
	});

	{% if error_stock_check is not defined %}
	$('#button_checkout').on('click', function() {
		updatePurchaseHiddenPhoneField();

		$.ajax({
			type: 'post',
			dataType: 'json',
			cache: false,
			url: purchaseUrls.makeOrder,
			data: $('#oct_purchase_form').serialize(),
			beforeSend: function() {
				masked('body', true);

				$('#button_checkout').data('original-content', $('#button_checkout').html());
				$('#button_checkout').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>').prop('disabled', true);
			},
			complete: function() {
				masked('body', false);
				
				setTimeout(function () {
					$('#button_checkout').html($('#button_checkout').data('original-content')).prop('disabled', false);
				}, 600);
			},
			success: function(json) {
				masked('body', false);

				if (json.sms_required || json.show_sms_modal) {
					const timerValue = json.timer || 60;
					
					$('#timer-seconds-popup').text(timerValue);
					$('#sms-timer-popup').show();
					$('#sms-code-input-popup').val('').prop('disabled', false);
					$('#btn-verify-sms-popup').prop('disabled', false);
					$('#btn-resend-sms-popup').prop('disabled', true);
					$('#sms-error-popup').addClass('d-none');
					
					startSmsTimer(timerValue, false);
					
					if (json.message) {
						prNotify('success', json.message);
					}
					
					$('#quickOrderModal').modal('hide');
					$('#smsVerificationModalPopup').modal('show');
					
					setTimeout(function() {
						const input = document.getElementById('sms-code-input-popup');
						if (input) {
							input.focus();
							if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
								input.setSelectionRange(0, 0);
							}
						}
					}, 400);
					
					return;
				}

				if (json.error) {
					$('#quickOrderModal .text-danger').remove();
					let errorOption = '';

					$.each(json.error.options, function(i, val) {
						if (val) {
							var element = $('#oct_purchase_form #input-option' + i.replace('_', '-'));

							if (element.parent().hasClass('input-group')) {
								element.parent().after('<div class="text-danger fsz-14 fw-500 mb-4">' + val + '</div>');
							} else {
								element.parent().after('<div class="text-danger mb-3 fsz-14 fw-500 mb-4">' + val + '</div>');
							}

							errorOption += '<div class="alert-text-item">' + val + '</div>';
						}
					});

					delete json.error.options;

					$.each(json.error, function(i, val) {
						if (val) {
							if (i === 'telephone') {
								const telInput = document.querySelector('#inputPurchasePhone');
								if (telInput) telInput.classList.add('error_style');
							} else {
								$('#quickOrderModal [name="' + i + '"]').addClass('error_style');
							}
							errorOption += '<div class="alert-text-item">' + val + '</div>';
						}
					});

					prNotify('danger', errorOption);
				} else {
					if (json.success) {
						{% if oct_analytics_google_ecommerce is defined and oct_analytics_google_ecommerce is not empty %}
						if (typeof gtag != 'undefined' && json.ecommerce) {
							gtag('event', 'purchase', json.ecommerce);
						}
						{% endif %}

						$("#pr-popup-success-text").html(json.success);
						$("#one-click-main-block").html($(".pr-popup-success"));
						$(".pr-popup-success").removeClass("d-none");
						$('#quickOrderModal .modal-dialog').removeClass('wide');
					}
				}
			}
		});
	});
	{% endif %}

	$('#popup-purchase-input-quantity').on('input', function(e) {
		updatePurchaseValue(false, false, false);
	});

	$('#popup-purchase-input-quantity').on('blur change', function(e) {
		updatePurchaseValue(false, false, true);
	});

	$("#pr-purchase-options-box input:not(.form-control), #pr-purchase-options-box select").on('change', function() {
		updatePurchasePrice();
	});

	$('button[id^=\'popup-button-upload\']').on('click', function() {
		var node = this;

		$('#form-upload').remove();

		$('body').prepend('<form enctype="multipart/form-data" id="form-upload" style="display: none;"><input type="file" name="file" /></form>');

		$('#form-upload input[name=\'file\']').trigger('click');

		if (typeof timer != 'undefined') {
			clearInterval(timer);
		}

		timer = setInterval(function() {
			if ($('#form-upload input[name=\'file\']').val() != '') {
				clearInterval(timer);

				$.ajax({
					url: purchaseUrls.upload,
					type: 'post',
					dataType: 'json',
					data: new FormData($('#form-upload')[0]),
					cache: false,
					contentType: false,
					processData: false,
					beforeSend: function() {
						$(node).button('loading');
					},
					complete: function() {
						$(node).button('reset');
					},
					success: function(json) {
						$('.text-danger').remove();

						if (json['error']) {
							$(node).parent().find('input').after('<div class="text-danger fsz-14 fw-500 mb-4">' + json['error'] + '</div>');
						}

						if (json['success']) {
							alert(json['success']);

							$(node).parent().find('input').val(json['code']);
						}
					},
					error: function(xhr, ajaxOptions, thrownError) {
						alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
					}
				});
			}
		}, 500);
	});
})();
</script>