/* DZQCOD v3 Frontend */
(function($){
'use strict';
$(function(){
    // ═══ GLOBAL FORM REFERENCES ═══
    var $w=$('.dzqcod-quick-order').first();
    var $f=$w.find('.dzqcod-form').first();
    var pid=$w.data('pid')||$f.find('input[name=product_id]').val()||0;

    // ═══ SUBMIT ORDER ═══
    $(document).on('submit','.dzqcod-form',function(e){
        e.preventDefault();var $form=$(this),$b=$form.find('.dzqcod-submit'),$m=$form.find('.dzqcod-msg');
        if(!validate($form))return;
        $b.prop('disabled',true);$b.find('.txt').hide();$b.find('.ld').show();$m.hide();
        var data=$form.serialize();
        data+='&time_on_page='+Math.round((Date.now()-window._dzqStart)/1000);
        data+='&scroll_depth='+Math.round(window._dzqScroll||0);
        $.post(dzqcod.ajax,data,function(r){
            if(r.success){
                if(r.data.redirect){window.location.href=r.data.redirect;return}
                document.cookie='dzqcod_ordered=1;path=/;max-age=86400';fire(r.data);
                // Hide the form and show post-order page
                $form.closest('.dzqcod-quick-order').fadeOut(300);
                if(r.data.otp_enabled)showOtpPage(r.data);else showThankYouPage(r.data);
            } else {
                $m.removeClass('success').addClass('error').text(r.data&&r.data.message?r.data.message:'خطأ').show();
                $b.prop('disabled',false);$b.find('.txt').show();$b.find('.ld').hide();
            }
        }).fail(function(){
            $m.removeClass('success').addClass('error').text('خطأ في الاتصال').show();
            $b.prop('disabled',false);$b.find('.txt').show();$b.find('.ld').hide();
        });
    });

    // ═══ POST-ORDER OVERLAY ═══
    function showPostOrderOverlay(html){
        var $ov=$('#dzqcod-post-order');
        if(!$ov.length){$ov=$('<div id="dzqcod-post-order" style="position:fixed;inset:0;z-index:999999;background:rgba(15,23,42,.85);display:flex;align-items:center;justify-content:center;padding:20px;backdrop-filter:blur(6px)"></div>');$('body').append($ov)}
        $ov.html('<div style="background:#fff;border-radius:20px;max-width:480px;width:100%;padding:32px;text-align:center;animation:dzqFadeIn .4s ease;box-shadow:0 20px 60px rgba(0,0,0,.3)">' + html + '</div>').show();
        if(!$('#dzq-post-css').length) $('head').append('<style id="dzq-post-css">@keyframes dzqFadeIn{from{opacity:0;transform:scale(.9) translateY(20px)}to{opacity:1;transform:none}}.dzq-po-btn{display:inline-block;padding:12px 28px;border-radius:12px;font-weight:800;font-size:15px;cursor:pointer;border:none;font-family:inherit;transition:.2s;margin:4px}.dzq-po-btn:hover{transform:translateY(-2px);box-shadow:0 6px 20px rgba(0,0,0,.15)}.dzq-po-primary{background:linear-gradient(135deg,#6366f1,#818cf8);color:#fff}.dzq-po-ghost{background:#f1f5f9;color:#475569}.dzq-po-success{background:linear-gradient(135deg,#22c55e,#4ade80);color:#fff}.dzq-po-slot{display:block;width:100%;padding:12px;margin:4px 0;border:2px solid #e2e8f0;border-radius:12px;background:#fff;cursor:pointer;font-size:14px;font-weight:600;font-family:inherit;transition:.2s;text-align:center}.dzq-po-slot:hover,.dzq-po-slot.active{border-color:#6366f1;background:#eef2ff;color:#6366f1}.dzq-otp-input{width:180px;padding:14px;font-size:28px;text-align:center;letter-spacing:12px;border:3px solid #e2e8f0;border-radius:14px;font-weight:900;font-family:inherit;outline:none;transition:.2s}.dzq-otp-input:focus{border-color:#6366f1;box-shadow:0 0 0 4px rgba(99,102,241,.15)}</style>');
    }
    function showOtpPage(data){
        var h='<div style="font-size:48px;margin-bottom:12px">📱</div><h2 style="font-size:22px;font-weight:900;margin-bottom:6px;color:#1e293b">تأكيد الطلب</h2>';
        h+='<p style="color:#64748b;font-size:14px;margin-bottom:20px">تم إرسال رمز التحقق إلى <strong dir="ltr">' + data.phone_masked + '</strong></p>';
        h+='<div style="margin-bottom:16px"><input type="text" id="dzq-otp-code" class="dzq-otp-input" maxlength="4" placeholder="----" autofocus></div>';
        h+='<div id="dzq-otp-msg" style="font-size:13px;min-height:20px;margin-bottom:12px"></div>';
        h+='<button id="dzq-otp-confirm" class="dzq-po-btn dzq-po-primary" data-oid="'+data.order_id+'">✅ تأكيد الطلب</button>';
        h+='<button id="dzq-otp-resend" class="dzq-po-btn dzq-po-ghost" data-phone="'+data.phone+'" disabled>📱 إعادة إرسال <span id="dzq-otp-timer">60</span></button>';
        h+='<div style="margin-top:16px;border-top:1px solid #f1f5f9;padding-top:12px"><button id="dzq-otp-skip" class="dzq-po-btn dzq-po-ghost" data-oid="'+data.order_id+'" data-name="'+data.name+'" data-phone="'+data.phone_masked+'" style="font-size:12px;color:#94a3b8">⏭️ تخطي</button></div>';
        showPostOrderOverlay(h);setTimeout(function(){$('#dzq-otp-code').focus()},400);
        var sec=60;var timer=setInterval(function(){sec--;$('#dzq-otp-timer').text(sec);if(sec<=0){clearInterval(timer);$('#dzq-otp-resend').prop('disabled',false).html('📱 إعادة إرسال')}},1000);
    }
    $(document).on('click','#dzq-otp-confirm',function(){var $b=$(this),oid=$b.data('oid'),code=$('#dzq-otp-code').val();if(!code||code.length<4){$('#dzq-otp-msg').text('أدخل الرمز المكوّن من 4 أرقام').css('color','#ef4444');return}$b.prop('disabled',true).text('⏳');$.post(dzqcod.ajax,{action:'dzqcod_verify_order_otp',order_id:oid,otp_code:code},function(r){if(r.success)showConfirmedPage(r.data);else{$b.prop('disabled',false).text('✅ تأكيد');$('#dzq-otp-msg').text(r.data?r.data.message:'رمز خاطئ').css('color','#ef4444')}})});
    $(document).on('keypress','#dzq-otp-code',function(e){if(e.which===13){e.preventDefault();$('#dzq-otp-confirm').click()}});
    $(document).on('click','#dzq-otp-resend:not(:disabled)',function(){var ph=$(this).data('phone');$(this).prop('disabled',true);$.post(dzqcod.ajax,{action:'dzqcod_send_otp',phone:ph},function(r){$('#dzq-otp-msg').text(r.data?r.data.message:'تم').css('color','#22c55e');var sec=60;$('#dzq-otp-timer').text(sec);var t=setInterval(function(){sec--;$('#dzq-otp-timer').text(sec);if(sec<=0){clearInterval(t);$('#dzq-otp-resend').prop('disabled',false).html('📱 إعادة إرسال')}},1000)})});
    $(document).on('click','#dzq-otp-skip',function(){showCallbackPage({order_id:$(this).data('oid'),name:$(this).data('name'),phone_masked:$(this).data('phone')})});

    function showCallbackPage(data){
        var h='<div style="font-size:48px;margin-bottom:12px">📞</div><h2 style="font-size:22px;font-weight:900;margin-bottom:6px">'+(dzqcod.po_callback_title||'📞 سنتصل بك لتأكيد الطلب')+'</h2>';
        h+='<p style="color:#64748b;font-size:14px;margin-bottom:16px">'+(dzqcod.po_callback_msg||'اختر الفترة المناسبة للاتصال بك')+'</p>';
        if(dzqcod.po_callback_phone) h+='<p style="color:#6366f1;font-size:13px;font-weight:700;margin-bottom:12px">📱 من: <span dir="ltr">'+dzqcod.po_callback_phone+'</span></p>';
        var slots=[{k:'morning',l:'☀️ صباحاً',t:'9-12'},{k:'afternoon',l:'🌤️ ظهراً',t:'12-15'},{k:'evening',l:'🌅 مساءً',t:'15-18'},{k:'night',l:'🌙 ليلاً',t:'18-21'},{k:'anytime',l:'⏰ أي وقت',t:''}];
        h+='<div style="margin-bottom:16px">';slots.forEach(function(s){h+='<button class="dzq-po-slot dzq-cb-slot" data-slot="'+s.k+'">'+s.l+(s.t?' <span style="font-size:12px;color:#94a3b8">'+s.t+'</span>':'')+'</button>'});h+='</div>';
        h+='<div id="dzq-cb-msg" style="font-size:13px;min-height:20px;margin-bottom:8px"></div>';
        h+='<button id="dzq-cb-confirm" class="dzq-po-btn dzq-po-primary" data-oid="'+data.order_id+'" disabled>📞 تأكيد الموعد</button>';
        showPostOrderOverlay(h);
    }
    $(document).on('click','.dzq-cb-slot',function(){$('.dzq-cb-slot').removeClass('active');$(this).addClass('active');$('#dzq-cb-confirm').prop('disabled',false).data('slot',$(this).data('slot'))});
    $(document).on('click','#dzq-cb-confirm',function(){var $b=$(this),oid=$b.data('oid'),slot=$b.data('slot');if(!slot)return;$b.prop('disabled',true).text('⏳');$.post(dzqcod.ajax,{action:'dzqcod_set_callback_pref',order_id:oid,time_slot:slot},function(r){if(r.success){showPostOrderOverlay('<div style="font-size:64px;margin-bottom:16px">📞</div><h2 style="font-size:24px;font-weight:900">شكراً لك!</h2><p style="font-size:16px;color:#22c55e;font-weight:700">'+r.data.message+'</p><button class="dzq-po-btn dzq-po-ghost dzq-po-close" style="margin-top:16px">🏠 العودة</button>')}})});
    function showConfirmedPage(data){showPostOrderOverlay('<div style="font-size:64px;margin-bottom:12px">🎉</div><h2 style="font-size:24px;font-weight:900;color:#22c55e">'+(dzqcod.po_confirmed_title||'🎉 تم تأكيد طلبك!')+'</h2><p style="font-size:15px;color:#64748b;margin-bottom:16px">'+(data.message||'سيتم شحن طلبك قريباً')+'</p><div style="background:#f0fdf4;border:2px solid #86efac;border-radius:14px;padding:20px;margin:12px 0"><div style="font-size:32px;font-weight:900;color:#166534">#'+data.order_id+'</div><p style="font-size:13px;color:#166534;margin:4px 0 0">رقم طلبك</p></div><button class="dzq-po-btn dzq-po-success dzq-po-close" style="margin-top:16px">🛒 متابعة التسوق</button>')}
    function showThankYouPage(data){
        var h='<div style="font-size:64px;margin-bottom:12px">✅</div><h2 style="font-size:24px;font-weight:900">'+(dzqcod.po_thankyou_title||'✅ تم إرسال طلبك!')+'</h2>';
        h+='<p style="font-size:15px;color:#64748b;margin-bottom:16px">'+(dzqcod.po_thankyou_msg||'سيتم الاتصال بك قريباً')+'</p>';
        h+='<div style="background:#eef2ff;border:2px solid #a5b4fc;border-radius:14px;padding:20px;margin:12px 0"><div style="font-size:32px;font-weight:900;color:#4f46e5">#'+data.order_id+'</div><p style="font-size:13px;color:#4f46e5;margin:4px 0 0">رقم طلبك</p></div>';
        if(dzqcod.po_show_callback==='yes'){h+='<div style="margin-top:16px;border-top:1px solid #f1f5f9;padding-top:12px"><p style="font-size:13px;color:#94a3b8;margin-bottom:8px">📞 متى تفضل أن نتصل بك؟</p><div style="display:flex;flex-wrap:wrap;gap:6px;justify-content:center">';
            [{k:'morning',l:'☀️ صباحاً'},{k:'afternoon',l:'🌤️ ظهراً'},{k:'evening',l:'🌅 مساءً'},{k:'anytime',l:'⏰ أي وقت'}].forEach(function(s){h+='<button class="dzq-po-slot dzq-cb-slot" data-slot="'+s.k+'" style="display:inline-block;width:auto;padding:8px 14px;font-size:13px">'+s.l+'</button>'});
            h+='</div><button id="dzq-cb-confirm" class="dzq-po-btn dzq-po-primary" data-oid="'+data.order_id+'" style="margin-top:10px;font-size:13px" disabled>📞 إرسال</button></div>'}
        h+='<button class="dzq-po-btn dzq-po-ghost dzq-po-close" style="margin-top:12px;font-size:13px">🏠 إغلاق</button>';
        showPostOrderOverlay(h);
    }
    $(document).on('click','.dzq-po-close',function(){$('#dzqcod-post-order').fadeOut(300,function(){$(this).remove()})});

    // ═══ VALIDATION ═══
    function validate($form){var ok=true;$form.find('[required]').each(function(){$(this).removeClass('error');if(!$(this).val()||!$(this).val().trim()){$(this).addClass('error');ok=false}});
    $form.find('[name=phone],[name=phone2]').each(function(){var v=$(this).val().replace(/\s/g,'');if(v&&!/^0[567]\d{8}$/.test(v)){$(this).addClass('error');ok=false}});
    if(!ok){$form.find('.error').first().focus();$form.find('.dzqcod-msg').removeClass('success').addClass('error').text('يرجى تعبئة الحقول المطلوبة بشكل صحيح').show()}return ok}

    // ═══ COMMUNE AUTO-LOAD ═══
    $(document).on('change','[name=wilaya]',function(){
        var $sel=$(this),$wrap=$sel.closest('.dzqcod-quick-order'),$c=$wrap.find('[name=commune]'),code=$sel.val();
        if(!code){$c.html('<option value="">اختر الولاية أولاً</option>').prop('disabled',true);return}
        $c.html('<option value="">⏳ جاري التحميل...</option>').prop('disabled',true);
        $.post(dzqcod.ajax,{action:'dzqcod_get_communes',wilaya:code},function(r){
            if(r.success&&r.data.communes){var h='<option value="">اختر البلدية</option>';r.data.communes.forEach(function(c){h+='<option value="'+c+'">'+c+'</option>'});$c.html(h).prop('disabled',false)}
            else $c.html('<option value="">أدخل البلدية يدوياً</option>').prop('disabled',false);
        }).fail(function(){$c.html('<option value="">خطأ</option>').prop('disabled',false)});
        recalcAll($wrap);
    });

    // ═══ QTY +/- ═══
    $(document).on('click','.dzqcod-qb.minus',function(){var $i=$(this).siblings('input'),v=parseInt($i.val())||1;if(v>1)$i.val(v-1).trigger('change')});
    $(document).on('click','.dzqcod-qb.plus',function(){var $i=$(this).siblings('input'),v=parseInt($i.val())||1;if(v<99)$i.val(v+1).trigger('change')});
    $(document).on('click','.dzqcod-tier',function(){var $wrap=$(this).closest('.dzqcod-quick-order');$wrap.find('.dzqcod-tier').removeClass('active');$(this).addClass('active');$wrap.find('[name=quantity]').val($(this).data('qty')).trigger('change')});
    $(document).on('change','[name=quantity]',function(){recalcAll($(this).closest('.dzqcod-quick-order'))});

    // ═══════════════════════════════════════════════════════
    //  UNIFIED PRICE RECALCULATION
    // ═══════════════════════════════════════════════════════
    function recalcAll($wrap){
        if(!$wrap||!$wrap.length) $wrap=$w;
        var $b=$wrap.find('.dzqcod-custom-builder');
        if($b.length) recalcCustom($wrap,$b);
        else recalcNormal($wrap);
    }

    function recalcNormal($wrap){
        var base=parseFloat($wrap.data('price'))||0,qty=parseInt($wrap.find('[name=quantity]').val())||1,unit=base;
        var raw=$wrap.data('qty-pricing'),tiers;
        if(raw){try{tiers=typeof raw==='string'?JSON.parse(raw):raw}catch(e){tiers=[]}
        if(tiers&&tiers.length){tiers.sort(function(a,b){return b.min_qty-a.min_qty});for(var i=0;i<tiers.length;i++){if(qty>=tiers[i].min_qty){unit=parseFloat(tiers[i].price);break}}}}
        var $sel=$wrap.find('[name=wilaya] option:selected'),delMode=$wrap.find('[name=delivery_mode]').val()||'home',ship=parseFloat($sel.data(delMode==='desk'?'desk':'home'))||0,sub=unit*qty,tot=sub+ship;
        var $bd=$wrap.find('.dzqcod-breakdown');$bd.find('.bk-qty').text(qty);$bd.find('.bk-sub').text(fmt(sub));
        $bd.find('.bk-ship').text(ship>0?fmt(ship):'اختر الولاية');$bd.find('.bk-tot').text(fmt(tot));$('.bk-tot-sticky').text(fmt(tot));$bd.slideDown();
        if(Math.abs(unit-base)>0.01){$wrap.find('.dzqcod-cprice').html(fmt(unit)+' <small style="font-size:12px;opacity:.7">/ قطعة</small>');
        var sv=Math.round((1-unit/base)*100);$wrap.find('.dzqcod-qty-hint').html(sv>0?'💰 وفّر '+sv+'%':'');}
        else{$wrap.find('.dzqcod-cprice').text(fmt(base));$wrap.find('.dzqcod-qty-hint').html('')}
    }

    // ═══ CUSTOM PRODUCT PRICE CALCULATOR ═══
    function recalcCustom($wrap,$builder){
        var mode=$builder.data('mode')||'fixed';
        var ppu=parseFloat($builder.data('ppu'))||0;
        var base=parseFloat($builder.data('base'))||0;
        var unit=$builder.data('unit')||'م²';

        // 1. Dimensions
        var dims=[];
        $builder.find('.dzqcod-dim').each(function(){dims.push(parseFloat($(this).val())||0)});

        var dimPrice=0,dimLabel='';
        var isCm=(unit.indexOf('سم')>=0||unit.indexOf('cm')>=0);
        switch(mode){
            case 'area':
                var area=(dims[0]||0)*(dims[1]||0);
                if(isCm) area/=10000;
                dimPrice=area*ppu;
                dimLabel=area.toFixed(2)+' '+(isCm?'م²':unit)+' × '+fmtN(ppu)+' دج';
                break;
            case 'linear':
                var len=dims[0]||0;
                if(isCm) len/=100;
                dimPrice=len*ppu;
                dimLabel=len.toFixed(2)+' م × '+fmtN(ppu)+' دج';
                break;
            case 'volume':
                var vol=(dims[0]||0)*(dims[1]||0)*(dims[2]||0);
                if(isCm) vol/=1000000;
                dimPrice=vol*ppu;
                dimLabel=vol.toFixed(4)+' م³ × '+fmtN(ppu)+' دج';
                break;
            case 'weight':
                dimPrice=(dims[0]||0)*ppu;
                dimLabel=(dims[0]||0)+' كغ × '+fmtN(ppu)+' دج';
                break;
        }

        // 2. Options
        var optsTotal=0,optsDetail=[];
        $builder.find('.dzqcod-opt:checked').each(function(){
            var p=parseFloat($(this).data('price'))||0;optsTotal+=p;
            optsDetail.push({name:$(this).closest('label').find('span').first().text(),price:p});
        });
        $builder.find('.dzqcod-opt-select').each(function(){
            var p=parseFloat($(this).find(':selected').data('price'))||0;
            if(p>0){optsTotal+=p;optsDetail.push({name:$(this).find(':selected').text(),price:p})}
        });
        $builder.find('.dzqcod-opt-num').each(function(){
            var v=parseInt($(this).val())||0,p=parseFloat($(this).data('price'))||0;
            if(v>0){var t=v*p;optsTotal+=t;optsDetail.push({name:$(this).closest('.dzqcod-field').find('label').text()+' ×'+v,price:t})}
        });

        // 3. Total
        var qty=parseInt($wrap.find('[name=quantity]').val())||1;
        var unitPrice=base+dimPrice+optsTotal;
        var total=unitPrice*qty;

        // 4. Update calc box
        if(base>0){$('#cc-base').show();$('#cc-base-v').text(fmtN(base)+' دج')} else $('#cc-base').hide();
        if(dimPrice>0){$('#cc-dims').show();$('#cc-dims-v').html(fmtN(dimPrice)+' دج'+(dimLabel?'<br><small style="color:#888;font-size:10px">'+dimLabel+'</small>':''))} else $('#cc-dims').hide();
        if(optsTotal>0){$('#cc-opts').show();$('#cc-opts-v').text(fmtN(optsTotal)+' دج');
            var det='';optsDetail.forEach(function(o){det+='<div style="display:flex;justify-content:space-between"><span>+ '+o.name+'</span><span>'+fmtN(o.price)+' دج</span></div>'});$('#cc-opts-detail').html(det)}
        else{$('#cc-opts').hide();$('#cc-opts-detail').html('')}
        $('#cc-total').text(fmtN(total)+' دج');
        if(qty>1)$('#cc-total').append(' <small style="opacity:.7">('+qty+'×)</small>');

        // 5. Breakdown
        var $sel=$wrap.find('[name=wilaya] option:selected'),delMode=$wrap.find('[name=delivery_mode]').val()||'home',ship=parseFloat($sel.data(delMode==='desk'?'desk':'home'))||0;
        var $bd=$wrap.find('.dzqcod-breakdown');
        $bd.find('.bk-qty').text(qty);$bd.find('.bk-sub').text(fmt(unitPrice));
        $bd.find('.bk-ship').text(ship>0?fmt(ship):'اختر الولاية');$bd.find('.bk-tot').text(fmt(total+ship));$('.bk-tot-sticky').text(fmt(total+ship));$bd.slideDown();

        // 6. Price display
        $wrap.find('.dzqcod-cprice').html(fmtN(unitPrice)+' <small style="font-size:12px;opacity:.7">دج / وحدة</small>');
    }

    function fmt(n){return Math.round(n).toLocaleString('ar-DZ')+' دج'}
    function fmtN(n){return Math.round(n).toLocaleString('ar-DZ')}

    // ═══ BIND CUSTOM BUILDER EVENTS ═══
    var $builder=$w.find('.dzqcod-custom-builder');
    if($builder.length){
        $builder.on('change input','.dzqcod-dim,.dzqcod-opt,.dzqcod-opt-select,.dzqcod-opt-num',function(){
            clearTimeout(window._ccT);window._ccT=setTimeout(function(){recalcCustom($w,$builder)},80);
        });
        $w.find('[name=quantity]').on('change input',function(){recalcCustom($w,$builder)});
        $w.find('[name=wilaya]').on('change',function(){setTimeout(function(){recalcCustom($w,$builder)},50)});
        setTimeout(function(){recalcCustom($w,$builder)},300);
    }

    // ═══ PIXELS ═══
    function fire(d){var v=d&&d.total?d.total:0;if(typeof fbq==='function'){fbq('track','Lead');fbq('track','Purchase',{value:v,currency:'DZD'})}if(typeof ttq==='object'&&ttq.track)ttq.track('SubmitForm');if(typeof gtag==='function')gtag('event','generate_lead',{value:v,currency:'DZD'})}

    // ═══ TRACKING ═══
    window._dzqStart=Date.now();window._dzqScroll=0;
    $(window).on('scroll',function(){var h=$(document).height()-$(window).height();if(h>0){var p=Math.round($(window).scrollTop()/h*100);if(p>window._dzqScroll)window._dzqScroll=p}});

    // ═══ UTM COOKIES ═══
    var params=new URLSearchParams(window.location.search);
    ['utm_source','utm_medium','utm_campaign','utm_content','utm_term','fbclid','ttclid','gclid'].forEach(function(k){var v=params.get(k);if(v)document.cookie='dzqcod_'+k+'='+encodeURIComponent(v)+';path=/;max-age=2592000'});
    if(!document.cookie.match(/dzqcod_landing/))document.cookie='dzqcod_landing='+encodeURIComponent(location.href)+';path=/;max-age=2592000';

    // ═══ COLOR/SIZE VARIANT BUTTONS ═══
    $(document).on('click','.color-btn',function(){var $v=$(this).closest('.dzqcod-variants');$v.find('.color-btn').removeClass('active');$(this).addClass('active');$v.find('input[name=color]').val($(this).data('value'))});
    $(document).on('click','.size-btn',function(){var $v=$(this).closest('.dzqcod-variants');$v.find('.size-btn').removeClass('active');$(this).addClass('active');$v.find('input[name=size]').val($(this).data('value'))});
    $(document).on('change','.dzqcod-pay-opt input',function(){$('.dzqcod-pay-opt').removeClass('active');$(this).closest('.dzqcod-pay-opt').addClass('active')});

    // ═══ COUNTDOWN ═══
    $('.dzqcod-countdown').each(function(){var $cd=$(this),$timer=$cd.find('.cd-timer'),end=new Date($cd.data('end')).getTime();function tick(){var now=Date.now(),diff=end-now;if(diff<=0){$cd.html('⏰ انتهى العرض!');return}var d=Math.floor(diff/86400000),h=Math.floor((diff%86400000)/3600000),m=Math.floor((diff%3600000)/60000),s=Math.floor((diff%60000)/1000);$timer.text((d?d+'ي ':'')+(h<10?'0':'')+h+':'+(m<10?'0':'')+m+':'+(s<10?'0':'')+s);setTimeout(tick,1000)}tick()});

    // ═══ RETURNING CUSTOMER — Phone Lookup ═══
    $(document).on('blur','[name=phone]',function(){
        var ph=$(this).val();if(!ph||!/^0[567]\d{8}$/.test(ph))return;
        $.post(dzqcod.ajax,{action:'dzqcod_phone_lookup',phone:ph},function(r){
            if(!r.success||!r.data.found)return;
            var d=r.data;
            // Show returning customer badge
            var $badge=$('.dzqcod-returning-badge');
            if(!$badge.length){$badge=$('<div class="dzqcod-returning-badge" style="background:linear-gradient(135deg,#eff6ff,#dbeafe);border:1px solid #93c5fd;padding:10px 14px;border-radius:10px;font-size:13px;margin:8px 0;display:flex;align-items:center;gap:8px"></div>');$('[name=phone]').closest('.dzqcod-form-section,.dzqcod-field-group,div').first().after($badge)}
            $badge.html('👋 <strong>مرحباً مجدداً '+d.name+'!</strong> <span style="color:#3b82f6;font-size:11px">('+d.orders+' طلب سابق)</span>');
            // Auto-fill fields
            if(d.name&&!$('[name=name]').val())$('[name=name]').val(d.name);
            if(d.wilaya)$('[name=wilaya]').val(d.wilaya).trigger('change');
            if(d.commune)setTimeout(function(){$('[name=commune]').val(d.commune)},500);
            if(d.address&&!$('[name=address]').val())$('[name=address]').val(d.address);
        });
    });

    // ═══ ABANDONED CART ═══
    var _abT;$(document).on('blur','[name=phone]',function(){var ph=$(this).val(),nm=$('[name=name]').val()||$('[name=full_name]').val()||'';if(!ph||!/^0[567]\d{8}$/.test(ph))return;clearTimeout(_abT);_abT=setTimeout(function(){$.post(dzqcod.ajax,{action:'dzqcod_track_abandoned',phone:ph,name:nm,product_id:pid,wilaya:$('[name=wilaya]').val()||''})},3000)});
    $(window).on('beforeunload',function(){var ph=$('[name=phone]').val();if(ph&&pid&&!/dzqcod_ordered/.test(document.cookie))navigator.sendBeacon(dzqcod.ajax+'?action=dzqcod_track_abandoned',new URLSearchParams({phone:ph,name:$('[name=name]').val()||'',product_id:pid}))});

    // ═══ FILE UPLOAD ═══
    var uploadedFiles=[];
    $(document).on('change','#dzqcod-file-input',function(){var files=this.files;if(!files.length)return;for(var i=0;i<files.length;i++){(function(file){var fd=new FormData();fd.append('action','dzqcod_upload_file');fd.append('product_id',pid);fd.append('dzqcod_file',file);fd.append('_n',$f.find('input[name=_n]').val()||'');var $item=$('<div class="dzqcod-file-item"><span>⏳ '+file.name+'</span></div>');$('#dzqcod-files-list').append($item);$.ajax({url:dzqcod.ajax,data:fd,processData:false,contentType:false,type:'POST',success:function(r){if(r.success){uploadedFiles.push(r.data.url);$('#dzqcod-uploaded-files').val(uploadedFiles.join(','));$item.html('📎 <span>'+r.data.name+' ('+r.data.size+')</span><span class="dzqcod-file-rm" data-url="'+r.data.url+'">✕</span>')}else $item.html('❌ '+file.name+': '+(r.data?r.data.message:'خطأ'))}})})(files[i])}this.value=''});
    $(document).on('click','.dzqcod-file-rm',function(){var url=$(this).data('url');uploadedFiles=uploadedFiles.filter(function(u){return u!==url});$('#dzqcod-uploaded-files').val(uploadedFiles.join(','));$(this).closest('.dzqcod-file-item').remove()});

    // ═══ UPSELL / ORDER BUMP ═══
    if(pid&&typeof dzqcod!=='undefined'&&dzqcod.upsell_enabled==='yes'){$.post(dzqcod.ajax,{action:'dzqcod_get_upsells',product_id:pid},function(r){if(!r.success||!r.data.items||!r.data.items.length)return;var h='<div class="dzqcod-upsells" style="margin:12px 0;padding:12px;background:#fff8e1;border:2px dashed #ffc107;border-radius:12px"><div style="font-weight:700;font-size:14px;margin-bottom:8px">🔥 '+(dzqcod.bump_title||'أضف لطلبك')+'</div>';r.data.items.forEach(function(item){h+='<label class="dzqcod-bump-item" style="display:flex;align-items:center;gap:8px;padding:6px;cursor:pointer;border-bottom:1px solid #f5f5f5"><input type="checkbox" name="bump_ids[]" value="'+item.id+'">';if(item.image)h+='<img src="'+item.image+'" style="width:40px;height:40px;border-radius:6px;object-fit:cover">';h+='<div style="flex:1"><div style="font-size:13px;font-weight:600">'+item.name+'</div>';if(item.bump_price)h+='<div style="font-size:12px"><del style="color:#999">'+item.price.toLocaleString()+' دج</del> <span style="color:#e53935;font-weight:700">'+item.bump_price.toLocaleString()+' دج</span></div>';else h+='<div style="font-size:12px;font-weight:600;color:#e53935">'+item.price.toLocaleString()+' دج</div>';h+='</div></label>'});h+='</div>';$f.find('.dzqcod-form-section').last().after(h)})}

    // ═══ LOYALTY CHECK ═══
    $(document).on('blur','[name=phone]',function(){var ph=$(this).val();if(!ph||!/^0[567]\d{8}$/.test(ph))return;$.post(dzqcod.ajax,{action:'dzqcod_loyalty_check',phone:ph},function(r){if(!r.success||!r.data.found)return;var $badge=$('.dzqcod-loyalty-badge');if(!$badge.length){$badge=$('<div class="dzqcod-loyalty-badge" style="background:linear-gradient(135deg,#ffd700,#ffaa00);padding:8px 12px;border-radius:10px;font-size:13px;margin:6px 0;text-align:center;font-weight:700"></div>');$('[name=phone]').closest('.dzqcod-form-section').append($badge)}$badge.html(r.data.tier_icon+' مستوى '+r.data.tier+' — '+r.data.points+' نقطة'+(r.data.discount_available>0?' — خصم: '+r.data.discount_available+' دج':''))})});

    // ═══ HEATMAP ═══
    var _hmE=[],_hmS=Math.random().toString(36).substr(2,10),_hmF={};
    $(document).on('focus','.dzqcod-form input,.dzqcod-form select,.dzqcod-form textarea',function(){_hmF[this.name]=Date.now()});
    $(document).on('blur','.dzqcod-form input,.dzqcod-form select,.dzqcod-form textarea',function(){var n=this.name,t=_hmF[n]?Math.round((Date.now()-_hmF[n])/1000):0;_hmE.push({pid:pid,field:n,type:this.value?'change':'blur',time:t});delete _hmF[n]});
    setInterval(function(){if(!_hmE.length)return;navigator.sendBeacon(dzqcod.ajax+'?action=dzqcod_track_heatmap',JSON.stringify({session_id:_hmS,events:_hmE}));_hmE=[]},15000);

    // ═══ OTP (pre-submit) ═══
    if(typeof dzqcod!=='undefined'&&dzqcod.otp_enabled==='yes'){
        $(document).on('blur','.dzqcod-form [name=phone]',function(){var ph=$(this).val();if(!ph||!/^0[567]\d{8}$/.test(ph))return;if(sessionStorage.getItem('dzqcod_otp_v_'+ph))return;var $wrap=$(this).closest('.dzqcod-form-section');if(!$wrap.find('.otp-row').length){$wrap.append('<div class="otp-row" style="display:flex;gap:6px;margin-top:6px;align-items:center"><input type="text" id="otp-code" maxlength="4" placeholder="رمز التحقق" style="width:100px;padding:8px;border:1px solid #ddd;border-radius:8px;text-align:center;font-size:18px;letter-spacing:4px"><button type="button" id="send-otp" style="padding:8px 16px;font-size:12px;border:1px solid #ddd;border-radius:8px;cursor:pointer">📱 إرسال رمز</button><button type="button" id="verify-otp" style="padding:8px 16px;font-size:12px;border:1px solid #ddd;border-radius:8px;cursor:pointer;display:none">✅ تحقق</button><span id="otp-msg" style="font-size:12px"></span></div>')}});
        $(document).on('click','#send-otp',function(){var ph=$('[name=phone]').val(),b=$(this);b.prop('disabled',true).text('⏳');$.post(dzqcod.ajax,{action:'dzqcod_send_otp',phone:ph},function(r){b.prop('disabled',false).text('📱 إعادة إرسال');$('#verify-otp').show();$('#otp-msg').text(r.data?r.data.message:'').css('color',r.success?'#4caf50':'#e53935')})});
        $(document).on('click','#verify-otp',function(){var ph=$('[name=phone]').val(),code=$('#otp-code').val();$.post(dzqcod.ajax,{action:'dzqcod_verify_otp',phone:ph,code:code},function(r){if(r.success){$('.otp-row').html('<span style="color:#4caf50;font-weight:700">✅ تم التحقق</span>');sessionStorage.setItem('dzqcod_otp_v_'+ph,'1')}else $('#otp-msg').text(r.data?r.data.message:'رمز خاطئ').css('color','#e53935')})});
    }

});
})(jQuery);
// Delivery toggle (global)
function dzqcodSetDel(btn){
    var wrap=btn.closest('.dzqcod-del-toggle');
    wrap.querySelectorAll('.dzqcod-del-btn').forEach(function(b){b.classList.remove('active')});
    btn.classList.add('active');
    var form=btn.closest('.dzqcod-quick-order')||document.getElementById('dzqcod-form');
    if(form){
        var inp=form.querySelector('[name=delivery_mode]');
        if(inp)inp.value=btn.dataset.del;
        var wil=form.querySelector('[name=wilaya]');
        if(wil)wil.dispatchEvent(new Event('change'));
    }
}
