(function(){ 'use strict'; var form=document.getElementById('ao-customizer-form'),frame=document.getElementById('ao-preview-frame'),stage=document.getElementById('ao-preview-stage'),status=document.getElementById('ao-preview-status'),state=document.getElementById('ao-save-state'),barLabel=document.getElementById('ao-savebar-label'),saveBtn=document.getElementById('ao-save-button'); var pagePaths={home:'/',offers:'/offers/',categories:'/categories/',shop:'/shop/',category:'/category/',product:'/product/',blog:'/blog/'}; var saving=false, history=[], historyIndex=-1, historyTimer=0, restoring=false, contextualMode=true; function setSaveState(type,text){ var map={ready:'جاهز للحفظ',dirty:'تعديلات غير محفوظة',saving:'جارٍ الحفظ…',saved:'تم الحفظ والنشر ✓',error:'فشل الحفظ'}; text=text||map[type]||map.ready; if(state){ state.className='ao-save-state '+(type==='dirty'?'is-dirty':type==='saving'?'is-saving':type==='saved'?'is-saved':type==='error'?'is-error':''); state.innerHTML=(type==='saved'?' ':type==='dirty'?' ':'')+text; } if(barLabel)barLabel.textContent=text; } function toast(message,type){var t=document.getElementById('ao-save-toast');if(!t){t=document.createElement('div');t.id='ao-save-toast';t.className='ao-save-toast';document.body.appendChild(t);}t.textContent=message;t.dataset.type=type||'success';t.classList.add('is-visible');clearTimeout(window.aoToastTimer);window.aoToastTimer=setTimeout(function(){t.classList.remove('is-visible');},4200);} function formSnapshot(){ if(!form)return []; return Array.from(form.elements).filter(function(el){return el.name;}).map(function(el){return {name:el.name,type:el.type||'',value:el.value,checked:!!el.checked};}); } function snapshotKey(s){try{return JSON.stringify(s);}catch(e){return '';}} function updateHistoryButtons(){ var u=document.getElementById('ao-undo'),r=document.getElementById('ao-redo'); if(u)u.disabled=historyIndex<=0; if(r)r.disabled=historyIndex<0||historyIndex>=history.length-1; } function pushHistory(force){ if(restoring||!form)return; var snap=formSnapshot(), key=snapshotKey(snap), last=history[historyIndex]&&snapshotKey(history[historyIndex]); if(!force&&key===last)return; history=history.slice(0,historyIndex+1); history.push(snap); if(history.length>30)history.shift(); historyIndex=history.length-1; updateHistoryButtons(); } function restoreSnapshot(snap){ if(!form||!Array.isArray(snap))return; restoring=true; var map={}; snap.forEach(function(x){if(!map[x.name])map[x.name]=[];map[x.name].push(x);}); Object.keys(map).forEach(function(name){var els=form.querySelectorAll('[name="'+cssEscapeValue(name)+'"]'), vals=map[name]; Array.prototype.forEach.call(els,function(el,i){var v=vals[i]||vals[vals.length-1]; if(el.type==='checkbox') el.checked=!!v.checked; else el.value=v.value; el.dispatchEvent(new Event('input',{bubbles:true}));});}); restoring=false; dirty(); sendPreview(); } function undo(){if(historyIndex<=0)return;historyIndex--;restoreSnapshot(history[historyIndex]);updateHistoryButtons();} function redo(){if(historyIndex>=history.length-1)return;historyIndex++;restoreSnapshot(history[historyIndex]);updateHistoryButtons();} function dirty(){window.aoUnsaved=true;if(form)form.classList.add('ao-has-unsaved');setSaveState('dirty');if(status)status.textContent='التغييرات الحالية لم تُحفظ بعد';} function pathParts(name){ name=String(name||''); var parts=[],m=name.match(/^([^\[]+)/); if(m) { parts.push(m[1]); name=name.slice(m[1].length); } else if(name.indexOf('[')===0) { /* root omitted intentionally */ } var re=/\[([^\]]*)\]/g,x; while((x=re.exec(name))) parts.push(x[1]); return parts.length?parts:[name]; } function setDeep(obj,parts,value){ if(!parts.length)return; var cur=obj; for(var i=0;i'+bp.label+'';ro.setAttribute('data-breakpoint',bp.key);} if(stage){stage.setAttribute('data-viewport-width',String(width));stage.setAttribute('data-breakpoint',bp.key);} updateResponsivePanelContext(bp.device,width); if(frame&&frame.contentWindow)frame.contentWindow.postMessage({type:'alamoffers:viewport-context',width:width,height:height,breakpoint:bp.key,breakpointLabel:bp.label,device:bp.device},window.location.origin); if(remember){try{localStorage.setItem('alamoffers-customizer-viewport-width',String(width));localStorage.setItem('alamoffers-customizer-viewport-height',String(height));}catch(e){}} } function installViewportLab(){ var wi=document.getElementById('ao-viewport-width'),he=document.getElementById('ao-viewport-height'); if(wi)wi.addEventListener('input',function(){applyViewport(wi.value,he?he.value:760,true);}); if(he)he.addEventListener('input',function(){applyViewport(wi?wi.value:1440,he.value,true);}); document.querySelectorAll('[data-viewport-width]').forEach(function(b){b.addEventListener('click',function(){var w=parseInt(b.dataset.viewportWidth,10)||1440;applyViewport(w,he?he.value:760,true);var bp=viewportBreakpoint(w);setDevice(bp.device);});}); var w=1440,h=760;try{w=parseInt(localStorage.getItem('alamoffers-customizer-viewport-width'),10)||w;h=parseInt(localStorage.getItem('alamoffers-customizer-viewport-height'),10)||h;}catch(e){} applyViewport(w,h,false); } function setDevice(device){ device=String(device||'desktop'); if(['desktop','tablet','mobile'].indexOf(device)<0)device='desktop'; if(!stage)return; var shell=stage.querySelector('.ao-device-frame'); if(shell){var sw=shell.style.width,sh=shell.style.height,sm=shell.style.maxWidth;shell.className='ao-device-frame ao-device-'+device;shell.style.width=sw;shell.style.height=sh;shell.style.maxWidth=sm;} document.body.setAttribute('data-ao-edit-device',device); document.querySelectorAll('[data-device]').forEach(function(b){b.classList.toggle('is-active',b.dataset.device===device);b.setAttribute('aria-pressed',b.dataset.device===device?'true':'false');}); var labels={desktop:'سطح المكتب',tablet:'iPad / جهاز لوحي',mobile:'الجوال'}; if(status)status.textContent='تحرير ومعاينة: '+(labels[device]||device); try{localStorage.setItem('alamoffers-customizer-device',device);}catch(e){} var width=currentViewportWidth(); updateResponsivePanelContext(device,width); if(frame&&frame.contentWindow)frame.contentWindow.postMessage({type:'alamoffers:device-context',device:device,width:width,breakpoint:viewportBreakpoint(width).key},window.location.origin); applyResponsiveControlState(device); } function setPage(page){if(!frame)return;var cfg=window.AOCustomizer||{},urls=cfg.previewUrls||{},base=urls[page]||pagePaths[page]||urls.home||'/';frame.src=base+(base.indexOf('?')>=0?'&':'?')+'ao_customizer_preview=1';document.querySelectorAll('[data-preview-page]').forEach(function(b){b.classList.toggle('is-active',b.dataset.previewPage===page);});var labels={home:'الرئيسية',offers:'العروض',categories:'التصنيفات',shop:'المتجر',category:'التصنيف',product:'المنتج',blog:'المدونة'};if(status)status.textContent='تحميل معاينة '+(labels[page]||page);try{localStorage.setItem('alamoffers-customizer-preview-page',page);}catch(e){}} function setContextualMode(on){contextualMode=!!on;var b=document.getElementById('ao-context-select-toggle');if(b){b.classList.toggle('is-active',contextualMode);b.setAttribute('aria-pressed',contextualMode?'true':'false');b.innerHTML=' '+(contextualMode?'إيقاف تحديد العنصر':'تحديد عنصر من المعاينة');}if(frame&&frame.contentWindow)frame.contentWindow.postMessage({type:'alamoffers:context-mode',enabled:contextualMode},window.location.origin);} var focusMap={brand:{page:'home',selectors:['.ao-header .ao-logo','.ao-logo']},colors:{page:'home',selectors:['.ao-home','.ao-header','.ao-product-card']},typography:{page:'home',selectors:['body','.ao-home','.ao-product-card']},header:{page:'home',selectors:['.ao-header']},navigation:{page:'home',selectors:['.ao-category-nav','.ao-menu']},product:{page:'product',selectors:['.single-product .product','.single-product .summary','.ao-product-card']},shop:{page:'shop',selectors:['.ao-shop-layout','.ao-shop-toolbar','.ao-shop-results']},category:{page:'category',selectors:['.ao-category-header','.woocommerce-products-header','.ao-category-grid','.product-categories']},deals:{page:'offers',selectors:['.ao-deals','.ao-product-grid','.ao-product-card']},homepage:{page:'home',selectors:['.ao-home']},hero:{page:'home',selectors:['.ao-hero-slider','.ao-hero','.ao-promo-strip']},ads:{page:'home',selectors:['.ao-ad-slot','.ao-ad','.alam-ad','.ao-home']},blog:{page:'blog',selectors:['main article','.ao-blog-grid','.site-main']},mobile:{page:'home',selectors:['.ao-mobile-bottom-nav','.mobile-bottom-nav','.ao-header','.ao-home']},footer:{page:'home',selectors:['.ao-footer']},advanced:{page:'home',selectors:['body']},app:{page:'home',selectors:['body']}}; function focusPreview(tab){var cfg=focusMap[tab]||focusMap.home;if(!frame||!frame.contentWindow)return;frame.contentWindow.postMessage({type:'alamoffers:focus',selectors:cfg.selectors||[]},window.location.origin);var page=cfg.page||'home';var active=document.querySelector('[data-preview-page].is-active');if(active&&active.dataset.previewPage===page){return;}setPage(page);} function installFocusButton(){var actions=document.querySelector('.ao-panel-head-actions');if(!actions||document.getElementById('ao-focus-preview'))return;var b=document.createElement('button');b.type='button';b.className='button ao-focus-preview';b.id='ao-focus-preview';b.title='إبراز العنصر في المعاينة';b.innerHTML=' إبراز في المعاينة';b.addEventListener('click',function(){var item=document.querySelector('.ao-tab.is-active[data-nav-item]');if(item)focusPreview(item.dataset.navItem);});actions.insertBefore(b,actions.firstChild);} function markClean(){window.aoUnsaved=false;if(form)form.classList.remove('ao-has-unsaved');setSaveState('saved');try{localStorage.removeItem('alamoffers-customizer-draft');}catch(e){}} function nativeFallback(){if(!form)return;form.dataset.nativeFallback='1';try{localStorage.removeItem('alamoffers-customizer-draft');}catch(e){}setSaveState('saving','الحفظ المباشر…');HTMLFormElement.prototype.submit.call(form);} function save(){ if(!form||saving)return; saving=true; if(saveBtn)saveBtn.disabled=true; setSaveState('saving'); var cfg=window.AOCustomizer||{}; if(!cfg.ajax||!cfg.saveNonce){nativeFallback();return;} var fd=new FormData(form); fd.set('action',cfg.ajaxAction||'alam_save_settings'); fd.set('nonce',cfg.saveNonce); fetch(cfg.ajax,{method:'POST',credentials:'same-origin',headers:{'X-Requested-With':'XMLHttpRequest','Accept':'application/json'},body:fd}) .then(function(r){return r.text().then(function(txt){var data;try{data=JSON.parse(txt);}catch(e){throw new Error('HTTP '+r.status+' — '+txt.slice(0,180));}if(!r.ok||!data.success)throw new Error(data&&data.data&&data.data.message?data.data.message:'HTTP '+r.status);return data;});}) .then(function(res){ markClean(); var msg=(res.data&&res.data.message)||'تم الحفظ والنشر ✓'; toast(msg,'success'); if(status)status.textContent=(res.data&&res.data.option)?'تم تأكيد الكتابة في '+res.data.option:'تم الحفظ في قاعدة البيانات'; if(frame){var src=frame.src.replace(/([?&])ao_saved=[^&]*/,'').replace(/[?&]$/,'');frame.src=src+(src.indexOf('?')>=0?'&':'?')+'ao_saved='+Date.now();} }) .catch(function(err){ setSaveState('error'); toast('تعذر الحفظ: '+(err.message||'خطأ غير معروف')+' — سيتم استخدام الحفظ المباشر.','error'); window.setTimeout(nativeFallback,60); }) .finally(function(){saving=false;if(saveBtn)saveBtn.disabled=false;}); } function storeDraft(){if(!form||!window.aoUnsaved)return;try{localStorage.setItem('alamoffers-customizer-draft',JSON.stringify({savedAt:Date.now(),entries:Array.from(new FormData(form).entries())}));}catch(e){}} function cssEscapeValue(v){return window.CSS&&CSS.escape?CSS.escape(v):String(v).replace(/[^a-zA-Z0-9_\-]/g,'\\$&');} function restoreDraft(){ if(!form)return; try{ var raw=localStorage.getItem('alamoffers-customizer-draft');if(!raw)return; var draft=JSON.parse(raw);var arr=Array.isArray(draft)?draft:draft&&draft.entries;if(!Array.isArray(arr)||!arr.length)return;if(draft&&draft.savedAt&&Date.now()-Number(draft.savedAt)>1800000){localStorage.removeItem('alamoffers-customizer-draft');return;} if(!confirm('توجد تعديلات محلية غير محفوظة لهذه الصفحة. هل تريد استعادتها؟')){localStorage.removeItem('alamoffers-customizer-draft');return;} arr.forEach(function(pair){ if(!Array.isArray(pair)||pair.length<2)return; var els=form.querySelectorAll('[name="'+cssEscapeValue(pair[0])+'"]');if(!els.length)return; var v=pair[1]; els.forEach(function(el){ if(el.type==='checkbox')el.checked=(v==='1'||v==='true'); else if(el.type!=='hidden')el.value=v; }); }); send(); }catch(e){} } if(form){ form.addEventListener('submit',function(e){if(form.dataset.nativeFallback==='1')return;e.preventDefault();save();}); form.addEventListener('focusin',function(e){ if(e.target && e.target.name) focusInlinePreviewForControl(e.target); }); form.addEventListener('input',function(e){ if(e.target && e.target.name) focusInlinePreviewForControl(e.target); var r=e.target.getAttribute('data-range'); if(r){var o=form.querySelector('[data-range-value="'+cssEscapeValue(r)+'"]');if(o){var suffix=e.target.dataset.suffix||((r.indexOf('splash_')===0)?' ms':((r.indexOf('cooldown')!==-1)?' دقيقة':((r.indexOf('min_discount')!==-1)?'%':'')));o.textContent=e.target.value+suffix;}} if(e.target.type==='color'){var out=form.querySelector('[data-color-output="'+cssEscapeValue(e.target.id)+'"]');if(out)out.value=e.target.value;} send(); if(!restoring){clearTimeout(historyTimer);historyTimer=setTimeout(function(){pushHistory(false);},180);} }); form.addEventListener('change',function(){send();pushHistory(false);}); pushHistory(true); setInterval(storeDraft,2000); window.setTimeout(restoreDraft,250); } if(frame)frame.addEventListener('load',function(){sendPreview();setContextualMode(contextualMode);var d=document.body.getAttribute('data-ao-edit-device')||'desktop';var w=currentViewportWidth();if(frame.contentWindow)frame.contentWindow.postMessage({type:'alamoffers:device-context',device:d,width:w,breakpoint:viewportBreakpoint(w).key},window.location.origin);updateResponsivePanelContext(d,w);}); var refresh=document.getElementById('ao-preview-refresh');if(refresh)refresh.addEventListener('click',function(){if(frame){var src=frame.src.replace(/([?&])ao_refresh=[^&]*/,'');frame.src=src+(src.indexOf('?')>=0?'&':'?')+'ao_refresh='+Date.now();}}); var contextToggle=document.getElementById('ao-context-select-toggle');if(contextToggle){contextToggle.addEventListener('click',function(){setContextualMode(!contextualMode);});setContextualMode(true);} document.querySelectorAll('[data-device]').forEach(function(b){b.addEventListener('click',function(){setDevice(b.dataset.device);});}); var initialDevice='desktop';try{initialDevice=localStorage.getItem('alamoffers-customizer-device')||'desktop';}catch(e){} setDevice(initialDevice); installViewportLab(); installVisualSpacingLab(); installGridLab();installHeaderHeroLab(); applyResponsiveControlState(initialDevice); document.querySelectorAll('[data-preview-page]').forEach(function(b){b.addEventListener('click',function(){setPage(b.dataset.previewPage);});}); var initialPreviewPage='home';try{initialPreviewPage=localStorage.getItem('alamoffers-customizer-preview-page')||'home';}catch(e){} if(document.querySelector('[data-preview-page="'+initialPreviewPage+'"]')) setPage(initialPreviewPage); document.getElementById('ao-undo')&&document.getElementById('ao-undo').addEventListener('click',undo); document.getElementById('ao-redo')&&document.getElementById('ao-redo').addEventListener('click',redo); document.querySelectorAll('.ao-reset-section').forEach(function(btn){btn.addEventListener('click',function(){ var section=btn.dataset.section, defs=window.AOCustomizer&&window.AOCustomizer.defaults&&window.AOCustomizer.defaults[section]; if(!defs||!form||!confirm('سيتم إعادة قسم «'+section+'» إلى القيم الافتراضية داخل المعاينة. لن يتم نشرها حتى تضغط حفظ.'))return; var prefix='alamoffers_theme_settings['+section+']'; Object.keys(defs).forEach(function(key){ var els=form.querySelectorAll('[name^="'+cssEscapeValue(prefix+'['+key+']')+'"]'); if(Array.isArray(defs[key])){ return; } if(!els.length)return; var v=defs[key]; Array.prototype.forEach.call(els,function(el){if(el.type==='checkbox')el.checked=!!v; else if(el.type!=='hidden')el.value=v;}); }); pushHistory(true); dirty(); sendPreview(); toast('تمت إعادة القسم إلى القيم الافتراضية — احفظ للنشر.','success'); });}); var discard=document.getElementById('ao-discard-draft'); if(discard)discard.addEventListener('click',function(){try{localStorage.removeItem('alamoffers-customizer-draft');}catch(e){};window.aoUnsaved=false;if(form)form.classList.remove('ao-has-unsaved');setSaveState('ready');toast('تم تجاهل المسودة المحلية.','success');}); document.addEventListener('keydown',function(e){if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()==='s'){e.preventDefault();save();}}); window.addEventListener('beforeunload',function(e){if(window.aoUnsaved){e.preventDefault();e.returnValue='';}}); document.querySelectorAll('.ao-media-pick').forEach(function(btn){btn.addEventListener('click',function(){var target=btn.dataset.target,input=document.querySelector('.ao-media-id[data-target="'+cssEscapeValue(target)+'"]'),preview=document.getElementById('ao-media-preview-'+target);if(!window.wp||!wp.media||!input)return;var modal=wp.media({title:'اختيار صورة',button:{text:'استخدام الصورة'},multiple:false,library:{type:['image']}});modal.on('select',function(){var a=modal.state().get('selection').first().toJSON();input.value=a.id;preview.innerHTML='';send();});modal.open();});}); document.querySelectorAll('.ao-media-clear').forEach(function(btn){btn.addEventListener('click',function(){var target=btn.dataset.target,input=document.querySelector('.ao-media-id[data-target="'+cssEscapeValue(target)+'"]'),preview=document.getElementById('ao-media-preview-'+target);if(input)input.value='0';if(preview)preview.innerHTML='لا يوجد ملف';send();});}); var sort=document.getElementById('ao-section-sort'); if(sort){var dragged=null;sort.querySelectorAll('.ao-sort-row').forEach(function(row){row.addEventListener('dragstart',function(){dragged=row;row.classList.add('is-dragging');});row.addEventListener('dragend',function(){row.classList.remove('is-dragging');send();});row.addEventListener('dragover',function(e){e.preventDefault();if(!dragged||dragged===row)return;var rect=row.getBoundingClientRect();var before=e.clientY