

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/intl-tel-input@23.6.0/build/css/intlTelInput.css">
<style>
    .iti { width: 100%; }
    .iti__country-container { z-index: 30; }
    .iti__selected-country-primary { padding: 0.9rem 0.75rem; }
</style>

<div
    id="apply-modal"
    class="hidden fixed inset-0 z-[999] flex items-center justify-center p-4"
    role="dialog"
    aria-modal="true"
    aria-labelledby="modal-title"
>
    
    <div id="modal-backdrop"
         class="absolute inset-0 bg-black/60 backdrop-blur-sm"
         onclick="ApplyModal.close()">
    </div>

    
    <div class="relative bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden"
         id="modal-panel">

        
        <button onclick="ApplyModal.close()"
                class="absolute top-4 right-4 z-10 w-8 h-8 flex items-center justify-center rounded-full text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition">
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>
        </button>

        
        <div class="h-1.5 bg-gray-100" id="modal-progress-track">
            <div id="modal-progress-bar"
                 class="h-full bg-blue-500 rounded-full transition-all duration-500 ease-out"
                 style="width: 20%">
            </div>
        </div>

        
        <div class="px-8 pt-6 pb-0">
            <div class="flex items-center justify-between mb-1">
                <span id="modal-step-label" class="text-xs font-semibold text-blue-500 uppercase tracking-wider">
                    Step 1 of 4
                </span>
                
                <div class="flex gap-1.5">
                    <?php $__currentLoopData = range(1, 4); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $s): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <div id="dot-<?php echo e($s); ?>"
                         class="w-2 h-2 rounded-full transition-all duration-300 <?php echo e($s === 1 ? 'bg-blue-500 w-4' : 'bg-gray-200'); ?>">
                    </div>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </div>
            </div>
            <h2 id="modal-title" class="text-xl font-bold text-gray-800 mt-2 mb-1">
                Enter Your Phone Number
            </h2>
            <p id="modal-subtitle" class="text-sm text-gray-500 mb-5">
                We'll send you a verification code to confirm your application.
            </p>
        </div>

        
        <div id="modal-error"
             class="hidden mx-8 mb-4 px-4 py-2.5 bg-red-50 border border-red-200 text-red-700 text-sm rounded-lg flex items-start gap-2">
            <svg class="w-4 h-4 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <span id="modal-error-text"></span>
        </div>

        
        
        
        <div id="step-1" class="px-8 pb-8 modal-step">
            <input
                type="tel"
                id="field-phone"
                placeholder="Enter your phone number"
                inputmode="tel"
                class="w-full px-4 py-3.5 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:border-blue-500 transition"
            />
            <p class="text-xs text-gray-400 mt-2 ml-1">All countries supported, Bangladesh selected by default</p>

            <button onclick="ApplyModal.next()"
                    class="w-full mt-5 bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition text-base">
                Continue
                <svg class="w-4 h-4 inline ml-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                </svg>
            </button>
        </div>

        
        
        
        <div id="step-2" class="hidden px-8 pb-8 modal-step">
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1.5">Full Name</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 flex items-center pl-4 pointer-events-none">
                            <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                            </svg>
                        </div>
                        <input
                            type="text"
                            id="field-name"
                            placeholder="Your full name"
                            class="w-full pl-12 pr-4 py-3.5 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:border-blue-500 transition"
                        />
                    </div>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1.5">Email Address</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 flex items-center pl-4 pointer-events-none">
                            <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                      d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                            </svg>
                        </div>
                        <input
                            type="email"
                            id="field-email"
                            placeholder="you@example.com"
                            class="w-full pl-12 pr-4 py-3.5 border-2 border-gray-200 rounded-xl text-base focus:outline-none focus:border-blue-500 transition"
                        />
                    </div>
                </div>
            </div>

            <div class="flex gap-3 mt-6">
                <button onclick="ApplyModal.prev()"
                        class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold py-3.5 rounded-xl transition">
                    ← Back
                </button>
                <button onclick="ApplyModal.next()"
                        class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition">
                    Continue →
                </button>
            </div>
        </div>

        
        
        
        <div id="step-3" class="hidden px-8 pb-8 modal-step">
            <label class="block text-sm font-medium text-gray-700 mb-2">Preferred Study Destination</label>

            
            <div id="country-grid"
                 class="grid grid-cols-2 gap-2.5 max-h-60 overflow-y-auto pr-1 rounded-xl">
                
                <div class="col-span-2 flex items-center justify-center py-6 text-gray-400 text-sm gap-2" id="country-loading">
                    <svg class="w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                    </svg>
                    Loading destinations…
                </div>
            </div>

            
            <button
                id="skip-country-btn"
                onclick="ApplyModal.skipCountry()"
                class="w-full mt-3 text-sm text-gray-400 hover:text-gray-600 underline underline-offset-2 transition">
                Not decided yet — skip this step
            </button>

            <?php echo $__env->make('partials.captcha-widget', [
                'form' => 'lead_otp',
                'id' => 'lead-otp-captcha',
                'manual' => true,
                'wrapperClass' => 'mt-4 flex justify-center'
            ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

            <div class="flex gap-3 mt-5">
                <button onclick="ApplyModal.prev()"
                        class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold py-3.5 rounded-xl transition">
                    ← Back
                </button>
                <button onclick="ApplyModal.next()"
                        id="country-next-btn"
                        class="flex-1 bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition">
                    Continue →
                </button>
            </div>
        </div>

        
        
        
        <div id="step-4" class="hidden px-8 pb-8 modal-step">
            <div class="bg-blue-50 border border-blue-100 rounded-xl px-4 py-3 mb-5 flex items-start gap-3">
                <svg class="w-5 h-5 text-blue-500 mt-0.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                </svg>
                <p class="text-sm text-blue-700">
                    We sent a verification code to
                    <strong id="otp-phone-display" class="font-semibold"></strong>.
                    <br/>
                    <span class="text-blue-500 text-xs">Code expires in 5 minutes.</span>
                </p>
            </div>

            
            <div class="flex gap-3 justify-center mb-2" id="otp-inputs">
                <?php $__currentLoopData = range(1, 4); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $i): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <input
                    type="text"
                    maxlength="1"
                    inputmode="numeric"
                    pattern="[0-9]*"
                    class="otp-box w-14 h-14 text-center text-2xl font-bold border-2 border-gray-200 rounded-xl
                           focus:outline-none focus:border-blue-500 transition caret-transparent"
                    data-index="<?php echo e($i - 1); ?>"
                />
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </div>

            <p class="text-center text-xs text-gray-400 mb-5">Enter the 4-digit code</p>

            
            <button onclick="ApplyModal.submitLead()"
                    id="verify-btn"
                    class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition flex items-center justify-center gap-2">
                <span id="verify-btn-text">Verify & Submit Application</span>
                <svg id="verify-spinner" class="hidden w-5 h-5 animate-spin" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
                </svg>
            </button>

            <div class="text-center mt-3">
                <button onclick="ApplyModal.resendOtp()"
                        class="text-sm text-blue-500 hover:text-blue-700 transition mb-2">
                    Resend OTP
                </button>
                <br/>
                <button onclick="ApplyModal.prev()"
                        class="text-sm text-gray-400 hover:text-gray-600 underline underline-offset-2 transition">
                    ← Back
                </button>
            </div>
        </div>

        
        
        
        <div id="step-5" class="hidden px-8 pb-10 modal-step text-center">
            
            <div class="flex items-center justify-center w-20 h-20 bg-green-100 rounded-full mx-auto mb-5 mt-2">
                <svg class="w-10 h-10 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7"/>
                </svg>
            </div>

            <h3 class="text-2xl font-bold text-gray-800 mb-2">Application Submitted!</h3>
            <p class="text-gray-500 text-sm mb-6 leading-relaxed">
                Thank you, <strong id="success-name" class="text-gray-700"></strong>!<br/>
                Our team will contact you within <strong>24 hours</strong> to discuss your options.
            </p>

            
            <div class="bg-gray-50 rounded-xl p-4 text-left text-sm space-y-2 mb-6">
                <div class="flex justify-between">
                    <span class="text-gray-500">Phone</span>
                    <span class="font-medium text-gray-800" id="success-phone"></span>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500">Email</span>
                    <span class="font-medium text-gray-800" id="success-email"></span>
                </div>
                <div class="flex justify-between" id="success-country-row">
                    <span class="text-gray-500">Destination</span>
                    <span class="font-medium text-gray-800" id="success-country"></span>
                </div>
            </div>

            
            <?php
                $waNumber = preg_replace('/\\D+/', '', $siteSettings['whatsapp_number'] ?? '');
                $waLink = $waNumber ? ('https://wa.me/' . $waNumber) : 'https://wa.me/+8801XXXXXXXXX';
            ?>
            <a href="<?php echo e($waLink); ?>" target="_blank"
               class="w-full flex items-center justify-center gap-2 bg-green-500 hover:bg-green-600 text-white font-semibold py-3.5 rounded-xl transition mb-3">
                <svg class="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
                    <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/>
                    <path d="M12 0C5.373 0 0 5.373 0 12c0 2.124.556 4.124 1.528 5.862L0 24l6.29-1.506A11.954 11.954 0 0012 24c6.627 0 12-5.373 12-12S18.627 0 12 0zm0 21.882a9.875 9.875 0 01-5.031-1.378l-.36-.214-3.733.894.928-3.638-.235-.374A9.867 9.867 0 012.12 12c0-5.45 4.43-9.882 9.88-9.882 5.449 0 9.879 4.432 9.879 9.882 0 5.449-4.43 9.882-9.879 9.882z"/>
                </svg>
                Chat with a Counselor
            </a>

            <button onclick="ApplyModal.close()"
                    class="w-full text-sm text-gray-400 hover:text-gray-600 transition">
                Close
            </button>
        </div>

    </div>
</div>





<script>
const ApplyModal = (() => {
    let phoneIti = null;
    let phoneLibLoaded = false;

    // ── State ─────────────────────────────────────────────────────
    let state = {
        currentStep : 1,
        totalSteps  : 4,
        phone       : '',
        name        : '',
        email       : '',
        country_id  : null,
        country_name: '',
        otp         : '',
        presetCountry: null,   // set when opened from a country page
    };

    let countriesLoaded = false;

    function loadIntlTelLibrary() {
        if (window.intlTelInput) {
            phoneLibLoaded = true;
            return Promise.resolve();
        }

        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/intl-tel-input@23.6.0/build/js/intlTelInput.min.js';
            script.async = true;
            script.onload = () => {
                phoneLibLoaded = true;
                resolve();
            };
            script.onerror = () => reject(new Error('Phone library failed to load.'));
            document.body.appendChild(script);
        });
    }

    async function initPhoneInput() {
        const input = document.getElementById('field-phone');
        if (! input) return;

        if (! phoneLibLoaded) {
            try {
                await loadIntlTelLibrary();
            } catch (e) {
                return;
            }
        }

        if (phoneIti) return;

        phoneIti = window.intlTelInput(input, {
            initialCountry: 'bd',
            preferredCountries: ['bd', 'in', 'pk', 'my', 'sg', 'ae', 'gb', 'us', 'ca', 'au'],
            separateDialCode: true,
            formatOnDisplay: true,
            nationalMode: true,
            autoPlaceholder: 'aggressive',
            utilsScript: 'https://cdn.jsdelivr.net/npm/intl-tel-input@23.6.0/build/js/utils.js',
        });
    }

    // ── Step config ───────────────────────────────────────────────
    const steps = {
        1: { label: 'Your contact number',         subtitle: 'We\'ll send you a verification code to confirm.' },
        2: { label: 'Tell us about yourself',      subtitle: 'Help us personalise your consultation.' },
        3: { label: 'Where do you want to study?', subtitle: 'Select your preferred destination.' },
        4: { label: 'Verify your number',          subtitle: 'Enter the 4-digit code we sent you.' },
    };

    // ── Open / Close ──────────────────────────────────────────────
    async function open(arg1 = null, arg2 = null, arg3 = null) {
        // Allow legacy signature (id, name) or options object
        const options = (typeof arg1 === 'object' && arg1 !== null)
            ? arg1
            : {
                countryId: arg1,
                countryName: arg2,
                ...(arg3 || {}),
            };

        const {
            countryId,
            countryName,
            name,
            email,
            phone,
            startAtStep = 1,
        } = options;

        state = {
            currentStep  : 1,
            totalSteps   : 4,
            phone        : phone || '',
            name         : name  || '',
            email        : email || '',
            country_id   : countryId   || null,
            country_name : countryName || '',
            otp          : '',
            presetCountry: countryId ? { id: countryId, name: countryName } : null,
        };

        // Reset all fields
        clearAllFields();
        hideError();
        gotoStep(1);

        const modal = document.getElementById('apply-modal');
        modal.classList.remove('hidden');
        document.body.style.overflow = 'hidden';

        await initPhoneInput();
        if (phoneIti) phoneIti.setCountry('bd');

        // Focus first input
        setTimeout(() => document.getElementById('field-phone')?.focus(), 100);

        // Load countries for step 3
        if (! countriesLoaded) loadCountries();

        // Prefill fields if provided
        if (state.phone) {
            const phoneInput = document.getElementById('field-phone');
            if (phoneInput) {
                phoneInput.value = state.phone;
                if (phoneIti) phoneIti.setNumber(state.phone);
            }
        }
        if (state.name) {
            const nameInput = document.getElementById('field-name');
            if (nameInput) nameInput.value = state.name;
        }
        if (state.email) {
            const emailInput = document.getElementById('field-email');
            if (emailInput) emailInput.value = state.email;
        }

        // Optional: jump straight to a later step (e.g., when data came from a sidebar form)
        if (Number(startAtStep) > 1) {
            gotoStep(Math.min(4, Number(startAtStep)));
        }
    }

    function close() {
        document.getElementById('apply-modal').classList.add('hidden');
        document.body.style.overflow = '';
    }

    // ── Navigation ────────────────────────────────────────────────
    function gotoStep(n) {
        for (let i = 1; i <= 5; i++) {
            const el = document.getElementById(`step-${i}`);
            if (el) el.classList.add('hidden');
        }
        const target = document.getElementById(`step-${n}`);
        if (target) target.classList.remove('hidden');

        state.currentStep = n;
        updateHeader(n);
        updateProgress(n);
        hideError();

        if (n === 3) {
            window.GpsCaptcha?.render('lead-otp-captcha');
        }
    }

    function updateHeader(n) {
        const isSuccess = n === 5;

        // Hide header on success
        document.getElementById('modal-step-label').parentElement.style.display = isSuccess ? 'none' : '';

        if (! isSuccess && steps[n]) {
            document.getElementById('modal-step-label').textContent = `Step ${n} of ${state.totalSteps}`;
            document.getElementById('modal-title').textContent      = steps[n].label;
            document.getElementById('modal-subtitle').textContent   = steps[n].subtitle;
        }

        // Dots
        for (let i = 1; i <= state.totalSteps; i++) {
            const dot = document.getElementById(`dot-${i}`);
            if (! dot) continue;
            dot.className = 'w-2 h-2 rounded-full transition-all duration-300 ';
            if (i < n)       dot.className += 'bg-blue-300';
            else if (i === n) dot.className += 'bg-blue-500 w-4';
            else              dot.className += 'bg-gray-200';
        }
    }

    function updateProgress(n) {
        const isSuccess = n === 5;
        const pct = isSuccess ? 100 : Math.round((n / state.totalSteps) * 100);
        document.getElementById('modal-progress-bar').style.width = pct + '%';
        if (isSuccess) {
            document.getElementById('modal-progress-bar').classList.replace('bg-blue-500', 'bg-green-500');
        } else {
            document.getElementById('modal-progress-bar').classList.replace('bg-green-500', 'bg-blue-500');
        }
    }

    // ── Validation ────────────────────────────────────────────────
    function showError(msg) {
        const box = document.getElementById('modal-error');
        document.getElementById('modal-error-text').textContent = msg;
        box.classList.remove('hidden');
    }

    function hideError() {
        document.getElementById('modal-error').classList.add('hidden');
    }

    function normalizeFallbackInternational(rawPhone) {
        const raw = (rawPhone || '').trim();
        if (! raw) return null;

        let compact = raw.replace(/[^\d+]/g, '');
        if (compact.startsWith('00')) compact = '+' + compact.slice(2);

        if (/^\+\d{8,15}$/.test(compact)) return compact;
        if (/^8801\d{9}$/.test(compact)) return '+' + compact;
        if (/^01\d{9}$/.test(compact)) return '+88' + compact;
        if (/^1\d{9}$/.test(compact)) return '+880' + compact;

        return null;
    }

    function normalizeDialAwarePhone(rawPhone, countryData = null, itiNumber = '') {
        const iso2 = (countryData?.iso2 || '').toLowerCase();
        const sanitizedItiNumber = (itiNumber || '').replace(/[^\d+]/g, '');

        if (iso2 === 'bd') {
            if (/^\+88001\d{9}$/.test(sanitizedItiNumber)) {
                return '+880' + sanitizedItiNumber.slice(6);
            }
            if (/^\+8801\d{9}$/.test(sanitizedItiNumber)) {
                return sanitizedItiNumber;
            }

            const rawDigits = (rawPhone || '').replace(/\D/g, '');
            if (/^01\d{9}$/.test(rawDigits)) {
                return '+88' + rawDigits;
            }
            if (/^1\d{9}$/.test(rawDigits)) {
                return '+880' + rawDigits;
            }
            if (/^8801\d{9}$/.test(rawDigits)) {
                return '+' + rawDigits;
            }
            if (/^88001\d{9}$/.test(rawDigits)) {
                return '+880' + rawDigits.slice(5);
            }
        }

        return normalizeFallbackInternational(sanitizedItiNumber || rawPhone);
    }

    function getNormalizedPhoneValue(rawPhone) {
        if (! phoneIti) {
            return normalizeFallbackInternational(rawPhone);
        }

        const countryData = typeof phoneIti.getSelectedCountryData === 'function'
            ? phoneIti.getSelectedCountryData()
            : null;
        const itiNumber = typeof phoneIti.getNumber === 'function'
            ? phoneIti.getNumber()
            : '';

        const normalized = normalizeDialAwarePhone(rawPhone, countryData, itiNumber);
        if (normalized) {
            return normalized;
        }

        return normalizeFallbackInternational(rawPhone);
    }

    function validateStep(n) {
        if (n === 1) {
            const phoneInput = document.getElementById('field-phone').value.trim();
            const normalizedPhone = getNormalizedPhoneValue(phoneInput);

            if (! normalizedPhone) {
                showError(phoneIti
                    ? 'Please enter a valid phone number.'
                    : 'Please enter a valid phone number with country code.');
                return false;
            }

            state.phone = normalizedPhone;
        }

        if (n === 2) {
            const name  = document.getElementById('field-name').value.trim();
            const email = document.getElementById('field-email').value.trim();
            if (! name)  { showError('Please enter your full name.'); return false; }
            if (! email || ! /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
                showError('Please enter a valid email address.');
                return false;
            }
            state.name  = name;
            state.email = email;
        }

        if (n === 3) {
            // Country is optional — user may have clicked "skip"
            // Nothing to block here
        }

        return true;
    }

    // ── Next / Prev ───────────────────────────────────────────────
    async function next() {
        if (! validateStep(state.currentStep)) return;

        const nextStep = state.currentStep + 1;

        if (nextStep === 4) {
            const sent = await requestLeadOtp();
            if (! sent) return;

            // Show phone in OTP step
            document.getElementById('otp-phone-display').textContent = state.phone;
            // Clear OTP boxes
            document.querySelectorAll('.otp-box').forEach(b => b.value = '');
        }

        gotoStep(nextStep);

        if (nextStep === 4) {
            setTimeout(() => document.querySelector('.otp-box')?.focus(), 100);
        }
    }

    async function requestLeadOtp() {
        hideError();

        const leadCaptchaContainer = document.getElementById('lead-otp-captcha');
        const captchaToken = window.GpsCaptcha?.getToken(leadCaptchaContainer) || '';

        if (leadCaptchaContainer && ! captchaToken) {
            showError('Please complete the verification challenge first.');
            return false;
        }

        try {
            const res = await fetch('<?php echo e(route("leads.otp.send")); ?>', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    'Accept': 'application/json',
                },
                body: JSON.stringify({
                    phone: state.phone,
                    captcha_token: captchaToken,
                }),
            });
            const data = await res.json();

            if (! res.ok || ! data.success) {
                if (leadCaptchaContainer) {
                    window.GpsCaptcha?.reset(leadCaptchaContainer);
                }
                showError(data.message || 'Could not send OTP. Please try again.');
                return false;
            }

            if (leadCaptchaContainer) {
                window.GpsCaptcha?.reset(leadCaptchaContainer);
            }
            return true;
        } catch (e) {
            if (leadCaptchaContainer) {
                window.GpsCaptcha?.reset(leadCaptchaContainer);
            }
            showError('Network error while sending OTP. Please try again.');
            return false;
        }
    }

    async function resendOtp() {
        const sent = await requestLeadOtp();
        if (sent) {
            hideError();
        }
    }

    function prev() {
        if (state.currentStep > 1) {
            gotoStep(state.currentStep - 1);
        }
    }

    function skipCountry() {
        state.country_id   = null;
        state.country_name = 'Not decided';
        next();
    }

    // ── Countries loader ──────────────────────────────────────────
    function loadCountries() {
        fetch('<?php echo e(route("leads.countries")); ?>')
            .then(r => r.json())
            .then(countries => {
                countriesLoaded = true;
                renderCountries(countries);
            })
            .catch(() => {
                document.getElementById('country-loading').innerHTML =
                    '<span class="text-red-400">Could not load destinations. You can skip this step.</span>';
            });
    }

    function renderCountries(countries) {
        const grid = document.getElementById('country-grid');
        document.getElementById('country-loading')?.remove();

        if (countries.length === 0) {
            grid.innerHTML = '<p class="col-span-2 text-center text-gray-400 text-sm py-4">No destinations available yet.</p>';
            return;
        }

        countries.forEach(c => {
            const btn = document.createElement('button');
            btn.type        = 'button';
            btn.dataset.id  = c.id;
            btn.dataset.name = c.name;
            btn.className   = [
                'country-card flex items-center gap-2.5 p-3 rounded-xl border-2 text-left transition',
                'border-gray-200 hover:border-blue-400 hover:bg-blue-50',
            ].join(' ');

            btn.innerHTML = `
                ${ c.flag_url
                    ? `<img src="${c.flag_url}" class="w-8 h-6 object-cover rounded border border-gray-200 flex-shrink-0" alt="${c.name}" />`
                    : `<span class="text-lg">🌍</span>`
                }
                <span class="text-sm font-medium text-gray-700 leading-tight">${c.name}</span>
            `;

            btn.addEventListener('click', () => selectCountry(c.id, c.name, btn));

            // Auto-select if preset (opened from country page)
            if (state.presetCountry && state.presetCountry.id === c.id) {
                selectCountry(c.id, c.name, btn);
            }

            grid.appendChild(btn);
        });
    }

    function selectCountry(id, name, btn) {
        document.querySelectorAll('.country-card').forEach(b => {
            b.classList.remove('border-blue-500', 'bg-blue-50', 'ring-2', 'ring-blue-300');
        });
        btn.classList.add('border-blue-500', 'bg-blue-50', 'ring-2', 'ring-blue-300');
        state.country_id   = id;
        state.country_name = name;
    }

    // ── OTP box UX (auto-advance, backspace) ──────────────────────
    function initOtpBoxes() {
        const boxes = document.querySelectorAll('.otp-box');
        boxes.forEach((box, idx) => {
            box.addEventListener('keydown', e => {
                if (e.key === 'Backspace' && ! box.value && idx > 0) {
                    boxes[idx - 1].focus();
                }
            });

            box.addEventListener('input', e => {
                const val = e.target.value.replace(/\D/g, '');
                box.value = val ? val[val.length - 1] : '';

                if (val && idx < boxes.length - 1) {
                    boxes[idx + 1].focus();
                }
                // Auto-submit if all 4 filled
                if ([...boxes].every(b => b.value)) {
                    document.getElementById('verify-btn').classList.add('ring-2', 'ring-blue-300');
                }
            });

            box.addEventListener('paste', e => {
                e.preventDefault();
                const pasted = (e.clipboardData || window.clipboardData).getData('text').replace(/\D/g, '');
                boxes.forEach((b, i) => { b.value = pasted[i] || ''; });
                if (pasted.length >= 4) boxes[3].focus();
            });
        });
    }

    function getOtpValue() {
        return [...document.querySelectorAll('.otp-box')].map(b => b.value).join('');
    }

    // ── Final submit ──────────────────────────────────────────────
    function submitLead() {
        const otp = getOtpValue();
        if (otp.length < 4) { showError('Please enter the 4-digit verification code.'); return; }

        state.otp = otp;

        // Loading state
        const btn        = document.getElementById('verify-btn');
        const btnText    = document.getElementById('verify-btn-text');
        const spinner    = document.getElementById('verify-spinner');
        btn.disabled     = true;
        btnText.textContent = 'Verifying…';
        spinner.classList.remove('hidden');
        hideError();

        fetch('<?php echo e(route("leads.store")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type'  : 'application/json',
                'X-CSRF-TOKEN'  : document.querySelector('meta[name="csrf-token"]').content,
                'Accept'        : 'application/json',
            },
            body: JSON.stringify({
                phone       : state.phone,
                name        : state.name,
                email       : state.email,
                country_id  : state.country_id,
                otp         : state.otp,
                source      : new URLSearchParams(window.location.search).get('source'),
                utm_medium  : new URLSearchParams(window.location.search).get('utm_medium'),
                utm_campaign: new URLSearchParams(window.location.search).get('utm_campaign'),
                page_url    : window.location.href,
            }),
        })
        .then(r => r.json())
        .then(data => {
            btn.disabled = false;
            btnText.textContent = 'Verify & Submit Application';
            spinner.classList.add('hidden');

            if (data.success) {
                showSuccess();
            } else {
                showError(data.message || 'Something went wrong. Please try again.');
            }
        })
        .catch(() => {
            btn.disabled = false;
            btnText.textContent = 'Verify & Submit Application';
            spinner.classList.add('hidden');
            showError('Network error. Please check your connection and try again.');
        });
    }

    function showSuccess() {
        document.getElementById('success-name').textContent    = state.name;
        document.getElementById('success-phone').textContent   = state.phone;
        document.getElementById('success-email').textContent   = state.email;

        const countryRow = document.getElementById('success-country-row');
        if (state.country_name && state.country_name !== 'Not decided') {
            document.getElementById('success-country').textContent = state.country_name;
            countryRow.classList.remove('hidden');
        } else {
            countryRow.classList.add('hidden');
        }

        // Hide header/dots on success
        document.getElementById('modal-step-label').closest('div.flex')?.classList.add('hidden');

        <?php if($marketingSettings['track_apply_lead'] ?? false): ?>
        window.gpsTrackMeta?.('Lead', {
            content_name: 'Apply Modal Lead',
            content_category: 'lead_form',
        });
        <?php endif; ?>

        gotoStep(5);
    }

    // ── Utility ───────────────────────────────────────────────────
    function clearAllFields() {
        ['field-name', 'field-email'].forEach(id => {
            const el = document.getElementById(id);
            if (el) el.value = '';
        });
        const phoneInput = document.getElementById('field-phone');
        if (phoneInput) {
            phoneInput.value = '';
        }
        if (phoneIti) {
            phoneIti.setCountry('bd');
        }
        document.querySelectorAll('.otp-box').forEach(b => b.value = '');
        document.querySelectorAll('.country-card').forEach(b => {
            b.classList.remove('border-blue-500', 'bg-blue-50', 'ring-2', 'ring-blue-300');
        });

        // Reset header visibility
        const stepLabelParent = document.getElementById('modal-step-label')?.closest('div.flex');
        if (stepLabelParent) stepLabelParent.classList.remove('hidden');

        document.getElementById('modal-progress-bar').classList.replace('bg-green-500', 'bg-blue-500');
    }

    // ── Keyboard: Escape closes --
    document.addEventListener('keydown', e => {
        if (e.key === 'Escape' && ! document.getElementById('apply-modal').classList.contains('hidden')) {
            close();
        }
        // Enter key advances step (except step 4)
        if (e.key === 'Enter' && [1, 2, 3].includes(state.currentStep)) {
            next();
        }
    });

    // Init OTP on DOMContentLoaded
    document.addEventListener('DOMContentLoaded', initOtpBoxes);
    document.addEventListener('DOMContentLoaded', () => { initPhoneInput(); });

    // Public API
    return { open, close, next, prev, skipCountry, submitLead, resendOtp };

})();
</script>
<?php /**PATH C:\xampp\htdocs\gps-migration\resources\views\partials\apply-modal.blade.php ENDPATH**/ ?>