function _e(o,t={}){const e=typeof NotifalOnPageStrings<"u"&&NotifalOnPageStrings[o]?NotifalOnPageStrings[o]:o;return Object.keys(t).reduce((a,n)=>a.replace(`{${n}}`,t[n]),e)}function gt(o){o.classList.toggle("active");const t=o.querySelector('input[type="hidden"]');o.classList.contains("active")?(t.removeAttribute("disabled"),NotifalUtils.showMessage(_e("label_added"),"success",2e3)):(t.setAttribute("disabled","disabled"),NotifalUtils.showMessage(_e("label_removed"),"info",2e3))}function yt(o){const t=o.closest(".notifal-label-badges"),e=t.querySelector('input[type="text"]'),a=e.value.trim();if(!a){NotifalUtils.showMessage(_e("enter_label_name"),"error");return}o.disabled=!0;const n=o.innerHTML,i=o.getAttribute("data-loading-text")||"Adding...";o.innerHTML='<span class="notifal-spinner size-16"></span>'+i;const _=new FormData;_.append("action","notifal_add_label_term"),_.append("nonce",NotifalOnPageAjax.nonce.add_label),_.append("name",a),fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:_}).then(m=>m.json()).then(m=>{if(!m.success){NotifalUtils.showMessage(m.data||"Something went wrong.","error");return}const f=m.data?.term;if(!f||!f.slug){NotifalUtils.showMessage(_e("unexpected_response"),"error");return}if(t.querySelector(`[data-slug="${f.slug}"]`)){NotifalUtils.showMessage(_e("label_exists"),"info");return}const b=document.createElement("div");b.className="notifal-label-badge notifal-flex notifal-align-center active",b.dataset.slug=f.slug,b.dataset.termId=f.term_id,b.innerHTML=`
                ${f.name}
                <input type="hidden" name="notifal_labels[]" value="${f.slug}">
                <button type="button" class="notifal-remove-badge" aria-label="Remove label">
                    <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                </button>
            `,t.insertBefore(b,t.querySelector(".notifal-label-add-wrapper")),e.value="",NotifalUtils.showMessage(_e("label_added_success"),"success")}).catch(()=>{NotifalUtils.showMessage(_e("generic_error"),"error")}).finally(()=>{o.disabled=!1,o.innerHTML=n})}function vt(o){const t=o.closest(".notifal-label-badge"),e=t?.dataset.slug,a=t?.dataset.termId,n=t?Array.from(t.childNodes).filter(_=>_.nodeType===Node.TEXT_NODE).map(_=>_.textContent.trim()).join("").trim():"";if(!e||!a||!confirm(`${_e("confirm_remove_label")} "${n}"?`))return;o.disabled=!0;const i=new FormData;i.append("action","notifal_remove_label_term"),i.append("nonce",NotifalOnPageAjax.nonce.remove_label),i.append("slug",e),i.append("term_id",a),fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:i}).then(_=>_.json()).then(_=>{if(!_.success){NotifalUtils.showMessage(_e("label_remove_fail"),"error"),o.disabled=!1;return}t.remove(),NotifalUtils.showMessage(_e("label_remove_success"),"success")}).catch(()=>{NotifalUtils.showMessage(_e("label_remove_error"),"error"),o.disabled=!1})}function Be(){document.body.addEventListener("click",o=>{if(o.target.classList.contains("notifal-label-badge")||o.target.closest(".notifal-label-badge")){const t=o.target.classList.contains("notifal-label-badge")?o.target:o.target.closest(".notifal-label-badge");!o.target.classList.contains("notifal-remove-badge")&&!o.target.closest(".notifal-remove-badge")&&gt(t)}if(o.target.classList.contains("notifal-label-add-btn")||o.target.closest(".notifal-label-add-btn")){const t=o.target.classList.contains("notifal-label-add-btn")?o.target:o.target.closest(".notifal-label-add-btn");yt(t)}if(o.target.classList.contains("notifal-remove-badge")||o.target.closest(".notifal-remove-badge")){const t=o.target.classList.contains("notifal-remove-badge")?o.target:o.target.closest(".notifal-remove-badge");vt(t)}})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Be):Be();function Re(){const o=document.querySelector('[name="display_rule_type"]'),t=document.querySelectorAll(".notifal-display-condition-section");o?.addEventListener("change",()=>{const e=o.value;if(["pages","posts","products"].includes(e)){const a=e;o.value="post_type",St(a),t.forEach(i=>i.classList.add("notifal-hidden"));const n=document.querySelector(".notifal-display-post_type");if(n){n.classList.remove("notifal-hidden");const i=typeof window<"u"&&window.notifalConfigureQuickSelectorSettings?window.notifalConfigureQuickSelectorSettings:Fe;typeof i=="function"&&i(a,n)}}else t.forEach(a=>a.classList.add("notifal-hidden")),document.querySelector(`.notifal-display-${e}`)?.classList.remove("notifal-hidden");if(e==="users"){const a=document.getElementById("target_user_type"),n=document.getElementById("limit_by_roles"),i=document.querySelector(".notifal-display-users .notifal-field-wrapper:last-child"),_=a?.value==="logged_in",m=n?.checked,f=n?.closest(".notifal-field-wrapper");f&&f.classList.toggle("notifal-hidden",!_),i&&i.classList.toggle("notifal-hidden",!(_&&m))}if(e==="url_match"){const a=document.querySelector(".notifal-display-url_match");if(a&&!a.dataset.urlMatchBound){a.dataset.urlMatchBound="1";const i=a.querySelector('[name="url_match_target"]'),_=a.querySelector(".notifal-url-match-url-mode"),m=a.querySelector(".notifal-url-match-param-mode"),f=a.querySelector('[name="target_url_param_operator"]'),h=a.querySelector('input[name="target_url_param_value"]')?.closest(".notifal-field-wrapper"),b=["exists","not_exists"],E=()=>{const x=(i?.value||"url")==="param";if(_&&_.classList.toggle("notifal-hidden",x),m&&m.classList.toggle("notifal-hidden",!x),x&&h){const I=f?.value||"";h.classList.toggle("notifal-hidden",b.includes(I))}};i?.addEventListener("change",E),f?.addEventListener("change",E)}const n=document.querySelector(".notifal-display-url_match");if(n){const i=n.querySelector('[name="url_match_target"]'),_=n.querySelector(".notifal-url-match-url-mode"),m=n.querySelector(".notifal-url-match-param-mode"),f=n.querySelector('[name="target_url_param_operator"]'),h=n.querySelector('input[name="target_url_param_value"]')?.closest(".notifal-field-wrapper"),E=(i?.value||"url")==="param";if(_&&_.classList.toggle("notifal-hidden",E),m&&m.classList.toggle("notifal-hidden",!E),E&&h){const k=f?.value||"";h.classList.toggle("notifal-hidden",["exists","not_exists"].includes(k))}}}e==="categories"&&setTimeout(()=>{const a=document.querySelector(".notifal-display-categories");if(a){const n=a.querySelector(".notifal-ajax-search-selected");if(n&&n.querySelectorAll(".notifal-selected-item").length===0){const _=["post"];window.NotifalOnPageConfig&&window.NotifalOnPageConfig.isWooCommerceActive&&_.push("product"),_.forEach(m=>{const f=document.createElement("div");f.className="notifal-selected-item",f.dataset.id=m,f.innerHTML=`
                                    <span class="notifal-selected-label">${ge(m)} (${m})</span>
                                    <input type="hidden" name="target_categories_post_types[]" value="${m}" />
                                    <button type="button" class="notifal-remove-selected">
                                        <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                                    </button>
                                `;const h=f.querySelector(".notifal-remove-selected");h&&h.addEventListener("click",()=>{f.remove()}),n.appendChild(f)})}}},100)})}function Fe(o,t){const a={pages:"page",posts:"post",products:"product"}[o];a&&ht(t,a)}try{typeof window<"u"&&(window.notifalConfigureQuickSelectorSettings=Fe)}catch{}function ht(o,t){const e=o.querySelector('[name="target_post_type_visibility"]');if(e){e.value="specific";const n=o.querySelector(".notifal-post-type-selection"),i=o.querySelector(".notifal-post-items-visibility");o.querySelector(".notifal-post-items-selection"),n&&n.classList.remove("notifal-hidden"),i&&i.classList.remove("notifal-hidden"),e.dispatchEvent(new Event("change"))}const a=()=>{const n=o.querySelector('.notifal-ajax-search[data-name="target_post_types[]"]');if(!n){const i=o.querySelector('[data-name="target_post_types[]"]');if(!i){setTimeout(a,50);return}Ve(i,t);return}Ve(n,t)};setTimeout(a,100)}function Ve(o,t){o.querySelectorAll(".notifal-selected-item").forEach(n=>n.remove());const a={id:t,title:ge(t)};bt(a,o)}function ge(o){return{page:"Page",post:"Post",product:"Product"}[o]||o}function bt(o,t){const e=t.querySelector(".notifal-ajax-search-selected");if(!e)return;const a=document.createElement("div");a.className="notifal-selected-item",a.dataset.id=o.id,a.innerHTML=`
        <span class="notifal-selected-label">${o.title} (${o.id})</span>
        <input type="hidden" name="target_post_types[]" value="${o.id}" />
        <button type="button" class="notifal-remove-selected">
            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
        </button>
    `;const n=a.querySelector(".notifal-remove-selected");n&&n.addEventListener("click",()=>{a.remove()}),e.appendChild(a)}function St(o){const t=document.createElement("div");t.className="notifal-quick-selector-feedback";const e={pages:"Pages",posts:"Posts",products:"Products"};t.innerHTML=`
        <span class="notifal-icon notifal-icon-question-circle size-16"></span>
        <span>${e[o]} automatically switched to Post Type for easier configuration.</span>
    `;const a=document.querySelector('[name="display_rule_type"]').closest(".notifal-field-wrapper");a&&(a.parentNode.insertBefore(t,a.nextSibling),setTimeout(()=>{t.parentNode&&t.remove()},3e3))}function ye(o){if(!o)return[];const t=o.querySelectorAll(".notifal-selected-item");return Array.from(t).map(e=>{const a=e.getAttribute("data-id");return a===null||typeof a>"u"?null:/^\d+$/.test(String(a))?parseInt(a,10):a}).filter(e=>e!==null)}function Ue(o,t){ce()}function ce(){const o=document.getElementById("notifal-display-rule-list"),t=document.getElementById("notifal-display-rules-summary"),e=document.getElementById("notifal-rules-count");if(!o)return;const a=o.children.length;if(t&&(a>0?(t.classList.remove("notifal-hidden"),t.style.display="block",t.style.visibility="visible",t.style.opacity="1"):(t.classList.add("notifal-hidden"),t.style.display="none")),e)e.textContent=a,e.style.display="inline-block",e.style.visibility="visible",e.style.opacity="1";else{const i=document.querySelector(".notifal-summary-count");i&&(i.textContent=a,i.style.display="inline-block",i.style.visibility="visible",i.style.opacity="1")}const n=document.getElementById("notifal-rule-combination-logic");return n&&(n.style.display=a>1?"block":"none"),a}function De(o,t){switch(o){case"pages":case"posts":case"products":return De("post_type",t);case"url_match":if(t.param_name&&String(t.param_name).trim()!==""){if(!["exists","not_exists"].includes(t.operator)&&(t.value===void 0||String(t.value).trim()===""))return{isValid:!1,message:NotifalOnPageStrings.enter_url_keyword||"Please enter a value to match for the URL parameter."}}else if(!t.keywords||t.keywords.length===0)return{isValid:!1,message:NotifalOnPageStrings.enter_url_keyword||"Please enter at least one URL keyword."};break;case"users":if(t.user_type==="logged_in"&&t.limit_by_roles&&(!t.roles||t.roles.length===0))return{isValid:!1,message:NotifalOnPageStrings.select_user_role||"Please select at least one user role."};break;case"post_type":return t.visibility==="all"?{isValid:!0}:!t.post_types||t.post_types.length===0?{isValid:!1,message:NotifalOnPageStrings.select_post_type||"Please select at least one post type."}:t.items_visibility&&t.items_visibility!=="all"&&(!t.post_items||t.post_items.length===0)?{isValid:!1,message:NotifalOnPageStrings.select_post_items||"Please select at least one post item."}:{isValid:!0};case"categories":return t.post_types_visibility==="all"?{isValid:!0}:!t.post_types||t.post_types.length===0?{isValid:!1,message:NotifalOnPageStrings.select_post_type||"Please select at least one post type to search categories from."}:t.mode==="specific"&&(!t.targets||t.targets.length===0)?{isValid:!1,message:NotifalOnPageStrings.select_categories||"Please select at least one category."}:{isValid:!0};default:if(!t.targets||t.targets.length===0)return{isValid:!1,message:NotifalOnPageStrings.select_post_type||"Please select at least one post type."};if(["pages","posts","products"].includes(o)&&t.items_visibility&&t.items_visibility!=="all"&&(!t.post_items||t.post_items.length===0))return{isValid:!1,message:NotifalOnPageStrings.select_post_items||"Please select at least one post item."}}return{isValid:!0}}function ut(o,t){const e={};switch(o){case"pages":case"posts":case"products":{const F=document.querySelector(".notifal-display-post_type");if(F)return ut("post_type",F);const N=document.querySelector('[name="target_post_type_visibility"]')?.value||"all",U=ye(document.querySelector('[data-name="target_post_types[]"]')),$=document.querySelector('[name="target_post_items_visibility"]')?.value||"all",O=ye(document.querySelector('[data-name="target_post_items[]"]'));return{visibility:N,post_types:U,items_visibility:$,post_items:O}}case"categories":{const F=t?.querySelector('[name="target_categories_mode"]')?.value||"specific",N=t?.querySelector('[name="target_categories_post_types_visibility"]')?.value||"specific",U=ye(t?.querySelector('[data-name="target_categories_post_types[]"]')),$=ye(t?.querySelector('[data-name="target_categories"]'));return{mode:F,post_types_visibility:N,post_types:U,targets:$}}case"url_match":{if((t?.querySelector('[name="url_match_target"]')?.value||"url")==="param")e.param_name=t?.querySelector('input[name="target_url_param_name"]')?.value?.trim()||"",e.operator=t?.querySelector('[name="target_url_param_operator"]')?.value||"equals",e.value=t?.querySelector('input[name="target_url_param_value"]')?.value?.trim()||"";else{const U=t?.querySelector('input[name="target_url_keywords"]');e.keywords=U?.value.trim().split(",").map($=>$.trim()).filter(Boolean)||[],e.mode=t?.querySelector('[name="url_match_mode"]')?.value||"contains"}break}case"users":const a=t?.querySelector('[name="target_user_type"]')?.value||"guest",n=t?.querySelector('[name="limit_by_roles"]')?.checked,i=t?.querySelector('[name="target_user_roles[]"]'),_=Array.from(i?.selectedOptions||[]).map(F=>F.value);e.user_type=a,e.limit_by_roles=n,e.roles=_;break;case"post_type":const m=t.querySelector('[name="target_post_type_visibility"]')?.value||"all",f=ye(t.querySelector('[data-name="target_post_types[]"]')),h=t.querySelector('[name="target_post_items_visibility"]')?.value||"all",b=ye(t.querySelector('[data-name="target_post_items[]"]'));return{visibility:m,post_types:f,items_visibility:h,post_items:b};default:const E=t?.querySelector(".notifal-ajax-search-selected"),x=t?.querySelector(`[name="target_${o}_mode"]`)?.value||"specific",I=[];if(E?.querySelectorAll(".notifal-selected-item")?.forEach(F=>{const N=F.querySelector('input[type="hidden"]');N?.value&&I.push(parseInt(N.value))}),e.targets=I,e.mode=x,["pages","posts","products"].includes(o)){const F=t.querySelector('[name="target_post_items_visibility"]')?.value||"all",N=ye(t.querySelector('[data-name="target_post_items[]"]'));e.items_visibility=F,e.post_items=N}}return e}window.notifalGenerateRuleSummary=function(o,t){const e={pages:'<span class="notifal-icon notifal-icon-file-earmark1 size-16"></span>',posts:'<span class="notifal-icon notifal-icon-file-earmark1 size-16"></span>',products:'<span class="notifal-icon notifal-icon-file-plus size-16"></span>',post_type:'<span class="notifal-icon notifal-icon-file-earmark1 size-16"></span>',categories:'<span class="notifal-icon notifal-icon-tags-fill size-16"></span>',url_match:'<span class="notifal-icon notifal-icon-link-45deg size-16"></span>',users:'<span class="notifal-icon notifal-icon-file-earmark-person size-16"></span>'},a=o.replace(/_/g," "),n=a.charAt(0).toUpperCase()+a.slice(1);switch(o){case"pages":case"posts":case"products":{const N=t.post_types?.length||0,U=t.visibility==="exclude"?"All Except":"Only";let $="";return t.post_types&&t.post_types.length>0&&($=`: ${t.post_types.map(G=>ge(G)).join(", ")}`),`${e.post_type} <span class="notifal-rule-text">Post Type: ${U} (${N})${$}</span>`}case"url_match":if(t.param_name&&String(t.param_name).trim()!==""){const N=t.param_name,U=t.operator||"equals",$=U.replace(/_/g," ").replace(/\b\w/g,G=>G.toUpperCase());if(["exists","not_exists"].includes(U))return`${e[o]} <span class="notifal-rule-text">URL: param [${N}] ${$}</span>`;const O=t.value||"";return`${e[o]} <span class="notifal-rule-text">URL: param [${N}] ${$} [${O}]</span>`}const i=t.keywords?.length||0,_=t.mode?t.mode.charAt(0).toUpperCase()+t.mode.slice(1):"Contains";return`${e[o]} <span class="notifal-rule-text">${n}: ${_} (${i})</span>`;case"users":return t.user_type==="guest"?`${e[o]} <span class="notifal-rule-text">${n}: Guests Only</span>`:t.limit_by_roles&&t.roles?.length?`${e[o]} <span class="notifal-rule-text">${n}: Logged-in Users (${t.roles.length} roles)</span>`:`${e[o]} <span class="notifal-rule-text">${n}: Logged-in Users</span>`;case"post_type":if(t.visibility==="all")return`${e[o]} <span class="notifal-rule-text">Post Type: All</span>`;const m=t.post_types?.length||0,f=t.visibility==="exclude"?"All Except":"Only";let h="";return t.post_types&&t.post_types.length>0&&(h=`: ${t.post_types.map(U=>ge(U)).join(", ")}`),`${e[o]} <span class="notifal-rule-text">Post Type: ${f} (${m})${h}</span>`;case"categories":if(t.post_types_visibility==="all")return`${e[o]} <span class="notifal-rule-text">Categories: All Post Types</span>`;const b=t.post_types?.length||0,E=t.post_types_visibility==="exclude"?"All Except":"Only",k=t.mode==="exclude"?"All Except":"Only",x=t.targets?.length||0;t.post_types&&t.post_types.length>0&&`${t.post_types.map(U=>ge(U)).join(", ")}`;let I=`Categories: ${k} (${x})`;return t.post_types_visibility==="specific"&&(I+=` for ${E} Post Types (${b})`),`${e[o]} <span class="notifal-rule-text">${I}</span>`;default:const P=t.targets?.length||0,F=t.mode==="exclude"?"All Except":"Only";return`${e[o]} <span class="notifal-rule-text">${n}: ${F} (${P})</span>`}};window.notifalGenerateRuleDetails=function(o,t){switch(o){case"pages":case"posts":case"products":return window.notifalGenerateRuleDetails("post_type",t);case"url_match":if(t.param_name&&String(t.param_name).trim()!==""){const b=t.param_name,E=t.operator||"equals",k=t.value||"",x=E.replace(/_/g," ").replace(/\b\w/g,P=>P.toUpperCase()),I=["exists","not_exists"].includes(E)?"":`<li class="notifal-rule-target-item"><span class="notifal-rule-target-title">Value: ${k}</span></li>`;return`
                    <div class="notifal-rule-details-content">
                        <div class="notifal-rule-details-header">
                            <span class="notifal-rule-details-title">URL parameter: ${b} (${x})</span>
                        </div>
                        <ul class="notifal-rule-targets-list" role="list" aria-label="URL parameter rule">
                            <li class="notifal-rule-target-item"><span class="notifal-rule-target-title">Parameter: ${b}</span></li>
                            <li class="notifal-rule-target-item"><span class="notifal-rule-target-title">Condition: ${x}</span></li>
                            ${I}
                        </ul>
                    </div>
                `}if(!t.keywords||t.keywords.length===0)return"";const e=t.keywords.map(b=>`
                <li class="notifal-rule-target-item">
                    <span class="notifal-rule-target-title" title="URL keyword: ${b.trim()}">${b.trim()}</span>
                </li>
            `).join("");return`
                <div class="notifal-rule-details-content">
                    <div class="notifal-rule-details-header">
                        <span class="notifal-rule-details-title">URL Keywords (${t.mode?t.mode.charAt(0).toUpperCase()+t.mode.slice(1):"Contains"}):</span>
                    </div>
                    <ul class="notifal-rule-targets-list" role="list" aria-label="URL keywords for matching">
                        ${e}
                    </ul>
                </div>
            `;case"users":return t.user_type!=="logged_in"||!t.limit_by_roles||!t.roles||t.roles.length===0?"":`
                <div class="notifal-rule-details-content">
                    <div class="notifal-rule-details-header">
                        <span class="notifal-rule-details-title">Selected User Roles:</span>
                    </div>
                    <ul class="notifal-rule-targets-list" role="list" aria-label="Selected user roles">
                        ${t.roles.map(b=>`
                <li class="notifal-rule-target-item">
                    <span class="notifal-rule-target-title" title="User role: ${b}">${b}</span>
                </li>
            `).join("")}
                    </ul>
                </div>
            `;case"post_type":return wt(o,t);case"categories":const i=t.post_types_visibility||"specific",_=t.post_types||[],m=t.targets||[];if(i==="all")return"";let f="";if(_.length>0){const b=_.map(k=>ge(k)).join(", "),E=t.post_types_visibility==="exclude"?"All Except":"Only";f+=`
                    <div class="notifal-rule-details-content">
                        <div class="notifal-rule-details-header">
                            <span class="notifal-rule-details-title">Post Types: ${E} (${_.length}): ${b}</span>
                        </div>
                    </div>
                `}if(t.mode!=="all"&&m.length>0){const b=t.mode==="exclude"?"All Categories Except":"Only Specific Categories",E=m.map(k=>`
                    <li class="notifal-rule-target-item" data-id="${k}">
                        <span class="notifal-loading-spinner"></span>
                        <span class="notifal-loading-text">Loading category information...</span>
                    </li>
                `).join("");f+=`
                    <div class="notifal-rule-details-content">
                        <div class="notifal-rule-details-header">
                            <span class="notifal-rule-details-title">Categories: ${b} (${m.length})</span>
                        </div>
                        <ul class="notifal-rule-targets-list">${E}</ul>
                    </div>
                `}return f;default:return!t.targets||t.targets.length===0?"":`
                <div class="notifal-rule-details-content">
                    <ul class="notifal-rule-targets-list">
                        ${t.targets.map(b=>`
                <li class="notifal-rule-target-item" data-id="${b}">
                    <span class="notifal-loading-spinner"></span>
                    <span class="notifal-loading-text">Loading page information...</span>
                </li>
            `).join("")}
                    </ul>
                </div>
            `}};function wt(o,t){const e=t.visibility||"all",a=t.post_types||[],n=t.items_visibility||"all",i=t.post_items||[];if(e==="all")return"";let _="";if(a.length>0){const m=a.map(f=>ge(f)).join(", ");_+=`
            <div class="notifal-rule-details-content">
                <div class="notifal-rule-details-header">
                    <span class="notifal-rule-details-title">Post Types (${a.length}): ${m}</span>
                </div>
            </div>
        `}if(n!=="all"&&i.length>0){const m=n==="exclude"?"All Items Except":"Only Specific Items",f=i.map(h=>`
            <li class="notifal-rule-target-item" data-id="${h}">
                <span class="notifal-loading-spinner"></span>
                <span class="notifal-loading-text">Loading page information...</span>
            </li>
        `).join("");_+=`
            <div class="notifal-rule-details-content">
                <div class="notifal-rule-details-header">
                    <span class="notifal-rule-details-title">Items: ${m} (${i.length})</span>
                </div>
                <ul class="notifal-rule-targets-list">${f}</ul>
            </div>
        `}return _}function qe(o){const t=JSON.parse(o.dataset.ruleData||"{}"),e=o.dataset.type||"";let a=[],n="",i="";if(e==="post_type"?(a=t.post_items||[],n="notifal_get_post_titles",i="post_ids"):e==="categories"?(a=t.targets||[],n="notifal_get_term_titles",i="term_ids"):(a=t.targets||[],n="notifal_get_post_titles",i="post_ids"),a.length===0)return;const _=o.querySelectorAll(".notifal-rule-target-item");if(_.length===0)return;const m=Array.from(_).map(k=>k.dataset.id).join(","),f=new URL(NotifalOnPageAjax.ajax_url);f.searchParams.append("action",n);const h=NotifalOnPageAjax.nonce?.search||"";f.searchParams.append("nonce",h),f.searchParams.append(i,m);const b=new AbortController,E=setTimeout(()=>b.abort(),1e4);fetch(f,{signal:b.signal}).then(k=>{if(clearTimeout(E),!k.ok)throw new Error(`HTTP error! status: ${k.status}`);return k.json()}).then(k=>{let x=Array.isArray(k)?k:k&&k.success&&Array.isArray(k.data)?k.data:[];_.forEach(I=>{const P=parseInt(I.dataset.id);let F=x.find(N=>N.id===P);if(F||(F=x.find(N=>String(N.id)===String(P))),F||(F=x.find(N=>parseInt(N.id)===P)),F)if(e==="categories")I.innerHTML=`
                            <span class="notifal-rule-target-title">${F.title}</span>
                        `;else{const N=F.url||Tt(F.id,F.type);I.innerHTML=`
                            <a href="${N}" target="_blank" class="notifal-rule-target-link" title="View ${F.title} on frontend">
                                <span class="notifal-rule-target-title">${F.title}</span>
                                <span class="notifal-rule-target-icon">
                                    <span class="notifal-icon notifal-icon-eye size-12"></span>
                                </span>
                            </a>
                        `}else{const N=e==="categories"?"Category":"Page";I.innerHTML=`
                        <span class="notifal-rule-target-error">
                            <span class="notifal-rule-target-id">${N} ID: ${P}</span>
                            <span class="notifal-rule-target-status">(not found)</span>
                        </span>
                    `}})}).catch(k=>{_.forEach(x=>{const I=x.dataset.id,P=e==="categories"?"Category":"Page",F=k.name==="AbortError"?"timeout":"error loading";x.innerHTML=`
                    <span class="notifal-rule-target-error">
                        <span class="notifal-rule-target-id">${P} ID: ${I}</span>
                        <span class="notifal-rule-target-status">(${F})</span>
                        <button class="notifal-retry-load" onclick="window.fetchRuleTargetTitles && window.fetchRuleTargetTitles(document.querySelector('[data-id=\\'${I}\\']').closest('.notifal-rule-row'))" title="Retry loading">
                            <span class="notifal-icon notifal-icon-arrow-repeat size-12"></span>
                        </button>
                    </span>
                `})})}function Tt(o,t){return typeof notifalFrontendUrl<"u"&&notifalFrontendUrl?notifalFrontendUrl.replace("{post_id}",o).replace("{post_type}",t):`${window.location.origin}/?p=${o}`}function He(){const o=document.querySelector(".notifal-add-display-rule"),t=document.getElementById("notifal-display-rule-list"),e=document.getElementById("notifal-display-rules-summary");o?.addEventListener("click",()=>{const n=document.querySelector('[name="display_rule_type"]').value,i=document.querySelector(`.notifal-display-${n}`),_=ut(n,i),m=De(n,_);if(!m.isValid){NotifalUtils.showMessage(m.message,"error");return}const f=["pages","posts","products"].includes(n)?"post_type":n,h=window.notifalGenerateRuleSummary(f,_),b=t.querySelector(`[data-type="${f}"]`);if(b){const I=b.querySelector(".notifal-rule-details"),P=b.querySelector(".notifal-rule-toggle");I&&!I.classList.contains("notifal-hidden")&&(I.classList.add("notifal-hidden"),P&&(P.textContent=NotifalOnPageStrings?.show_details||"Show Details",P.setAttribute("aria-label","Show Details"),P.setAttribute("title","Show Details"))),b.querySelector(".notifal-rule-label").innerHTML=h,b.dataset.ruleData=JSON.stringify(_);const F=window.notifalGenerateRuleDetails(f,_),N=b.querySelector(".notifal-rule-content");if(F){P?(P.style.display="inline-block",P.textContent=NotifalOnPageStrings?.show_details||"Show Details"):N.innerHTML+='<button class="notifal-rule-toggle" aria-label="Show Details" title="Show Details">Show Details</button>';let U=b.querySelector(".notifal-rule-details");U||(U=document.createElement("div"),U.className="notifal-rule-details notifal-hidden",b.appendChild(U)),U.innerHTML=F}else{const U=N.querySelector(".notifal-rule-toggle");U&&(U.style.display="none");const $=b.querySelector(".notifal-rule-details");$&&$.remove()}if(f==="url_match"&&_.keywords&&_.keywords.length>0){const U=window.notifalGenerateRuleDetails(f,_),$=b.querySelector(".notifal-rule-content");if(U){P?(P.style.display="inline-block",P.textContent=NotifalOnPageStrings?.show_details||"Show Details"):$.innerHTML+='<button class="notifal-rule-toggle" aria-label="Show Details" title="Show Details">Show Details</button>';let O=b.querySelector(".notifal-rule-details");O||(O=document.createElement("div"),O.className="notifal-rule-details notifal-hidden",b.appendChild(O)),O.innerHTML=U}else{const O=$.querySelector(".notifal-rule-toggle");O&&(O.style.display="none");const G=b.querySelector(".notifal-rule-details");G&&G.remove()}}else if(f==="users"&&_.user_type==="logged_in"&&_.limit_by_roles&&_.roles&&_.roles.length>0){const U=window.notifalGenerateRuleDetails(f,_),$=b.querySelector(".notifal-rule-content");if(U){P?(P.style.display="inline-block",P.textContent=NotifalOnPageStrings?.show_details||"Show Details"):$.innerHTML+='<button class="notifal-rule-toggle" aria-label="Show Details" title="Show Details">Show Details</button>';let O=b.querySelector(".notifal-rule-details");O||(O=document.createElement("div"),O.className="notifal-rule-details notifal-hidden",b.appendChild(O)),O.innerHTML=U}else{const O=$.querySelector(".notifal-rule-toggle");O&&(O.style.display="none");const G=b.querySelector(".notifal-rule-details");G&&G.remove()}}b.classList.add("notifal-updated"),setTimeout(()=>{b.classList.remove("notifal-updated")},2e3),NotifalUtils.showMessage("Rule updated successfully!","success"),ce();return}const E=document.createElement("div");E.className="notifal-rule-row",E.dataset.type=f,E.dataset.ruleData=JSON.stringify(_);let k=window.notifalGenerateRuleDetails(f,_);E.innerHTML=`
            <div class="notifal-rule-content">
                <span class="notifal-rule-label">${h}</span>
                ${k?'<button class="notifal-rule-toggle" aria-label="Show Details" title="Show Details">Show Details</button>':""}
            </div>
            ${k?`<div class="notifal-rule-details notifal-hidden">${k}</div>`:""}
            <button class="notifal-remove-rule" aria-label="Remove Rule" title="Remove Rule">
                <span class="notifal-icon notifal-icon-x-circle size-16"></span>
            </button>
        `,t.appendChild(E),E.classList.add("notifal-new-rule"),setTimeout(()=>{E.classList.remove("notifal-new-rule")},2e3);const x=document.querySelector(".notifal-display-rules-fields");x&&x.classList.contains("notifal-hidden")&&x.classList.remove("notifal-hidden"),setTimeout(()=>{ce();const I=document.getElementById("rule_combination_logic")?.value||"OR";Se(I,t.children.length)},0),qt(n,i),NotifalUtils.showMessage("Rule added successfully!","success"),setTimeout(()=>{e.classList.contains("notifal-hidden")&&t.children.length>0&&(e.classList.remove("notifal-hidden"),e.style.display="block",e.style.visibility="visible",e.style.opacity="1")},100)})}function qt(o,t){switch(o){case"url_match":{const F=t?.closest(".notifal-display-url_match")||document.querySelector(".notifal-display-url_match");if(F){const N=F.querySelector('[name="url_match_target"]'),U=F.querySelector('input[name="target_url_keywords"]'),$=F.querySelector('input[name="target_url_param_name"]'),O=F.querySelector('[name="target_url_param_operator"]'),G=F.querySelector('input[name="target_url_param_value"]');N&&(N.value="url"),U&&(U.value=""),$&&($.value=""),O&&(O.value="equals"),G&&(G.value=""),F.querySelector(".notifal-url-match-url-mode")?.classList.remove("notifal-hidden"),F.querySelector(".notifal-url-match-param-mode")?.classList.add("notifal-hidden")}break}case"users":const e=t?.querySelector('[name="target_user_roles[]"]');e&&Array.from(e.options).forEach(F=>F.selected=!1);const a=t?.querySelector('[name="target_user_type"]'),n=t?.querySelector('[name="limit_by_roles"]'),i=t?.querySelector(".notifal-field-wrapper:last-child");a&&(a.value="guest"),n&&(n.checked=!1);const _=n?.closest(".notifal-field-wrapper");_&&_.classList.add("notifal-hidden"),i&&i.classList.add("notifal-hidden");break;case"categories":const m=t.querySelector('[name="target_categories_mode"]');m&&(m.value="exclude");const f=t.querySelector('[name="target_categories_post_types_visibility"]');f&&(f.value="specific",f.dispatchEvent(new Event("change")));const h=t.querySelector(".notifal-ajax-search-selected");if(h){h.querySelectorAll(".notifal-selected-item").forEach(U=>U.remove());const N=["post"];window.NotifalOnPageConfig&&window.NotifalOnPageConfig.isWooCommerceActive&&N.push("product"),N.forEach(U=>{const $=document.createElement("div");$.className="notifal-selected-item",$.dataset.id=U,$.innerHTML=`
                        <span class="notifal-selected-label">${ge(U)} (${U})</span>
                        <input type="hidden" name="target_categories_post_types[]" value="${U}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const O=$.querySelector(".notifal-remove-selected");O&&O.addEventListener("click",()=>{$.remove()}),h.appendChild($)})}const b=t.querySelector('[data-name="target_categories"]');b&&b.querySelectorAll(".notifal-selected-item").forEach(N=>N.remove());break;case"post_type":const E=t.querySelector('[name="target_post_type_visibility"]');E&&(E.value="all",E.dispatchEvent(new Event("change")));const k=t.querySelector('[data-name="target_post_types[]"]');k&&k.querySelectorAll(".notifal-selected-item").forEach(N=>N.remove());const x=t.querySelector('[name="target_post_items_visibility"]');x&&(x.value="all",x.dispatchEvent(new Event("change")));const I=t.querySelector('[data-name="target_post_items[]"]');I&&I.querySelectorAll(".notifal-selected-item").forEach(N=>N.remove());break;default:const P=t?.querySelector(".notifal-ajax-search-selected");P&&(P.innerHTML="")}}function ze(){const o=document.getElementById("notifal-display-rule-list");document.getElementById("notifal-display-rules-summary"),o?.addEventListener("click",t=>{const e=t.target.closest(".notifal-remove-rule");if(e){const a=e.closest(".notifal-rule-row");a&&(a.classList.add("notifal-removing"),setTimeout(()=>{a.remove(),ce();const n=document.getElementById("rule_combination_logic")?.value||"OR";Se(n,o.children.length),NotifalUtils.showMessage("Rule removed successfully!","success")},400))}if(t.target.classList.contains("notifal-rule-toggle")){const a=t.target.closest(".notifal-rule-row"),n=a.querySelector(".notifal-rule-details"),i=t.target;n&&(n.classList.contains("notifal-hidden")?(n.classList.remove("notifal-hidden"),i.textContent=NotifalOnPageStrings?.hide_details||"Hide Details",i.setAttribute("aria-label","Hide Details"),i.setAttribute("title","Hide Details"),n.querySelectorAll(".notifal-loading-spinner").length>0&&setTimeout(()=>{qe(a)},150)):(n.classList.add("notifal-hidden"),i.textContent=NotifalOnPageStrings?.show_details||"Show Details",i.setAttribute("aria-label","Show Details"),i.setAttribute("title","Show Details")))}})}function We(){document.getElementById("notifal-show-rule-form")?.addEventListener("click",()=>{document.getElementById("notifal-empty-rules-message")?.classList.add("notifal-hidden"),document.querySelector(".notifal-display-rules-fields")?.classList.remove("notifal-hidden")});const o=document.getElementById("target_user_type"),t=document.getElementById("limit_by_roles"),e=document.querySelector(".notifal-display-users .notifal-field-wrapper:last-child"),a=()=>{const n=o?.value==="logged_in",i=t?.checked,_=t?.closest(".notifal-field-wrapper");_&&_.classList.toggle("notifal-hidden",!n),e&&e.classList.toggle("notifal-hidden",!(n&&i))};o?.addEventListener("change",a),t?.addEventListener("change",a),a()}function Ge(){const o=document.getElementById("rule_combination_logic");o?.addEventListener("change",()=>{const t=o.value,e=document.getElementById("notifal-display-rule-list");let a=document.querySelector('input[name="rule_combination_logic"]');a||(a=document.createElement("input"),a.type="hidden",a.name="rule_combination_logic",document.querySelector(".notifal-display-rules-settings")?.appendChild(a)),a.value=t,Se(t,e.children.length);const n=t==="AND"?"ALL rules must match":"ANY rule can match";NotifalUtils.showMessage(`Rule logic changed: ${n}`,"info")})}function Se(o,t){document.getElementById("rule_combination_logic");const e=document.getElementById("notifal-rule-combination-logic");e&&t>1&&(e.style.display="block",e.className=`notifal-rule-combination-logic notifal-mb-16 notifal-logic-${o.toLowerCase()}`)}function Je(){const o=document.getElementById("notifal-display-rule-list"),t=document.getElementById("notifal-display-rules-summary"),e=document.querySelector('input[name="display_rules_data"]'),a=document.querySelector('input[name="rule_combination_logic"]');if(e&&e.value)try{const n=JSON.parse(e.value);if(!n||Array.isArray(n)||typeof n!="object"){e.value="",Ue(t,o),ce();return}const i=a?.value||"OR";Object.entries(n).forEach(([m,f])=>{const h=["pages","posts","products"].includes(m)?"post_type":m;let b=f;["pages","posts","products"].includes(m)&&(b={visibility:f.visibility||"all",post_types:f.post_types||[m],items_visibility:f.items_visibility||"all",post_items:f.post_items||[]});const E=window.notifalGenerateRuleSummary(h,b),k=document.createElement("div");k.className="notifal-rule-row",k.dataset.type=h,k.dataset.ruleData=JSON.stringify(b);let x=notifalGenerateRuleDetails(h,b);k.innerHTML=`
                    <div class="notifal-rule-content">
                        <span class="notifal-rule-label">${E}</span>
                        ${x?'<button class="notifal-rule-toggle" aria-label="Show Details" title="Show Details">Show Details</button>':""}
                    </div>
                    ${x?`<div class="notifal-rule-details notifal-hidden">${x}</div>`:""}
                    <button class="notifal-remove-rule" aria-label="Remove Rule" title="Remove Rule">
                        <span class="notifal-icon notifal-icon-x-circle size-16"></span>
                    </button>
                `;const I=k.querySelector(".notifal-rule-content");I&&(I.style.cursor="pointer",I.addEventListener("click",P=>{P.target.closest(".notifal-rule-toggle")||(Le(h,b),NotifalUtils.showMessage("Rule loaded for editing. You can now modify the settings.","success"))})),o.appendChild(k)}),Ue(t,o),Se(i,Object.keys(n).length);const _=document.getElementById("rule_combination_logic");_&&(_.value=i),ce()}catch(n){console.error("Notifal: Error loading existing rules:",n)}}function Ye(){const o=document.getElementById("notifal-display-rule-list");if(!o)return;const t={};let a=document.getElementById("rule_combination_logic")?.value||"OR";const n=document.querySelector('input[name="rule_combination_logic"]');n&&n.value&&(a=n.value);const i=o?.querySelectorAll(".notifal-rule-row");i?.forEach((f,h)=>{const b=f.dataset.type,E=f.dataset.ruleData;if(b&&E)try{const k=JSON.parse(E);t[b]=k}catch(k){console.error("Notifal: Error parsing rule data for type:",b,k)}});let _=document.querySelector('input[name="display_rules_data"]');if(!_){_=document.createElement("input"),_.type="hidden",_.name="display_rules_data";const f=document.querySelector(".notifal-display-rules-settings");f&&f.appendChild(_)}if(_.value=JSON.stringify(t),(i?.length||0)>1){let f=document.querySelector('input[name="rule_combination_logic"]');if(!f){f=document.createElement("input"),f.type="hidden",f.name="rule_combination_logic";const h=document.querySelector(".notifal-display-rules-settings");h&&h.appendChild(f)}f.value=a}else{const f=document.querySelector('input[name="rule_combination_logic"]');f&&f.remove()}}function Xe(){const o=document.getElementById("notifal-display-rule-list");if(!o)return{isValid:!0};const t=o.querySelectorAll(".notifal-rule-row");if(t.length===0)return{isValid:!0};for(const e of t){const a=e.dataset.type,n=e.dataset.ruleData;if(a&&n)try{const i=JSON.parse(n),_=De(a,i);if(!_.isValid)return _}catch(i){return console.error("Notifal: Error parsing rule data for validation:",i),{isValid:!1,message:NotifalOnPageStrings.generic_error||"Error validating display rules."}}}return{isValid:!0}}function Ke(){ce()}function Qe(){ce(),setTimeout(()=>{ce()},50)}function Ze(){const o=document.getElementById("notifal-display-rule-list");if(!o)return;new MutationObserver(e=>{let a=!1;e.forEach(n=>{n.type==="childList"&&(a=!0)}),a&&setTimeout(()=>{ce()},10)}).observe(o,{childList:!0,subtree:!0})}function et(){const o=document.querySelector('[name="target_post_type_visibility"]'),t=document.querySelector(".notifal-post-type-selection"),e=document.querySelector(".notifal-post-items-visibility"),a=document.querySelector(".notifal-post-items-selection");if(!o)return;const n=()=>{const i=o.value;t&&(i==="all"?(t.classList.add("notifal-hidden"),e&&e.classList.add("notifal-hidden"),a&&a.classList.add("notifal-hidden")):(t.classList.remove("notifal-hidden"),e&&e.classList.remove("notifal-hidden")))};n(),o.addEventListener("change",n)}function tt(){const o=document.querySelector('[name="target_categories_post_types_visibility"]'),t=document.querySelector(".notifal-categories-post-type-selection"),e=document.querySelector(".notifal-categories-selection");if(!o)return;const a=()=>{const n=o.value;t&&(n==="all"?(t.classList.add("notifal-hidden"),e&&e.classList.add("notifal-hidden")):(t.classList.remove("notifal-hidden"),e&&e.classList.remove("notifal-hidden")))};a(),o.addEventListener("change",a)}function at(){const o=document.querySelector('[name="target_post_items_visibility"]'),t=document.querySelector(".notifal-post-items-selection");if(!o||!t)return;const e=()=>{o.value==="all"?t.classList.add("notifal-hidden"):t.classList.remove("notifal-hidden")};e(),o.addEventListener("change",e)}function it(){const o=document.querySelector('[name="display_rule_type"]');if(!o)return;const t=o.value;if(document.querySelectorAll(".notifal-display-condition-section").forEach(a=>a.classList.add("notifal-hidden")),["pages","posts","products"].includes(t)){const a=document.querySelector(".notifal-display-post_type");if(a){a.classList.remove("notifal-hidden");const n=typeof window<"u"&&window.notifalConfigureQuickSelectorSettings?window.notifalConfigureQuickSelectorSettings:Fe;typeof n=="function"&&n(t,a)}}else if(t==="post_type"){const a=document.querySelector(".notifal-display-post_type");a&&a.classList.remove("notifal-hidden")}else if(t==="categories"){const a=document.querySelector(".notifal-display-categories");if(a){a.classList.remove("notifal-hidden");const n=a.querySelector(".notifal-categories-post-type-selection"),i=a.querySelector(".notifal-categories-selection");n&&n.classList.remove("notifal-hidden"),i&&i.classList.remove("notifal-hidden");const _=a.querySelector(".notifal-ajax-search-selected");if(_&&_.querySelectorAll(".notifal-selected-item").length===0){const f=["post"];window.NotifalOnPageConfig&&window.NotifalOnPageConfig.isWooCommerceActive&&f.push("product"),f.forEach(h=>{const b=document.createElement("div");b.className="notifal-selected-item",b.dataset.id=h,b.innerHTML=`
                            <span class="notifal-selected-label">${ge(h)} (${h})</span>
                            <input type="hidden" name="target_categories_post_types[]" value="${h}" />
                            <button type="button" class="notifal-remove-selected">
                                <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                            </button>
                        `;const E=b.querySelector(".notifal-remove-selected");E&&E.addEventListener("click",()=>{b.remove()}),_.appendChild(b)})}}}else{const a=document.querySelector(`.notifal-display-${t}`);a&&a.classList.remove("notifal-hidden")}}function Le(o,t){const e=document.querySelector('[name="display_rule_type"]');e&&(e.value=o,e.dispatchEvent(new Event("change"))),setTimeout(()=>{const a=document.querySelector(`.notifal-display-${o}`);if(!a){console.warn(`Wrapper not found for type: ${o}`);return}switch(o){case"categories":Lt(a,t);break;case"post_type":ft(a,t);break;case"users":Et(a,t);break;case"url_match":At(a,t);break;case"pages":case"posts":case"products":xt(a,t,o);break;default:Ct(a,t,o);break}},100)}function Lt(o,t){const e=o.querySelector('[name="target_categories_mode"]');e&&t.mode&&(e.value=t.mode);const a=o.querySelector('[name="target_categories_post_types_visibility"]');if(a&&t.post_types_visibility&&(a.value=t.post_types_visibility,setTimeout(()=>{a.dispatchEvent(new Event("change"))},50)),t.post_types&&t.post_types.length>0){const n=o.querySelector('[data-name="target_categories_post_types[]"]');if(n){const i=n.querySelector(".notifal-ajax-search-selected");i&&(i.querySelectorAll(".notifal-selected-item").forEach(m=>m.remove()),t.post_types.forEach(m=>{const f=document.createElement("div");f.className="notifal-selected-item",f.dataset.id=m,f.innerHTML=`
                        <span class="notifal-selected-label">${ge(m)}</span>
                        <input type="hidden" name="target_categories_post_types[]" value="${m}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const h=f.querySelector(".notifal-remove-selected");h&&h.addEventListener("click",()=>{f.remove()}),i.appendChild(f)}))}}if(t.targets&&t.targets.length>0){const n=o.querySelector('[data-name="target_categories"]');if(n){const i=n.querySelector(".notifal-ajax-search-selected");i&&(i.querySelectorAll(".notifal-selected-item").forEach(m=>m.remove()),t.targets.forEach(m=>{const f=document.createElement("div");f.className="notifal-selected-item",f.dataset.id=m,f.innerHTML=`
                        <span class="notifal-loading-spinner"></span>
                        <span class="notifal-loading-text">Loading category information...</span>
                        <input type="hidden" name="target_categories[]" value="${m}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const h=f.querySelector(".notifal-remove-selected");h&&h.addEventListener("click",()=>{f.remove()}),i.appendChild(f)}),setTimeout(()=>{Ne("categories",t.targets,i)},100))}}}function ft(o,t){const e=o.querySelector('[name="target_post_type_visibility"]');if(e&&t.visibility&&(e.value=t.visibility,setTimeout(()=>{e.dispatchEvent(new Event("change"))},50)),t.post_types&&t.post_types.length>0){const n=o.querySelector('[data-name="target_post_types[]"]');if(n){const i=n.querySelector(".notifal-ajax-search-selected");i&&(i.querySelectorAll(".notifal-selected-item").forEach(m=>m.remove()),t.post_types.forEach(m=>{const f=document.createElement("div");f.className="notifal-selected-item",f.dataset.id=m,f.innerHTML=`
                        <span class="notifal-selected-label">${ge(m)}</span>
                        <input type="hidden" name="target_post_types[]" value="${m}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const h=f.querySelector(".notifal-remove-selected");h&&h.addEventListener("click",()=>{f.remove()}),i.appendChild(f)}))}}const a=o.querySelector('[name="target_post_items_visibility"]');if(a&&t.items_visibility&&(a.value=t.items_visibility,setTimeout(()=>{a.dispatchEvent(new Event("change"))},100)),t.post_items&&t.post_items.length>0){const n=o.querySelector('[data-name="target_post_items[]"]');if(n){const i=n.querySelector(".notifal-ajax-search-selected");i&&(i.querySelectorAll(".notifal-selected-item").forEach(m=>m.remove()),t.post_items.forEach(m=>{const f=document.createElement("div");f.className="notifal-selected-item",f.dataset.id=m,f.innerHTML=`
                        <span class="notifal-loading-spinner"></span>
                        <span class="notifal-loading-text">Loading post information...</span>
                        <input type="hidden" name="target_post_items[]" value="${m}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const h=f.querySelector(".notifal-remove-selected");h&&h.addEventListener("click",()=>{f.remove()}),i.appendChild(f)}),setTimeout(()=>{Ne("post_type",t.post_items,i)},150))}}}function Et(o,t){const e=o.querySelector('[name="target_user_type"]');e&&t.user_type&&(e.value=t.user_type,setTimeout(()=>{e.dispatchEvent(new Event("change"))},50));const a=o.querySelector('[name="limit_by_roles"]');if(a&&t.limit_by_roles!==void 0&&(a.checked=t.limit_by_roles,setTimeout(()=>{a.dispatchEvent(new Event("change"))},100)),t.roles&&t.roles.length>0){const n=o.querySelector('[name="target_user_roles[]"]');n&&Array.from(n.options).forEach(i=>{i.selected=t.roles.includes(i.value)})}}function At(o,t){const e=t.param_name&&String(t.param_name).trim()!=="",a=o.querySelector('[name="url_match_target"]'),n=o.querySelector(".notifal-url-match-url-mode"),i=o.querySelector(".notifal-url-match-param-mode");if(a&&(a.value=e?"param":"url",a.dispatchEvent(new Event("change"))),n&&n.classList.toggle("notifal-hidden",e),i&&i.classList.toggle("notifal-hidden",!e),e){const _=o.querySelector('input[name="target_url_param_name"]'),m=o.querySelector('[name="target_url_param_operator"]'),f=o.querySelector('input[name="target_url_param_value"]');_&&t.param_name!==void 0&&(_.value=t.param_name),m&&t.operator&&(m.value=t.operator,m.dispatchEvent(new Event("change"))),f&&t.value!==void 0&&(f.value=t.value)}else{const _=o.querySelector('[name="url_match_mode"]');_&&t.mode&&(_.value=t.mode);const m=o.querySelector('[name="target_url_keywords"]');m&&t.keywords&&t.keywords.length>0&&(m.value=t.keywords.join(", "))}}function xt(o,t,e){const a={visibility:t.visibility||"all",post_types:[e],items_visibility:t.items_visibility||"all",post_items:t.targets||[]};ft(o,a)}function Ct(o,t,e){if(t.targets&&t.targets.length>0){const a=o.querySelector(".notifal-ajax-search-selected");a&&(a.innerHTML="",t.targets.forEach(n=>{const i=document.createElement("div");i.className="notifal-selected-item",i.dataset.id=n,i.innerHTML=`
                    <span class="notifal-loading-spinner"></span>
                    <span class="notifal-loading-text">Loading information...</span>
                    <input type="hidden" name="target_${e}[]" value="${n}" />
                    <button type="button" class="notifal-remove-selected">
                        <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                    </button>
                `;const _=i.querySelector(".notifal-remove-selected");_&&_.addEventListener("click",()=>{i.remove()}),a.appendChild(i)}),setTimeout(()=>{Ne(e,t.targets,a)},100))}}function ot(){try{typeof Re=="function"&&Re(),typeof He=="function"&&He(),typeof ze=="function"&&ze(),typeof We=="function"&&We(),typeof Ge=="function"&&Ge(),typeof et=="function"&&et(),typeof tt=="function"&&tt(),typeof at=="function"&&at(),typeof Je=="function"&&Je(),typeof Ze=="function"&&Ze(),setTimeout(()=>{typeof Ke=="function"&&Ke()},100),setTimeout(()=>{typeof it=="function"&&it()},150),setTimeout(()=>{typeof ce=="function"&&ce()},200),setTimeout(()=>{typeof ce=="function"&&ce()},500),typeof qe=="function"&&(window.fetchRuleTargetTitles=qe),typeof Qe=="function"&&(window.forceRefreshRulesCount=Qe),typeof ce=="function"&&(window.ensureRulesCountIsCorrect=ce),typeof Ye=="function"?window.saveRulesData=Ye:console.error("Notifal: saveRulesData function is not defined!"),typeof Xe=="function"?window.validateDisplayRules=Xe:console.error("Notifal: validateDisplayRules function is not defined!"),typeof Le=="function"?window.populateFormForEditing=Le:console.error("Notifal: populateFormForEditing function is not defined!"),document.addEventListener("click",o=>{if(o.target.classList.contains("notifal-remove-selected")){const t=o.target.closest(".notifal-selected-item");t&&t.remove()}})}catch(o){console.error("Notifal: Error during rules initialization:",o)}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{setTimeout(()=>{ot(),window.notifalRulesReady=!0},100)}):setTimeout(()=>{ot(),window.notifalRulesReady=!0},100);function Ne(o,t,e){if(!t||t.length===0||!e){console.warn("Missing required parameters:",{ids:t,container:e});return}let a="",n="";o==="categories"?(a="notifal_get_term_titles",n="term_ids"):o==="users"?(a="notifal_get_user_titles",n="user_ids"):(a="notifal_get_post_titles",n="post_ids");const i=new FormData;i.append("action",a),i.append("nonce",NotifalOnPageAjax.nonce.search),i.append(n,t.join(",")),fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:i}).then(_=>_.json()).then(_=>{_.success&&_.data?e.querySelectorAll(".notifal-selected-item").forEach(f=>{const h=parseInt(f.dataset.id),b=_.data.find(E=>parseInt(E.id)===h);if(b){const E=e.closest("[data-name]"),k=E?E.dataset.name:"target_"+o;f.innerHTML=`
                        <span class="notifal-selected-label">${b.title}</span>
                        <input type="hidden" name="${k}[]" value="${h}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const x=f.querySelector(".notifal-remove-selected");x&&x.addEventListener("click",()=>{f.remove()})}else{console.warn("Item not found in fetched data:",{itemId:h,data:_.data});const E=e.closest("[data-name]"),k=E?E.dataset.name:"target_"+o;f.innerHTML=`
                        <span class="notifal-selected-label notifal-error">ID ${h} (not found)</span>
                        <input type="hidden" name="${k}[]" value="${h}" />
                        <button type="button" class="notifal-remove-selected">
                            <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                        </button>
                    `;const x=f.querySelector(".notifal-remove-selected");x&&x.addEventListener("click",()=>{f.remove()})}}):console.warn("AJAX response not successful:",_)}).catch(_=>{console.error("Error populating form field with titles:",_),e.querySelectorAll(".notifal-selected-item").forEach(f=>{const h=f.dataset.id,b=e.closest("[data-name]"),E=b?b.dataset.name:"target_"+o;f.innerHTML=`
                <span class="notifal-selected-label notifal-error">ID ${h} (error loading)</span>
                <input type="hidden" name="${E}[]" value="${h}" />
                <button type="button" class="notifal-remove-selected">
                    <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                </button>
            `;const k=f.querySelector(".notifal-remove-selected");k&&k.addEventListener("click",()=>{f.remove()})})})}function kt(){if(window.NotifalOnPageConfig?.is_pro_active||!1)return;const t=document.querySelector('[name="display_rule_type"]');t&&t.addEventListener("change",function(i){const m=i.target.options[i.target.selectedIndex].dataset.proFeature;if(m)return i.preventDefault(),we(m),i.target.value="post_type",i.target.dispatchEvent(new Event("change")),!1});const e=document.querySelector("#rule_combination_logic");e&&e.addEventListener("change",function(i){if(i.target.value==="AND")return i.preventDefault(),we("multiple_rules_and_logic"),i.target.value="OR",!1});let a=0;const n=document.querySelector(".notifal-add-display-rule");n&&n.addEventListener("click",function(i){if(a++,a>1)return i.preventDefault(),we("multiple_rules"),a--,!1})}function we(o){const e={categories:"Category targeting is a Pro feature. Upgrade to target specific categories and taxonomies.",url_match:"URL targeting is a Pro feature. Upgrade to show notifications based on URL patterns.",users:"User targeting is a Pro feature. Upgrade to target specific user types and roles.",multiple_rules:"Multiple display rules are a Pro feature. Upgrade to add unlimited rules with AND/OR logic.",multiple_rules_and_logic:"AND logic for multiple rules is a Pro feature. Upgrade to combine rules with advanced logic."}[o]||"This feature requires Notifal Pro.",a=window.NotifalOnPageConfig?.upgrade_url||"https://notifal.com/pricing/?utm_source=wordpress_plugin&utm_medium=plugin&utm_campaign=notifal_pro_upgrade";confirm(e+`

Would you like to upgrade now?`)&&window.open(a,"_blank")}document.addEventListener("DOMContentLoaded",function(){kt()});function Ee(){let o=!1;document.addEventListener("keydown",t=>{t.key==="Control"&&(o=!0,document.body.classList.add("notifal-multi-select-mode"))}),document.addEventListener("keyup",t=>{t.key==="Control"&&(o=!1,document.body.classList.remove("notifal-multi-select-mode"))}),window.addEventListener("blur",()=>{o=!1}),document.querySelectorAll(".notifal-ajax-search-input:not([data-notifal-search-initialized])").forEach(t=>{t.setAttribute("data-notifal-search-initialized","true");const e=t.closest(".notifal-ajax-search"),a=e.querySelector(".ajaxnotifal-ajax-search-loader"),n=e.querySelector(".ajaxnotifal-ajax-search-no-results"),i=e.querySelector(".ajaxnotifal-ajax-search-results"),_=e.querySelector(".notifal-ajax-search-selected"),m=e.querySelector(".notifal-search-wrapper");let f=e.dataset.postType||"page";const h=()=>{f=e.dataset.postType||"page"},b=$=>{const O=document.createElement("div");O.className="notifal-selected-item",O.dataset.id=$.id,O.innerHTML=`
                ${$.title}
                <input type="hidden" name="${e.dataset.name}[]" value="${$.id}" />
                <button type="button" class="notifal-remove-selected">
                    <span class="notifal-icon notifal-icon-x-circle size-12"></span>
                </button>
            `,_.appendChild(O)},E=$=>e.querySelector(`.notifal-selected-item[data-id="${$}"]`)!==null,k=$=>$==="user"?"notifal_search_users":$==="post_type"?e.closest(".notifal-display-categories")?"notifal_search_post_types_for_categories":"notifal_search_post_types":$.startsWith("term_")||$==="any_category"||$.includes("category")||$==="product_cat"?"notifal_search_terms":"notifal_search_posts",x=()=>{const $=e.closest(".notifal-display-post_type");if($){const z=$.querySelector('[data-name="target_post_types[]"]');if(z){const W=Array.from(z.querySelectorAll(".notifal-selected-item")).map(A=>A.dataset.id);if(W.length>0)return W.join(",")}}const O=e.closest(".notifal-display-categories");if(O){const z=O.querySelector('[data-name="target_categories_post_types[]"]');if(z){const W=Array.from(z.querySelectorAll(".notifal-selected-item")).map(A=>A.dataset.id);if(W.length>0)return W.join(",")}}if(e.closest(".notifal-content-source-settings, .notifal-step-content, .notifal-restriction-card")){if(window.detectedCustomPostTypes&&window.detectedCustomPostTypes.length>0)return window.detectedCustomPostTypes.join(",");if(window.customPostTypeFilterManager&&window.customPostTypeFilterManager.detectedPostTypes)return window.customPostTypeFilterManager.detectedPostTypes.join(",")}return window.detectedCustomPostTypes&&window.detectedCustomPostTypes.length>0?window.detectedCustomPostTypes.join(","):""};let I=null;t.addEventListener("input",()=>{clearTimeout(I);const $=t.value.trim();i.innerHTML="",i.style.display="none",n.style.display="none",a.style.display="none",!($.length<2)&&(h(),I=setTimeout(()=>{a.style.display="block",i.innerHTML="",i.style.display="none",n.style.display="none";const O=k(f),G=new URL(NotifalOnPageAjax.ajax_url);if(G.searchParams.append("action",O),G.searchParams.append("nonce",NotifalOnPageAjax.nonce.search),G.searchParams.append("post_type",f),G.searchParams.append("s",$),O==="notifal_search_posts"){const z=x();z&&(G.searchParams.set("post_type","any"),G.searchParams.append("context_post_types",z))}if(O==="notifal_search_terms"&&(f==="custom_posttype_category"||!f.includes("cat")&&!f.includes("tag")&&f!=="category"&&f!=="product_cat")){const z=x();z&&G.searchParams.append("context_post_types",z)}fetch(G).then(z=>z.json()).then(z=>{if(a.style.display="none",!Array.isArray(z)||!z.length){n.style.display="block";return}i.innerHTML="",i.style.display="block",z.forEach(W=>{if(W.type==="product"&&W.variations&&W.variations.length>0){const A=document.createElement("div");A.className="notifal-search-result notifal-product-with-variations",A.dataset.id=W.id,E(W.id)&&A.classList.add("notifal-selected");let d="";W.image&&(d=`<img class="notifal-search-thumb" src="${W.image}" alt="" />`),A.innerHTML=`
                                    <div class="notifal-search-info notifal-flex notifal-gap-10 notifal-align-center">
                                        <span class="notifal-search-id">#${W.id}</span>
                                        ${d}
                                        <span class="notifal-search-title">${W.title}</span>
                                        <span class="notifal-variation-count">(${W.variations.length} variations)</span>
                                        ${E(W.id)?'<span class="notifal-selected-indicator"><span class="notifal-icon notifal-icon-check size-14"></span></span>':""}
                                    </div>
                                `,A.addEventListener("click",()=>{if(E(W.id)&&o){e.querySelector(`.notifal-selected-item[data-id="${W.id}"]`)?.remove(),A.classList.remove("notifal-selected"),A.querySelector(".notifal-selected-indicator")?.remove();return}if(!E(W.id)){b(W),A.classList.add("notifal-selected");const T=A.querySelector(".notifal-search-info");if(T&&!T.querySelector(".notifal-selected-indicator")){const q=document.createElement("span");q.className="notifal-selected-indicator",q.innerHTML='<span class="notifal-icon notifal-icon-check size-14"></span>',T.appendChild(q)}}o||(t.value="",i.innerHTML="",i.style.display="none")}),i.appendChild(A),W.variations.forEach(T=>{const q=document.createElement("div");q.className="notifal-search-result notifal-product-variation",q.dataset.id=T.id,E(T.id)&&q.classList.add("notifal-selected"),q.innerHTML=`
                                        <div class="notifal-search-info notifal-flex notifal-gap-10 notifal-align-center">
                                            <span class="notifal-search-id notifal-variation-id">#${T.id}</span>
                                            <span class="notifal-variation-indicator">└─</span>
                                            <span class="notifal-search-title">${T.title}</span>
                                            ${E(T.id)?'<span class="notifal-selected-indicator"><span class="notifal-icon notifal-icon-check size-14"></span></span>':""}
                                        </div>
                                    `,q.addEventListener("click",()=>{if(E(T.id)&&o){e.querySelector(`.notifal-selected-item[data-id="${T.id}"]`)?.remove(),q.classList.remove("notifal-selected"),q.querySelector(".notifal-selected-indicator")?.remove();return}if(!E(T.id)){b(T),q.classList.add("notifal-selected");const g=q.querySelector(".notifal-search-info");if(g&&!g.querySelector(".notifal-selected-indicator")){const L=document.createElement("span");L.className="notifal-selected-indicator",L.innerHTML='<span class="notifal-icon notifal-icon-check size-14"></span>',g.appendChild(L)}}o||(t.value="",i.innerHTML="",i.style.display="none")}),i.appendChild(q)})}else{const A=document.createElement("div");A.className="notifal-search-result",A.dataset.id=W.id,E(W.id)&&A.classList.add("notifal-selected");let d="";W.image?d=`<img class="notifal-search-thumb" src="${W.image}" alt="" />`:f==="user"&&(d='<div class="notifal-search-thumb notifal-user-avatar">👤</div>'),A.innerHTML=`
                                    <div class="notifal-search-info notifal-flex notifal-gap-10 notifal-align-center">
                                        <span class="notifal-search-id">#${W.id}</span>
                                        ${d}
                                        <span class="notifal-search-title">${W.title}</span>
                                        ${E(W.id)?'<span class="notifal-selected-indicator"><span class="notifal-icon notifal-icon-check size-14"></span></span>':""}
                                    </div>
                                `,A.addEventListener("click",()=>{if(E(W.id)&&o){e.querySelector(`.notifal-selected-item[data-id="${W.id}"]`)?.remove(),A.classList.remove("notifal-selected"),A.querySelector(".notifal-selected-indicator")?.remove();return}if(!E(W.id)){b(W),A.classList.add("notifal-selected");const T=A.querySelector(".notifal-search-info");if(T&&!T.querySelector(".notifal-selected-indicator")){const q=document.createElement("span");q.className="notifal-selected-indicator",q.innerHTML='<span class="notifal-icon notifal-icon-check size-14"></span>',T.appendChild(q)}}o||(t.value="",i.innerHTML="",i.style.display="none")}),i.appendChild(A)}})}).catch(z=>{})},300))}),m?.addEventListener("click",$=>{if($.target.classList.contains("notifal-remove-selected")){const O=$.target.closest(".notifal-selected-item"),G=O?.dataset.id;if(O?.remove(),i.style.display!=="none"){const z=i.querySelector(`[data-id="${G}"]`);z&&(z.classList.remove("notifal-selected"),z.querySelector(".notifal-selected-indicator")?.remove())}}});let P=!1;m?.addEventListener("focusin",()=>{F()}),t.addEventListener("focus",()=>{document.addEventListener("keydown",N),document.addEventListener("keyup",U),F()});const F=()=>{if(document.activeElement!==t)return;let $=m.querySelector(".notifal-multi-select-hint");$||($=document.createElement("div"),$.className="notifal-multi-select-hint",m.appendChild($)),o?($.innerHTML="<small>"+(NotifalOnPageStrings?.multi_select_active||"💡 Multi-select is now active! Hold Ctrl to continue selecting")+"</small>",$.style.color="var(--notifal-primary)",$.style.fontWeight="500",P||(t.classList.add("notifal-multi-select-active"),t.placeholder="Multi-select mode active - click items to select multiple",P=!0)):($.innerHTML="<small>"+(NotifalOnPageStrings?.hold_ctrl_select||"💡 Hold <kbd>Ctrl</kbd> to select multiple items")+"</small>",$.style.color="#666",$.style.fontWeight="normal",P&&(t.classList.remove("notifal-multi-select-active"),t.placeholder="Type at least 3 letters to start searching.",P=!1))},N=$=>{$.key==="Control"&&F()},U=$=>{$.key==="Control"&&F()};document.addEventListener("keydown",N),document.addEventListener("keyup",U),t.addEventListener("blur",()=>{const $=m.querySelector(".notifal-multi-select-hint");$&&$.remove(),P&&(t.classList.remove("notifal-multi-select-active"),t.placeholder="Type at least 3 letters to start searching.",P=!1),document.removeEventListener("keydown",N),document.removeEventListener("keyup",U)}),_&&_.addEventListener("click",$=>{const O=$.target.closest(".notifal-remove-selected");if(O){const G=O.closest(".notifal-selected-item");G&&G.remove()}}),document.addEventListener("click",$=>{e.contains($.target)||(i.innerHTML="",i.style.display="none",a.style.display="none",n.style.display="none")})})}window.initSearchBoxes=Ee;document.readyState==="loading"?document.addEventListener("DOMContentLoaded",Ee):Ee();function Ae(o,t,e){t.forEach(a=>{a.classList.toggle("active",a.dataset.tab===o)}),e.forEach(a=>{a.classList.toggle("active",a.id==="tab-"+o)})}function Te(o,t){const e=window.location.hash.replace("#","")||"general";Ae(e,o,t)}function xe(){const o=document.querySelectorAll(".notifal-tabs button"),t=document.querySelectorAll(".notifal-tab-panel");!o.length||!t.length||(o.forEach(e=>{e.addEventListener("click",()=>{window.location.hash=e.dataset.tab})}),window.addEventListener("hashchange",()=>{Te(o,t)}),Te(o,t),window.activateTab=Ae,window.handleHashChange=Te,window.initTabs=xe,window.switchToTab=function(e){const a=document.querySelectorAll(".notifal-tabs button"),n=document.querySelectorAll(".notifal-tab-panel");Ae(e,a,n),window.location.hash=e})}function nt(){document.querySelectorAll(".notifal-enable-link").forEach(t=>{t.addEventListener("click",e=>{e.preventDefault();const a=t.dataset.tab;a&&window.switchToTab&&window.switchToTab(a)})})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{xe(),nt()}):(xe(),nt());function Ce(){const o=document.querySelector('[name="content_source_type"]');o?st(o):Ie('[name="content_source_type"]',st)}function Ie(o,t){const e=document.querySelector(o);if(e){t(e);return}const a=new MutationObserver(i=>{i.forEach(_=>{if(_.type==="childList"){const m=document.querySelector(o);m&&(a.disconnect(),t(m))}})});a.observe(document.body,{childList:!0,subtree:!0});const n=setInterval(()=>{const i=document.querySelector(o);i&&(clearInterval(n),a.disconnect(),t(i))},100);setTimeout(()=>{clearInterval(n),a.disconnect()},5e3)}function st(o){o.addEventListener("change",e=>{const a=e.target.value;lt(a),be(a),ke(a)});const t=o.value;t&&(lt(t),be(t),ke(t))}function ke(o){const t=document.querySelector('button[data-tab="content-source"]');if(t)if(o==="static"){t.style.display="none",t.classList.add("notifal-hidden");const e=document.getElementById("tab-content-source");if(e&&t&&t.classList.contains("active")&&!e.classList.contains("notifal-hidden")){const a=document.querySelectorAll(".notifal-tabs button"),n=document.querySelectorAll(".notifal-tab-panel");a.forEach(m=>m.classList.remove("active")),n.forEach(m=>m.classList.remove("active"));const i=document.querySelector('button[data-tab="general"]'),_=document.getElementById("tab-general");i&&_&&(i.classList.add("active"),_.classList.add("active"),window.location.hash!=="#general"&&history.replaceState(null,null,"#general"))}}else t.style.display="",t.classList.remove("notifal-hidden")}function Me(){typeof window.handleTemplateSelection=="function"&&window.handleTemplateSelection(),typeof window.handleTemplateSelection=="function"&&(document.querySelectorAll('input[name="notifal_template_id"]').forEach(t=>{const e=t.cloneNode(!0);t.parentNode.replaceChild(e,t)}),window.handleTemplateSelection()),typeof window.NotifalTemplateSelection<"u"&&window.NotifalTemplateSelection.handleTemplateSelection&&window.NotifalTemplateSelection.handleTemplateSelection()}async function be(o){const t=document.querySelectorAll(".notifal-template-group");if(!t.length)return;t.forEach(a=>{const n=a.querySelector(".notifal-template-grid");n&&(n.innerHTML=`
                <div class="notifal-loading-state">
                    <div class="notifal-loading-spinner"></div>
                    <p>${NotifalOnPageStrings?.filtering_templates||"Filtering templates..."}</p>
                </div>
            `)});const e=document.querySelector(".notifal-no-templates-found");e&&(e.style.display="none",e.classList.add("notifal-hidden"));try{const a=["elementor","block-editor"];for(const n of a)await pt(n,o);Me(),typeof window.NotifalTemplateSelection<"u"&&window.NotifalTemplateSelection.restoreSavedTemplateSelection&&setTimeout(()=>{window.NotifalTemplateSelection.restoreSavedTemplateSelection()},100)}catch(a){console.error("Template filtering error:",a),t.forEach(n=>{const i=n.querySelector(".notifal-template-grid");i&&(i.innerHTML=`
                    <div class="notifal-error-state">
                        <p>${NotifalOnPageStrings?.error_filtering_templates||"Error filtering templates. Please try again."}</p>
                    </div>
                `)})}}async function pt(o,t){const e=document.querySelector(`.notifal-template-group[data-builder="${o}"]`);if(!e)return;const a=e.querySelector(".notifal-template-grid"),n=e.querySelector(".notifal-load-more");if(a)try{let i=window.notifalGetSelectedTemplateId();if(i||typeof sessionStorage<"u"&&(i=sessionStorage.getItem("notifal_selected_template_id")),!i){const h=document.querySelector('input[name="template_id"]');i=h?h.value:null}const _=new FormData;_.append("action","notifal_get_filtered_templates"),_.append("nonce",NotifalOnPageAjax.nonce.get_filtered_templates||NotifalOnPageAjax.nonce.search),_.append("builder",o),_.append("content_source_type",t),_.append("offset",0),_.append("limit",6),i&&i!=="0"&&_.append("selected_template_id",i);const m=await fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:_});if(!m.ok)throw new Error(`HTTP error! status: ${m.status}`);const f=await m.json();if(f.success){a.innerHTML=f.data.html,n&&(n.dataset.contentSourceType=t,f.data.has_more?(n.style.display="block",n.classList.remove("notifal-hidden"),n.dataset.currentOffset="6"):(n.style.display="none",n.classList.add("notifal-hidden"))),f.data.total_count===0?(e.style.display="none",e.classList.add("notifal-hidden")):(e.style.display="block",e.classList.remove("notifal-hidden"));const h=document.querySelector(".notifal-no-templates-found");h&&(Array.from(document.querySelectorAll(".notifal-template-group[data-builder]")).every(k=>k.style.display==="none"||k.classList.contains("notifal-hidden"))?(h.style.display="block",h.classList.remove("notifal-hidden")):(h.style.display="none",h.classList.add("notifal-hidden")));const b=e.querySelector(".notifal-section-title");if(b){const E=b.dataset.originalTitle||b.textContent;b.dataset.originalTitle=E;const k=t==="static"?"Static":"Dynamic";b.textContent=`${E} (${k})`}}else a.innerHTML=`
                <div class="notifal-error-state">
                    <p>${f.data?.message||"Failed to load filtered templates."}</p>
                </div>
            `}catch(i){console.error("Error in loadFilteredTemplates:",i),a.innerHTML=`
            <div class="notifal-error-state">
                <p>${NotifalOnPageStrings?.error_loading_templates||"Error loading templates."}</p>
            </div>
        `}}function Pe(o=!1){document.querySelectorAll(".notifal-load-more[data-builder]").forEach(e=>{if(e.hasAttribute("data-notifal-filtered-load-more-initialized")&&!o)return;let a=e;if(o&&e.hasAttribute("data-notifal-filtered-load-more-initialized")){const h=e.cloneNode(!0);e.parentNode.replaceChild(h,e),a=h}const n=document.querySelector('[name="content_source_type"]');n&&!a.dataset.contentSourceType&&(a.dataset.contentSourceType=n.value),a.setAttribute("data-notifal-filtered-load-more-initialized","true");const i=a.dataset.builder,m=a.closest(".notifal-template-group").querySelector(".notifal-template-grid");let f=parseInt(a.dataset.currentOffset)||6;a.addEventListener("click",async function(){if(a.classList.contains("loading"))return;const h=document.querySelector('[name="content_source_type"]'),b=a.dataset.contentSourceType||h?.value||"dynamic",E=h&&a.dataset.contentSourceType,k=a.textContent;a.textContent=NotifalOnPageStrings?.loading||"Loading...",a.classList.add("loading","notifal-disable"),a.setAttribute("disabled","disabled");try{let x=new FormData;if(E){let F=window.notifalGetSelectedTemplateId();if(F||typeof sessionStorage<"u"&&(F=sessionStorage.getItem("notifal_selected_template_id")),!F){const N=document.querySelector('input[name="template_id"]');F=N?N.value:null}x.append("action","notifal_get_filtered_templates"),x.append("nonce",NotifalOnPageAjax.nonce.get_filtered_templates||NotifalOnPageAjax.nonce.search),x.append("builder",i),x.append("content_source_type",b),x.append("offset",f),x.append("limit",6),F&&F!=="0"&&x.append("selected_template_id",F)}else x.append("action","notifal_load_more_templates"),x.append("nonce",NotifalOnPageAjax.nonce.load_more_templates),x.append("builder",i),x.append("offset",f);const I=await fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:x});if(!I.ok)throw new Error(`HTTP error! status: ${I.status}`);const P=await I.json();if(P.success){m.insertAdjacentHTML("beforeend",P.data.html),f=P.data.next_offset,a.dataset.currentOffset=f,P.data.has_more||(a.style.display="none",a.classList.add("notifal-hidden")),E&&(Me(),typeof window.NotifalTemplateSelection<"u"&&window.NotifalTemplateSelection.restoreSavedTemplateSelection&&setTimeout(()=>{window.NotifalTemplateSelection.restoreSavedTemplateSelection()},100));const F=new CustomEvent("notifal:templates:loaded",{detail:{builder:i,loadedCount:P.data.loaded_count,totalCount:P.data.total_count,hasMore:P.data.has_more,filtered:E}});document.dispatchEvent(F)}else{const F=P.data?.message||"Failed to load templates.";window.notifalShowToast("error",F)}}catch{window.notifalShowToast("error","Network error occurred while loading templates.")}finally{a.textContent=k,a.classList.remove("loading","notifal-disable"),a.removeAttribute("disabled")}})})}window.notifalGetSelectedTemplateId=function(){const o=document.querySelector('input[name="notifal_template_id"]:checked');return o?o.value:null};function lt(o){document.querySelectorAll(".notifal-load-more[data-builder]").forEach(e=>{e.dataset.contentSourceType=o,e.dataset.currentOffset="6"})}window.notifalShowToast=function(o,t){typeof window.NotifalUtils<"u"&&window.NotifalUtils.showMessage?window.NotifalUtils.showMessage(t,o,5e3):typeof NotifalUtils<"u"&&NotifalUtils.showMessage?NotifalUtils.showMessage(t,o,5e3):console.warn(`Toast message (${o}): ${t}`)};function he(){const o=document.getElementById("notifal-template-refresh-btn");o&&(o.hasAttribute("data-notifal-refresh-initialized")||(o.setAttribute("data-notifal-refresh-initialized","true"),o.addEventListener("click",async function(){if(o.classList.contains("loading"))return;const t=document.querySelector('[name="content_source_type"]'),e=t?t.value:"dynamic",a=o.textContent;o.textContent=NotifalOnPageStrings?.refreshing_templates||"Refreshing...",o.classList.add("loading");try{await be(e),Pe(!0),window.notifalShowToast("success",NotifalOnPageStrings?.templates_refreshed||"Templates refreshed successfully")}catch(n){console.error("Template refresh error:",n),window.notifalShowToast("error",NotifalOnPageStrings?.error_refreshing_templates||"Error refreshing templates. Please try again.")}finally{o.textContent=a,o.classList.remove("loading")}})))}function rt(){const o=document.querySelector('[name="content_source_type"]'),t=document.querySelectorAll(".notifal-template-group"),e=document.getElementById("notifal-template-refresh-btn");o&&t.length>0?(Ce(),Pe(),he()):Pt(['[name="content_source_type"]',".notifal-template-group"],()=>{Ce(),Pe(),he()}),e?he():Ie("#notifal-template-refresh-btn",he)}function Pt(o,t){const e=new Set,a=()=>{e.size===o.length&&t()};o.forEach(n=>{Ie(n,i=>{e.add(n),a()})})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",rt):rt();typeof window<"u"&&(window.NotifalTemplateFilter={init:Ce,filterTemplatesByContentType:be,loadFilteredTemplates:pt,reinitializeContentSourceAnalysis:Me,updateContentSourceTabVisibility:ke});function $e(){if(document.querySelector('[name="content_source_type"]'))return;document.querySelectorAll(".notifal-load-more[data-builder]").forEach(e=>{if(e.hasAttribute("data-notifal-load-more-initialized"))return;e.setAttribute("data-notifal-load-more-initialized","true");const a=e.dataset.builder,n=e.closest(".notifal-template-group").querySelector(".notifal-template-grid");let i=6;e.addEventListener("click",async function(){if(e.classList.contains("loading"))return;const _=e.textContent;e.textContent=NotifalOnPageStrings?.loading||"Loading...",e.classList.add("loading","notifal-disable"),e.setAttribute("disabled","disabled");try{const m=new FormData;m.append("action","notifal_load_more_templates"),m.append("nonce",NotifalOnPageAjax.nonce.load_more_templates),m.append("builder",a),m.append("offset",i);const f=await fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:m});if(!f.ok)throw new Error(`HTTP error! status: ${f.status}`);const h=await f.json();if(h.success){n.insertAdjacentHTML("beforeend",h.data.html),i=h.data.next_offset;const b=new CustomEvent("notifal:templates:loaded",{detail:{builder:a,loadedCount:h.data.loaded_count,totalCount:h.data.total_count,hasMore:h.data.has_more}});document.dispatchEvent(b),h.data.has_more||setTimeout(()=>{const E=document.querySelectorAll('.notifal-load-more[data-builder="'+a+'"]');E.length!==0&&E.forEach(k=>{k.style.display="none",k.style.visibility="hidden",k.classList.add("notifal-hidden"),k.setAttribute("hidden","hidden"),setTimeout(()=>{(k.style.display!=="none"||k.offsetParent!==null)&&k.remove()},200)})},100)}else{const b=h.data?.message||"Failed to load templates.";typeof window.notifalShowToast=="function"?window.notifalShowToast("error",b):ct("error",b)}}catch{const f="Network error occurred while loading templates.";typeof window.notifalShowToast=="function"?window.notifalShowToast("error",f):ct("error",f)}finally{e.textContent=_,e.classList.remove("loading","notifal-disable"),e.removeAttribute("disabled")}})})}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",$e):$e();function ct(o,t){typeof window.NotifalUtils<"u"&&window.NotifalUtils.showMessage?window.NotifalUtils.showMessage(t,o,5e3):typeof NotifalUtils<"u"&&NotifalUtils.showMessage?NotifalUtils.showMessage(t,o,5e3):console.warn(`Toast message (${o}): ${t}`)}typeof window<"u"&&(window.NotifalTemplateLoadMore={init:$e});(function(){function o(x,I={}){const P=typeof NotifalOnPageStrings<"u"&&NotifalOnPageStrings[x]?NotifalOnPageStrings[x]:x;return Object.keys(I).reduce((F,N)=>F.replace(`{${N}}`,I[N]),P)}function t(){e(),a(),m(),setTimeout(()=>{_()},500)}function e(){const x=document.querySelectorAll('input[name="notifal_template_id"]');x.length&&x.forEach(I=>{I.addEventListener("change",P=>{P.target.checked&&(n(P.target.value),i(P.target.value),f("success",o("template_selected")),typeof window.handleTemplateSelection=="function"&&window.handleTemplateSelection())})})}function a(){const x=new MutationObserver(P=>{P.forEach(F=>{F.type==="childList"&&F.addedNodes.forEach(N=>{if(N.nodeType===Node.ELEMENT_NODE){const U=N.querySelectorAll?N.querySelectorAll('input[name="notifal_template_id"]'):[];U.length>0&&U.forEach($=>{$.addEventListener("change",O=>{O.target.checked&&(n(O.target.value),i(O.target.value),f("success",o("template_selected")),typeof window.handleTemplateSelection=="function"&&window.handleTemplateSelection())})})}})})});document.querySelectorAll(".notifal-template-grid").forEach(P=>{x.observe(P,{childList:!0,subtree:!0})})}function n(x){let I=document.querySelector('input[name="template_id"]');if(!I){I=document.createElement("input"),I.type="hidden",I.name="template_id";const P=document.querySelector(".notifal-notification-form");P&&P.appendChild(I)}I.value=x,typeof sessionStorage<"u"&&sessionStorage.setItem("notifal_selected_template_id",x),document.dispatchEvent(new CustomEvent("notifal:template:selected",{detail:{templateId:x}}))}function i(x){const I=new FormData;I.append("action","notifal_get_template_content"),I.append("nonce",NotifalOnPageAjax.nonce.get_template_content||NotifalOnPageAjax.nonce.search),I.append("template_id",x),fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:I}).then(P=>P.json()).then(P=>{if(P.success&&P.data.content){let F=document.querySelector('input[name="template_content"]');if(!F){F=document.createElement("input"),F.type="hidden",F.name="template_content";const N=document.querySelector(".notifal-notification-form");N&&N.appendChild(F)}F.value=P.data.content}}).catch(P=>{console.warn("Error fetching template content:",P)})}function _(){let x=null;const I=document.querySelector('input[name="template_id"]')?.value;if(I&&I!=="0"&&(x=I),!x&&typeof sessionStorage<"u"){const P=sessionStorage.getItem("notifal_selected_template_id");P&&(x=P)}if(x){const P=document.querySelector(`input[name="notifal_template_id"][value="${x}"]`);P&&(P.checked=!0,n(x),i(x),typeof sessionStorage<"u"&&sessionStorage.setItem("notifal_selected_template_id",x))}}function m(){document.addEventListener("notifal:notification:saved",()=>{h()}),window.addEventListener("beforeunload",()=>{window.location.href.includes("action=edit")&&h()})}function f(x,I){typeof window.NotifalUtils<"u"&&window.NotifalUtils.showMessage?window.NotifalUtils.showMessage(I,x,2e3):typeof NotifalUtils<"u"&&NotifalUtils.showMessage&&NotifalUtils.showMessage(I,x,2e3)}function h(){typeof sessionStorage<"u"&&sessionStorage.removeItem("notifal_selected_template_id")}function b(){const x=document.querySelector('input[name="notifal_template_id"]:checked');return x?x.value:null}function E(){return b()!==null}function k(x=!0){return b()?!0:(x&&f("error","Please select a template before saving."),!1)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{setTimeout(t,100)}):setTimeout(t,100),typeof window<"u"&&(window.NotifalTemplateSelection={init:t,handleTemplateSelection:e,updateHiddenTemplateFields:n,updateTemplateContentField:i,restoreSavedTemplateSelection:_,clearSavedTemplateSelection:h,getSelectedTemplateId:b,isTemplateSelected:E,validateTemplateSelection:k})})();(function(){function o(){document.querySelectorAll(".notifal-template-iframe").forEach(t),i()}function t(m){if(m.hasAttribute("data-notifal-loader-initialized"))return;m.setAttribute("data-notifal-loader-initialized","true");const f=m.closest(".notifal-template-card-parent");if(!f)return;const h=f.querySelector(".notifal-iframe-loading");h&&(m.addEventListener("load",function(){e(m,h)}),m.addEventListener("error",function(){a(m,h)}),setTimeout(()=>{h&&h.style.display!=="none"&&n(m,h)},1e4))}function e(m,f){try{setTimeout(()=>{f.style.display="none",f.classList.add("notifal-hidden"),m.style.opacity="1",m.style.visibility="visible",m.classList.add("notifal-iframe-loaded"),m.dispatchEvent(new CustomEvent("notifal:iframe:loaded",{bubbles:!0,detail:{iframe:m}}))},300)}catch(h){console.warn("Error handling iframe load:",h),f.style.display="none"}}function a(m,f){f.innerHTML=`
            <div style="text-align: center; color: #dc3232; font-size: 12px;">
                <i class="dashicons dashicons-warning" style="font-size: 20px; margin-bottom: 5px;"></i>
                <div>Failed to load preview</div>
                <div style="margin-top: 5px;">
                    <a href="${m.src}" target="_blank" style="color: #0073aa; text-decoration: none; font-size: 11px;">
                        View in new tab
                    </a>
                </div>
            </div>
        `,m.dispatchEvent(new CustomEvent("notifal:iframe:error",{bubbles:!0,detail:{iframe:m}}))}function n(m,f){try{if(m.contentDocument&&m.contentDocument.readyState==="complete"){e(m,f);return}}catch{}f.innerHTML=`
            <div style="text-align: center; color: #ff8800; font-size: 12px;">
                <i class="dashicons dashicons-clock" style="font-size: 20px; margin-bottom: 5px;"></i>
                <div>Loading timeout</div>
                <div style="margin-top: 5px;">
                    <a href="${m.src}" target="_blank" style="color: #0073aa; text-decoration: none; font-size: 11px;">
                        View in new tab
                    </a>
                </div>
            </div>
        `,m.dispatchEvent(new CustomEvent("notifal:iframe:timeout",{bubbles:!0,detail:{iframe:m}}))}function i(){const m=new MutationObserver(b=>{b.forEach(E=>{E.type==="childList"&&E.addedNodes.forEach(k=>{if(k.nodeType===Node.ELEMENT_NODE){const x=k.querySelectorAll?k.querySelectorAll(".notifal-template-iframe"):[];k.classList&&k.classList.contains("notifal-template-iframe")&&x.push(k),x.forEach(t)}})})});document.querySelectorAll(".notifal-template-grid").forEach(b=>{m.observe(b,{childList:!0,subtree:!0})});const h=document.querySelector(".notifal-template-selector");h&&m.observe(h,{childList:!0,subtree:!0})}function _(){document.querySelectorAll(".notifal-template-iframe").forEach(f=>{f.removeAttribute("data-notifal-loader-initialized"),t(f)})}document.addEventListener("notifal:templates:loaded",()=>{setTimeout(_,100)}),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",o):o(),typeof window<"u"&&(window.NotifalIframeLoader={init:o,setupIframeLoadHandler:t,recheckAllIframes:_})})();try{class o{constructor(e,a){this.filterType=e,this.container=a,this.conditions=[],this.nextId=1,this.isProActive=this.checkProStatus(),this.init()}init(){this.bindEvents(),this.updateUI()}checkProStatus(){return typeof window.NotifalContentSourceProStatus<"u"?window.NotifalContentSourceProStatus:typeof window.is_notifal_pro_active=="function"?window.is_notifal_pro_active():(document.querySelectorAll(".notifal-pro-badge").length>0,!1)}getPopulatedValuesAttribute(e,a){return!e.data||!e.data[a]||!Array.isArray(e.data[a])||e.data[a].length===0?"":`data-populated-values="${JSON.stringify(e.data[a]).replace(/"/g,"&quot;")}"`}bindEvents(){const e=this.container.querySelector(".notifal-add-filter-btn"),a=this.container.querySelector(".notifal-logic-selector select");e&&e.addEventListener("click",()=>this.addFilter()),a&&a.addEventListener("change",()=>this.updateLogic())}addFilter(){if(!this.isProActive&&this.conditions.length>=1){NotifalUtils.showMessage(NotifalOnPageStrings?.multiple_filters_pro||"Multiple filters are available in Notifal Pro. Upgrade to add more conditions.","info");return}const e=this.conditions.map(m=>m.type).filter(m=>this.getSingularFilterTypes().includes(m)),a=this.getFilterTypeOptions(),n=a.find(m=>!e.includes(m.value)),i=n?n.value:a.length>0?a[0].value:"all",_={id:this.nextId++,type:i,data:{},enabled:!0};this.conditions.push(_),this.renderCondition(_),this.updateUI(),this.updateAllTypeSelectors()}removeFilter(e){this.conditions=this.conditions.filter(a=>a.id!==e),this.updateUI(),this.updateAllTypeSelectors()}updateFilter(e,a){const n=this.conditions.find(i=>i.id===e);n&&(Object.assign(n,a),this.updateUI())}renderCondition(e){const a=this.container.querySelector(".notifal-filter-conditions"),n=this.createConditionElement(e);a.appendChild(n),typeof initSearchBoxes=="function"&&initSearchBoxes()}createConditionElement(e){const a=document.createElement("div");a.className="notifal-filter-condition",a.dataset.conditionId=e.id;const n=this.createTypeSelector(e),i=this.createDataFields(e),_=this.createRemoveButton(e.id);return a.innerHTML=`
                <div class="notifal-condition-header">
                    <div class="notifal-condition-type">
                        ${n}
                    </div>
                    <div class="notifal-condition-actions">
                        ${_}
                    </div>
                </div>
                <div class="notifal-condition-data">
                    ${i}
                </div>
            `,this.bindConditionEvents(a,e),a}createTypeSelector(e){const n=this.getFilterTypeOptions().map(i=>`<option value="${i.value}" ${i.value===e.type?"selected":""}>${i.label}</option>`).join("");return`
                <select class="notifal-condition-type-select notifal-select small" data-condition-id="${e.id}">
                    ${n}
                </select>
            `}createDataFields(e){switch(this.filterType){case"product":return this.createProductDataFields(e);case"order":return this.createOrderDataFields(e);case"user":return this.createUserDataFields(e);case"post":return this.createPostDataFields(e);case"page":return this.createPageDataFields(e);case"comment":return this.createCommentDataFields(e);case"custom_posttype":return this.createCustomPostTypeDataFields(e);default:return""}}createProductDataFields(e){switch(e.type){case"categories":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Product Categories</label>
                            <div class="notifal-ajax-search" data-name="product_categories" data-post-type="product_cat" data-condition-id="${e.id}" data-field="categories" ${this.getPopulatedValuesAttribute(e,"categories")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"specific":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Specific Products</label>
                            <div class="notifal-ajax-search" data-name="specific_products" data-post-type="product" data-condition-id="${e.id}" data-field="products" ${this.getPopulatedValuesAttribute(e,"products")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"sale":return'<div class="notifal-info-message">Shows only products that are currently on sale.</div>';case"featured":return'<div class="notifal-info-message">Shows only featured products.</div>';case"date_range":const a=new Date().toISOString().split("T")[0],n=new Date;n.setFullYear(n.getFullYear()+1);const i=n.toISOString().split("T")[0];return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Type</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="date_type">
                                <option value="publish" ${e.data.date_type==="publish"?"selected":""}>Publish Date</option>
                                <option value="modified" ${e.data.date_type==="modified"?"selected":""}>Modified Date</option>
                            </select>
                        </div>
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Range</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="range">
                                <option value="last_24h" ${e.data.range==="last_24h"?"selected":""}>Last 24 Hours</option>
                                <option value="last_7d" ${e.data.range==="last_7d"?"selected":""}>Last 7 Days</option>
                                <option value="last_30d" ${e.data.range==="last_30d"?"selected":""}>Last 30 Days</option>
                                <option value="last_90d" ${e.data.range==="last_90d"?"selected":""}>Last 90 Days</option>
                                <option value="custom" ${e.data.range==="custom"?"selected":""}>Custom Range</option>
                            </select>
                            <div class="notifal-custom-date-range ${e.data.range==="custom"?"":"notifal-hidden"}">
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">Start Date</label>
                                    <input type="date" class="notifal-input" 
                                           data-condition-id="${e.id}" data-field="start_date" 
                                           value="${e.data.start_date||""}"
                                           max="${a}" />
                                </div>
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">End Date</label>
                                    <input type="date" class="notifal-input" 
                                           data-condition-id="${e.id}" data-field="end_date" 
                                           value="${e.data.end_date||""}"
                                           max="${i}" />
                                </div>
                            </div>
                        </div>
                    `;case"custom_meta":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="_regular_price>100" 
                                   data-condition-id="${e.id}" data-field="custom_filter" 
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Use operators: >, <, =, !=, >=, <=. Combine with && (AND) or || (OR).
                            </div>
                            
                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="product">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available Product Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All products will be included.</div>'}}createOrderDataFields(e){switch(e.type){case"status":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Order Statuses</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="statuses">
                                <option value="completed" ${(e.data.statuses||[]).includes("completed")?"selected":""}>Completed</option>
                                <option value="processing" ${(e.data.statuses||[]).includes("processing")?"selected":""}>Processing</option>
                                <option value="on-hold" ${(e.data.statuses||[]).includes("on-hold")?"selected":""}>On Hold</option>
                                <option value="pending" ${(e.data.statuses||[]).includes("pending")?"selected":""}>Pending</option>
                                <option value="cancelled" ${(e.data.statuses||[]).includes("cancelled")?"selected":""}>Cancelled</option>
                                <option value="refunded" ${(e.data.statuses||[]).includes("refunded")?"selected":""}>Refunded</option>
                            </select>
                        </div>
                    `;case"date_range":const a=new Date().toISOString().split("T")[0],n=new Date;n.setFullYear(n.getFullYear()+1);const i=n.toISOString().split("T")[0];return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Range</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="range">
                                <option value="last_24h" ${e.data.range==="last_24h"?"selected":""}>Last 24 Hours</option>
                                <option value="last_7d" ${e.data.range==="last_7d"?"selected":""}>Last 7 Days</option>
                                <option value="last_30d" ${e.data.range==="last_30d"?"selected":""}>Last 30 Days</option>
                                <option value="last_90d" ${e.data.range==="last_90d"?"selected":""}>Last 90 Days</option>
                                <option value="custom" ${e.data.range==="custom"?"selected":""}>Custom Range</option>
                            </select>
                            <div class="notifal-custom-date-range ${e.data.range==="custom"?"":"notifal-hidden"}">
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">Start Date</label>
                                    <input type="date" class="notifal-input" 
                                           data-condition-id="${e.id}" data-field="start_date" 
                                           value="${e.data.start_date||""}"
                                           max="${a}" />
                                </div>
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">End Date</label>
                                    <input type="date" class="notifal-input" 
                                           data-condition-id="${e.id}" data-field="end_date" 
                                           value="${e.data.end_date||""}"
                                           max="${i}" />
                                </div>
                            </div>
                        </div>
                    `;case"products":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Orders Containing Products</label>
                            <div class="notifal-ajax-search" data-name="order_products" data-post-type="product" data-condition-id="${e.id}" data-field="products" ${this.getPopulatedValuesAttribute(e,"products")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"custom_filter":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="_order_total>200" 
                                   data-condition-id="${e.id}" data-field="custom_filter" 
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Use operators: >, <, =, !=, >=, <=. Combine with && (AND) or || (OR).
                            </div>
                            
                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="order">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available Order Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All orders will be included.</div>'}}createUserDataFields(e){switch(e.type){case"roles":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">User Roles</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="roles">
                                <option value="administrator" ${(e.data.roles||[]).includes("administrator")?"selected":""}>Administrator</option>
                                <option value="editor" ${(e.data.roles||[]).includes("editor")?"selected":""}>Editor</option>
                                <option value="author" ${(e.data.roles||[]).includes("author")?"selected":""}>Author</option>
                                <option value="contributor" ${(e.data.roles||[]).includes("contributor")?"selected":""}>Contributor</option>
                                <option value="subscriber" ${(e.data.roles||[]).includes("subscriber")?"selected":""}>Subscriber</option>
                                <option value="customer" ${(e.data.roles||[]).includes("customer")?"selected":""}>Customer</option>
                            </select>
                        </div>
                    `;case"specific":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Specific Users</label>
                            <div class="notifal-ajax-search" data-name="specific_users" data-post-type="user" data-condition-id="${e.id}" data-field="users" ${this.getPopulatedValuesAttribute(e,"users")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"custom_filter":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="meta_key:value"
                                   data-condition-id="${e.id}" data-field="custom_filter"
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Enter a custom meta key and value (e.g., user_type:premium) to filter users.
                            </div>

                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="user">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available User Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All users will be included.</div>'}}createPostDataFields(e){switch(e.type){case"categories":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Post Categories</label>
                            <div class="notifal-ajax-search" data-name="post_categories" data-post-type="category" data-condition-id="${e.id}" data-field="categories" ${this.getPopulatedValuesAttribute(e,"categories")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"specific":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Specific Posts</label>
                            <div class="notifal-ajax-search" data-name="specific_posts" data-post-type="post" data-condition-id="${e.id}" data-field="posts" ${this.getPopulatedValuesAttribute(e,"posts")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"author":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Post Authors</label>
                            <div class="notifal-ajax-search" data-name="post_authors" data-post-type="user" data-condition-id="${e.id}" data-field="authors" ${this.getPopulatedValuesAttribute(e,"authors")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"date_range":const a=new Date().toISOString().split("T")[0],n=new Date;n.setFullYear(n.getFullYear()+1);const i=n.toISOString().split("T")[0];return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Type</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="date_type">
                                <option value="publish" ${e.data.date_type==="publish"?"selected":""}>Publish Date</option>
                                <option value="modified" ${e.data.date_type==="modified"?"selected":""}>Modified Date</option>
                            </select>
                        </div>
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Range</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="range">
                                <option value="last_24h" ${e.data.range==="last_24h"?"selected":""}>Last 24 Hours</option>
                                <option value="last_7d" ${e.data.range==="last_7d"?"selected":""}>Last 7 Days</option>
                                <option value="last_30d" ${e.data.range==="last_30d"?"selected":""}>Last 30 Days</option>
                                <option value="last_90d" ${e.data.range==="last_90d"?"selected":""}>Last 90 Days</option>
                                <option value="custom" ${e.data.range==="custom"?"selected":""}>Custom Range</option>
                            </select>
                            <div class="notifal-custom-date-range ${e.data.range==="custom"?"":"notifal-hidden"}">
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">Start Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="start_date"
                                           value="${e.data.start_date||""}"
                                           max="${a}" />
                                </div>
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">End Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="end_date"
                                           value="${e.data.end_date||""}"
                                           max="${i}" />
                                </div>
                            </div>
                        </div>
                    `;case"custom_meta":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="_thumbnail_id>0"
                                   data-condition-id="${e.id}" data-field="custom_filter"
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Use operators: >, <, =, !=, >=, <=. Combine with && (AND) or || (OR).
                            </div>

                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="post">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available Post Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All posts will be included.</div>'}}createPageDataFields(e){switch(e.type){case"specific":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Specific Pages</label>
                            <div class="notifal-ajax-search" data-name="specific_pages" data-post-type="page" data-condition-id="${e.id}" data-field="pages" ${this.getPopulatedValuesAttribute(e,"pages")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"status":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Page Status</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="statuses">
                                <option value="publish" ${(e.data.statuses||[]).includes("publish")?"selected":""}>Published</option>
                                <option value="draft" ${(e.data.statuses||[]).includes("draft")?"selected":""}>Draft</option>
                                <option value="pending" ${(e.data.statuses||[]).includes("pending")?"selected":""}>Pending</option>
                                <option value="private" ${(e.data.statuses||[]).includes("private")?"selected":""}>Private</option>
                                <option value="trash" ${(e.data.statuses||[]).includes("trash")?"selected":""}>Trash</option>
                            </select>
                        </div>
                    `;case"author":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Page Authors</label>
                            <div class="notifal-ajax-search" data-name="page_authors" data-post-type="user" data-condition-id="${e.id}" data-field="authors" ${this.getPopulatedValuesAttribute(e,"authors")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"template":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Page Templates</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="templates">
                                <option value="default" ${(e.data.templates||[]).includes("default")?"selected":""}>Default Template</option>
                                <option value="page-fullwidth.php" ${(e.data.templates||[]).includes("page-fullwidth.php")?"selected":""}>Full Width</option>
                                <option value="page-sidebar.php" ${(e.data.templates||[]).includes("page-sidebar.php")?"selected":""}>With Sidebar</option>
                            </select>
                            <div class="notifal-field-description">
                                Note: Available templates depend on your theme.
                            </div>
                        </div>
                    `;case"date_range":const a=new Date().toISOString().split("T")[0],n=new Date;n.setFullYear(n.getFullYear()+1);const i=n.toISOString().split("T")[0];return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Type</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="date_type">
                                <option value="publish" ${e.data.date_type==="publish"?"selected":""}>Publish Date</option>
                                <option value="modified" ${e.data.date_type==="modified"?"selected":""}>Modified Date</option>
                            </select>
                        </div>
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Range</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="range">
                                <option value="last_24h" ${e.data.range==="last_24h"?"selected":""}>Last 24 Hours</option>
                                <option value="last_7d" ${e.data.range==="last_7d"?"selected":""}>Last 7 Days</option>
                                <option value="last_30d" ${e.data.range==="last_30d"?"selected":""}>Last 30 Days</option>
                                <option value="last_90d" ${e.data.range==="last_90d"?"selected":""}>Last 90 Days</option>
                                <option value="custom" ${e.data.range==="custom"?"selected":""}>Custom Range</option>
                            </select>
                            <div class="notifal-custom-date-range ${e.data.range==="custom"?"":"notifal-hidden"}">
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">Start Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="start_date"
                                           value="${e.data.start_date||""}"
                                           max="${a}" />
                                </div>
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">End Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="end_date"
                                           value="${e.data.end_date||""}"
                                           max="${i}" />
                                </div>
                            </div>
                        </div>
                    `;case"custom_meta":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="_wp_page_template:page-fullwidth.php"
                                   data-condition-id="${e.id}" data-field="custom_filter"
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Use operators: >, <, =, !=, >=, <=. Combine with && (AND) or || (OR).
                            </div>

                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="page">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available Page Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All pages will be included.</div>'}}createCommentDataFields(e){switch(e.type){case"status":const a=window.NotifalCommentStatuses||{approve:"Approved",hold:"Unapproved",spam:"Spam",trash:"Trash"},n={approve:"approved",hold:"pending",spam:"spam",trash:"trash"},i=Object.entries(a).map(([h,b])=>{const E=n[h]||h,k=(e.data.statuses||[]).includes(E);return`<option value="${E}" ${k?"selected":""}>${b}</option>`}).join("");return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Comment Status</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="statuses">
                                ${i}
                            </select>
                        </div>
                    `;case"post_type":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Post Types</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="post_types">
                                <option value="post" ${(e.data.post_types||[]).includes("post")?"selected":""}>Posts</option>
                                <option value="page" ${(e.data.post_types||[]).includes("page")?"selected":""}>Pages</option>
                                <option value="product" ${(e.data.post_types||[]).includes("product")?"selected":""}>Products</option>
                            </select>
                        </div>
                    `;case"author":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Comment Authors</label>
                            <input type="text" class="notifal-input notifal-author-input" placeholder="Author name, email, or multiple separated by comma"
                                   data-condition-id="${e.id}" data-field="authors"
                                   value="${e.data.authors||""}" />
                            <div class="notifal-field-description">
                                Enter author name(s), email(s), or multiple separated by comma. Leave empty for all authors.
                            </div>
                        </div>
                    `;case"date_range":const _=new Date().toISOString().split("T")[0],m=new Date;m.setFullYear(m.getFullYear()+1);const f=m.toISOString().split("T")[0];return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Range</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="range">
                                <option value="last_24h" ${e.data.range==="last_24h"?"selected":""}>Last 24 Hours</option>
                                <option value="last_7d" ${e.data.range==="last_7d"?"selected":""}>Last 7 Days</option>
                                <option value="last_30d" ${e.data.range==="last_30d"?"selected":""}>Last 30 Days</option>
                                <option value="last_90d" ${e.data.range==="last_90d"?"selected":""}>Last 90 Days</option>
                                <option value="custom" ${e.data.range==="custom"?"selected":""}>Custom Range</option>
                            </select>
                            <div class="notifal-custom-date-range ${e.data.range==="custom"?"":"notifal-hidden"}">
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">Start Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="start_date"
                                           value="${e.data.start_date||""}"
                                           max="${_}" />
                                </div>
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">End Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="end_date"
                                           value="${e.data.end_date||""}"
                                           max="${f}" />
                                </div>
                            </div>
                        </div>
                    `;case"custom_meta":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="rating=5"
                                   data-condition-id="${e.id}" data-field="custom_filter"
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Use operators: >, <, =, !=, >=, <=. Combine with && (AND) or || (OR).
                            </div>

                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="comment">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available Comment Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All comments will be included.</div>'}}createCustomPostTypeDataFields(e){const a=this.detectedPostType||window.primaryCustomPostType||"any",n="custom_posttype_category";switch(e.type){case"categories":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Categories</label>
                            <div class="notifal-ajax-search" data-name="custom_posttype_categories" data-post-type="${n}" data-condition-id="${e.id}" data-field="categories" ${this.getPopulatedValuesAttribute(e,"categories")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                            <div class="notifal-field-description">
                                Note: Available categories depend on the custom post type's taxonomy configuration.
                            </div>
                        </div>
                    `;case"specific":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Specific Items</label>
                            <div class="notifal-ajax-search" data-name="specific_custom_posttypes" data-post-type="${a}" data-condition-id="${e.id}" data-field="items" ${this.getPopulatedValuesAttribute(e,"items")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"status":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Status</label>
                            <select class="notifal-multi-select" multiple data-condition-id="${e.id}" data-field="statuses">
                                <option value="publish" ${(e.data.statuses||[]).includes("publish")?"selected":""}>Published</option>
                                <option value="draft" ${(e.data.statuses||[]).includes("draft")?"selected":""}>Draft</option>
                                <option value="pending" ${(e.data.statuses||[]).includes("pending")?"selected":""}>Pending</option>
                                <option value="private" ${(e.data.statuses||[]).includes("private")?"selected":""}>Private</option>
                                <option value="trash" ${(e.data.statuses||[]).includes("trash")?"selected":""}>Trash</option>
                            </select>
                        </div>
                    `;case"author":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Authors</label>
                            <div class="notifal-ajax-search" data-name="custom_posttype_authors" data-post-type="user" data-condition-id="${e.id}" data-field="authors" ${this.getPopulatedValuesAttribute(e,"authors")}>
                                <div class="notifal-search-wrapper">
                                    <div class="notifal-ajax-search-selected"></div>
                                    <input type="text" class="notifal-ajax-search-input" placeholder="Type at least 3 letters to start searching..." autocomplete="off" />
                                    <div class="ajaxnotifal-ajax-search-loader" style="display: none;">Loading</div>
                                    <div class="ajaxnotifal-ajax-search-no-results" style="display: none;">No results found</div>
                                    <div class="ajaxnotifal-ajax-search-results" style="display: none;"></div>
                                </div>
                            </div>
                        </div>
                    `;case"date_range":const i=new Date().toISOString().split("T")[0],_=new Date;_.setFullYear(_.getFullYear()+1);const m=_.toISOString().split("T")[0];return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Type</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="date_type">
                                <option value="publish" ${e.data.date_type==="publish"?"selected":""}>Publish Date</option>
                                <option value="modified" ${e.data.date_type==="modified"?"selected":""}>Modified Date</option>
                            </select>
                        </div>
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Date Range</label>
                            <select class="notifal-select" data-condition-id="${e.id}" data-field="range">
                                <option value="last_24h" ${e.data.range==="last_24h"?"selected":""}>Last 24 Hours</option>
                                <option value="last_7d" ${e.data.range==="last_7d"?"selected":""}>Last 7 Days</option>
                                <option value="last_30d" ${e.data.range==="last_30d"?"selected":""}>Last 30 Days</option>
                                <option value="last_90d" ${e.data.range==="last_90d"?"selected":""}>Last 90 Days</option>
                                <option value="custom" ${e.data.range==="custom"?"selected":""}>Custom Range</option>
                            </select>
                            <div class="notifal-custom-date-range ${e.data.range==="custom"?"":"notifal-hidden"}">
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">Start Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="start_date"
                                           value="${e.data.start_date||""}"
                                           max="${i}" />
                                </div>
                                <div class="notifal-date-field">
                                    <label class="notifal-date-label">End Date</label>
                                    <input type="date" class="notifal-input"
                                           data-condition-id="${e.id}" data-field="end_date"
                                           value="${e.data.end_date||""}"
                                           max="${m}" />
                                </div>
                            </div>
                        </div>
                    `;case"custom_meta":return`
                        <div class="notifal-field-wrapper">
                            <label class="notifal-form-label">Custom Meta Filter</label>
                            <input type="text" class="notifal-input" placeholder="_custom_field=value"
                                   data-condition-id="${e.id}" data-field="custom_filter"
                                   value="${e.data.custom_filter||""}" />
                            <div class="notifal-field-description">
                                Use operators: >, <, =, !=, >=, <=. Combine with && (AND) or || (OR).
                            </div>

                        </div>
                        <!-- Available Meta Fields -->
                        <div class="notifal-available-meta-section" data-meta-type="custom_posttype">
                            <div class="notifal-meta-header">
                                <label class="notifal-form-label notifal-meta-toggle" tabindex="0" role="button" aria-expanded="false">
                                    Available Custom Post Type Meta Fields
                                    <span class="notifal-icon notifal-icon-chevron-down notifal-meta-arrow"></span>
                                </label>
                            </div>
                            <div class="notifal-meta-content notifal-hidden">
                                <div class="notifal-meta-search">
                                    <input type="text" class="notifal-meta-search-input" placeholder="Search meta fields..." />
                                </div>
                                <div class="notifal-meta-list">
                                    <div class="notifal-meta-loading">Loading available meta fields...</div>
                                </div>
                            </div>
                        </div>
                    `;default:return'<div class="notifal-info-message">All custom post type items will be included.</div>'}}createRemoveButton(e){return`
                <button type="button" class="notifal-button secondary small notifal-remove-condition-btn" 
                        data-condition-id="${e}">
                    <span class="notifal-icon notifal-icon-trash size-16"></span>
                    Remove
                </button>
            `}bindConditionEvents(e,a){const n=e.querySelector(".notifal-condition-type-select");n&&n.addEventListener("change",m=>{a.type=m.target.value,a.data={},this.rerenderCondition(a),this.updateAllTypeSelectors()});const i=e.querySelector(".notifal-remove-condition-btn");i&&i.addEventListener("click",()=>{e.remove(),this.removeFilter(a.id)}),this.bindDataFieldEvents(e,a),e.querySelectorAll(".notifal-ajax-search").forEach(m=>{const f=m.querySelector(".notifal-ajax-search-selected");if(f){const h=()=>{const E=m.dataset.field;if(!E)return;const k=f.querySelectorAll(".notifal-selected-item"),x=Array.from(k).map(I=>{const P=I.getAttribute("data-id");return P?parseInt(P,10):null}).filter(I=>I!==null);a.data||(a.data={}),a.data[E]=x};h(),new MutationObserver(h).observe(f,{childList:!0})}})}bindDataFieldEvents(e,a){e.querySelectorAll("input[data-condition-id], select[data-condition-id]").forEach(m=>{const f=m.dataset.field;m.addEventListener("change",h=>{if(a.data||(a.data={}),m.multiple)a.data[f]=Array.from(h.target.selectedOptions).map(b=>b.value);else if(a.data[f]=h.target.value,f==="authors"&&m.classList.contains("notifal-author-input")){const b=h.target.value.split(",").map(E=>E.trim()).filter(E=>E.length>0).join(", ");b!==h.target.value&&(h.target.value=b,a.data[f]=b)}if(f==="range"&&h.target.value==="custom"){const b=e.querySelector(".notifal-custom-date-range");b&&b.classList.remove("notifal-hidden")}else if(f==="range"){const b=e.querySelector(".notifal-custom-date-range");b&&b.classList.add("notifal-hidden")}(f==="start_date"||f==="end_date")&&this.validateDateRange(e)})});const i=e.querySelector(".notifal-available-meta-section");i&&typeof window.setupMetaFieldSection=="function"&&window.setupMetaFieldSection(i),e.querySelectorAll(".notifal-ajax-search-wrapper").forEach(m=>{this.initializeAjaxSearch(m,a)})}validateDateRange(e){const a=e.querySelector('[data-field="start_date"]'),n=e.querySelector('[data-field="end_date"]');if(!a||!n)return;const i=new Date(a.value),_=new Date(n.value);a.value&&n.value&&(i>_?n.setCustomValidity("End date must be after start date"):n.setCustomValidity("")),a.value&&(n.min=a.value)}initializeAjaxSearch(e,a){const n=e.getAttribute("data-post-type"),i=e.getAttribute("data-field");e.classList.add("notifal-ajax-search"),e.setAttribute("data-name",`condition_${a.id}_${i}`)}rerenderCondition(e){const a=this.container.querySelector(`[data-condition-id="${e.id}"]`);if(a){const n=this.createConditionElement(e);a.parentNode.replaceChild(n,a),typeof initSearchBoxes=="function"&&initSearchBoxes()}}updateUI(){const e=this.container.querySelector(".notifal-empty-filters-message"),a=this.container.querySelector(".notifal-logic-selector"),n=this.container.querySelector(".notifal-filter-conditions"),i=this.container.querySelector(".notifal-add-filter-btn");this.conditions.length===0?(e&&e.classList.remove("notifal-hidden"),a&&a.classList.add("notifal-hidden"),n&&(n.innerHTML=""),i&&i.classList.remove("notifal-hidden")):(e&&e.classList.add("notifal-hidden"),a&&(this.conditions.length>1?a.classList.remove("notifal-hidden"):a.classList.add("notifal-hidden")),i&&(!this.isProActive&&this.conditions.length>=1?i.classList.add("notifal-hidden"):i.classList.remove("notifal-hidden")))}updateLogic(){const e=this.container.querySelector(".notifal-logic-selector select");e&&(this.logic=e.value)}getSingularFilterTypes(){return{product:["sale","featured","custom_meta","date_range"],order:["status","date_range","products","custom_meta","custom_filter"],user:["roles","registration_date","custom_meta","custom_filter"],post:["date_range","custom_meta"],page:["template","date_range","custom_meta"],comment:["author","date_range","custom_meta"],custom_posttype:["date_range","custom_meta"]}[this.filterType]||[]}updateAllTypeSelectors(){const e=this.conditions.map(i=>i.type),a=this.getSingularFilterTypes();this.container.querySelectorAll(".notifal-filter-condition").forEach(i=>{const _=parseInt(i.dataset.conditionId,10),m=this.conditions.find(h=>h.id===_);if(!m)return;const f=i.querySelector(".notifal-condition-type-select");f&&Array.from(f.options).forEach(h=>{a.includes(h.value)&&e.includes(h.value)&&h.value!==m.type?h.disabled=!0:h.disabled=!1})})}getFilterTypeOptions(){switch(this.filterType){case"product":return[{value:"all",label:"All Products"},{value:"categories",label:"Specific Categories"},{value:"specific",label:"Specific Products"},{value:"sale",label:"Sale Products Only"},{value:"featured",label:"Featured Products Only"},{value:"date_range",label:"Date Range"},{value:"custom_meta",label:"Custom Meta"}];case"order":return[{value:"all",label:"All Orders"},{value:"status",label:"Order Status"},{value:"date_range",label:"Date Range"},{value:"products",label:"Orders with Products"},{value:"custom_filter",label:"Custom Filter"}];case"user":return[{value:"all",label:"All Users"},{value:"roles",label:"User Roles"},{value:"specific",label:"Specific Users"},{value:"registration_date",label:"Registration Date"},{value:"custom_filter",label:"Custom Filter"}];case"post":return[{value:"all",label:"All Posts"},{value:"categories",label:"Specific Categories"},{value:"specific",label:"Specific Posts"},{value:"author",label:"Post Authors"},{value:"date_range",label:"Date Range"},{value:"custom_meta",label:"Custom Meta"}];case"page":return[{value:"all",label:"All Pages"},{value:"specific",label:"Specific Pages"},{value:"status",label:"Page Status"},{value:"author",label:"Page Authors"},{value:"template",label:"Page Template"},{value:"date_range",label:"Date Range"},{value:"custom_meta",label:"Custom Meta"}];case"comment":return[{value:"all",label:"All Comments"},{value:"status",label:"Comment Status"},{value:"post_type",label:"Post Types"},{value:"author",label:"Comment Authors"},{value:"date_range",label:"Date Range"},{value:"custom_meta",label:"Custom Meta"}];case"custom_posttype":return[{value:"all",label:"All Items"},{value:"categories",label:"Specific Categories"},{value:"specific",label:"Specific Items"},{value:"status",label:"Status"},{value:"author",label:"Authors"},{value:"date_range",label:"Date Range"},{value:"custom_meta",label:"Custom Meta"}];default:return[]}}getDefaultFilterType(){switch(this.filterType){case"product":return"all";case"order":return"status";case"user":return"all";case"post":return"all";case"page":return"all";case"comment":return"all";case"custom_posttype":return"all";default:return"all"}}getConfig(){const e=this.container.querySelector(".notifal-logic-selector select");return this.updateConditionsFromDOM(),{multiple_filters:!0,logic:e?e.value:"AND",conditions:this.conditions.filter(a=>a.enabled)}}updateConditionsFromDOM(){this.conditions.forEach(e=>{const a=this.container.querySelector(`[data-condition-id="${e.id}"]`);if(!a)return;a.querySelectorAll("input[data-field], select[data-field]").forEach(_=>{const m=_.dataset.field;m&&(e.data||(e.data={}),_.multiple?e.data[m]=Array.from(_.selectedOptions).map(f=>f.value):e.data[m]=_.value)}),a.querySelectorAll(".notifal-ajax-search[data-field]").forEach(_=>{const m=_.dataset.field;if(!m)return;e.data||(e.data={});const f=_.querySelectorAll(".notifal-selected-item"),h=Array.from(f).map(b=>{const E=b.getAttribute("data-id");return E?parseInt(E):null}).filter(b=>b!==null);e.data[m]=h})})}validate(){const e=[];return this.conditions.forEach((a,n)=>{const i=a.data||{},_=`#${n+1}`,m=this.getFilterTypeOptions().find(E=>E.value===a.type)?.label||a.type,f=E=>`${this.filterType.charAt(0).toUpperCase()+this.filterType.slice(1)} filter ${_} ('${m}'): ${E}`,h={"order:status":()=>(!i.statuses||i.statuses.length===0)&&"Please select at least one order status.","order:date_range":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","order:products":()=>(!i.products||i.products.length===0)&&"Please select at least one product.","order:custom_filter":()=>!i.custom_filter&&"Custom filter value cannot be empty.","product:categories":()=>(!i.categories||i.categories.length===0)&&"Please select at least one category.","product:specific":()=>(!i.products||i.products.length===0)&&"Please select at least one product.","product:date_range":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","product:custom_meta":()=>!i.custom_filter&&"Custom filter value cannot be empty.","user:roles":()=>(!i.roles||i.roles.length===0)&&"Please select at least one user role.","user:specific":()=>(!i.users||i.users.length===0)&&"Please select at least one user.","user:custom_meta":()=>(!i.meta_key||!i.value)&&"Please provide a meta key and value.","user:registration_date":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","post:categories":()=>(!i.categories||i.categories.length===0)&&"Please select at least one category.","post:specific":()=>(!i.posts||i.posts.length===0)&&"Please select at least one post.","post:author":()=>(!i.authors||i.authors.length===0)&&"Please select at least one author.","post:date_range":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","post:custom_meta":()=>!i.custom_filter&&"Custom filter value cannot be empty.","page:specific":()=>(!i.pages||i.pages.length===0)&&"Please select at least one page.","page:status":()=>(!i.statuses||i.statuses.length===0)&&"Please select at least one page status.","page:author":()=>(!i.authors||i.authors.length===0)&&"Please select at least one author.","page:template":()=>(!i.templates||i.templates.length===0)&&"Please select at least one template.","page:date_range":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","page:custom_meta":()=>!i.custom_filter&&"Custom filter value cannot be empty.","comment:status":()=>(!i.statuses||i.statuses.length===0)&&"Please select at least one comment status.","comment:post_type":()=>(!i.post_types||i.post_types.length===0)&&"Please select at least one post type.","comment:author":()=>(!i.authors||i.authors.trim()==="")&&"Please enter an author name or email.","comment:date_range":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","comment:custom_meta":()=>!i.custom_filter&&"Custom filter value cannot be empty.","custom_posttype:categories":()=>(!i.categories||i.categories.length===0)&&"Please select at least one category.","custom_posttype:specific":()=>(!i.items||i.items.length===0)&&"Please select at least one item.","custom_posttype:status":()=>(!i.statuses||i.statuses.length===0)&&"Please select at least one status.","custom_posttype:author":()=>(!i.authors||i.authors.length===0)&&"Please select at least one author.","custom_posttype:date_range":()=>i.range==="custom"&&(!i.start_date||!i.end_date)&&"Please select both start and end dates.","custom_posttype:custom_meta":()=>!i.custom_filter&&"Custom filter value cannot be empty."},b=`${this.filterType}:${a.type}`;if(h[b]){const E=h[b]();E&&e.push(f(E))}}),e}loadConfig(e){if(!e||!e.multiple_filters)return;const a=this.container.querySelector(".notifal-logic-selector select");if(a&&e.logic&&(a.value=e.logic),e.conditions&&Array.isArray(e.conditions)){this.conditions=e.conditions.map(i=>({...i,id:this.nextId++}));const n=this.container.querySelector(".notifal-filter-conditions");n&&(n.innerHTML="",this.conditions.forEach(i=>{this.renderCondition(i)}),typeof initSearchBoxes=="function"&&initSearchBoxes())}this.updateUI(),this.updateAllTypeSelectors()}}window.MultiFilterManager=o,document.addEventListener("DOMContentLoaded",function(){const t=document.getElementById("notifal-product-restrictions");t&&(window.productFilterManager=new o("product",t));const e=document.getElementById("notifal-order-restrictions");e&&(window.orderFilterManager=new o("order",e));const a=document.getElementById("notifal-user-restrictions");a&&(window.userFilterManager=new o("user",a));const n=document.getElementById("notifal-post-restrictions");n&&(window.postFilterManager=new o("post",n));const i=document.getElementById("notifal-page-restrictions");i&&(window.pageFilterManager=new o("page",i));const _=document.getElementById("notifal-comment-restrictions");_&&(window.commentFilterManager=new o("comment",_));const m=document.getElementById("notifal-custom-posttype-restrictions");m&&(window.customPostTypeFilterManager=new o("custom_posttype",m))})}catch(o){console.error("Error in multi-filters.js:",o)}try{let o=function(r){if(!r||typeof r!="string")return!1;const s=r.trim();return s.length<2||/[\s;:{}\\]/.test(s)?!1:/^[a-zA-Z_][a-zA-Z0-9_/.-]*$/.test(s)},t=function(r){if(!r||typeof r!="string")return[];const s=/\{([^}]+)\}/g,u=[];let v;for(;(v=s.exec(r))!==null;){const S=v[1].trim();S&&o(S)&&!u.includes(S)&&u.push(S)}return u},e=function(r){const s=document.getElementById("notifal-template-analysis-status"),u=document.getElementById("notifal-detected-tags"),v=document.getElementById("notifal-tags-list"),S=document.querySelector(".notifal-template-analysis-section");if(!s||!u||!v)return;if(!r||r.length===0){s.classList.remove("notifal-hidden"),u.classList.add("notifal-hidden"),i();return}if(s.classList.add("notifal-hidden"),u.classList.remove("notifal-hidden"),S){const p=S.querySelector(".notifal-field-header");p&&p.classList.add("notifal-hidden")}const w=r.map(p=>`
            <div class="notifal-tag-badge" data-tag="${p}">
                <span class="notifal-tag-icon">
                    <span class="notifal-icon notifal-icon-tags-fill size-16"></span>
                </span>
                <span class="notifal-tag-name">${p}</span>
            </div>
        `).join("");v.innerHTML=w,n(r)},a=function(r){const s={product:!1,order:!1,user:!1,post:!1,page:!1,comment:!1,custom_posttype:!1,detectedCustomPostTypes:[]};if(!r||!Array.isArray(r))return s;const u=window.NotifalOnPageConfig?.generatedPostTypes||[],v={product:0,order:0,user:0,post:0,page:0,comment:0,custom_posttype:0};r.forEach(p=>{if(p.startsWith("product_")||p.includes("product_name")||p.includes("product_link")||p.includes("product_price")||p.startsWith("product_publish_date")||p.startsWith("product_modified_date")||p.startsWith("product_created_date")||p.includes("product_meta_"))v.product++;else if(p.startsWith("order_")||p.includes("order_id")||p.includes("order_total")||p.startsWith("order_created_date")||p.startsWith("order_completed_date")||p.startsWith("order_paid_date")||p.startsWith("order_modified_date")||p.startsWith("order_shipped_date")||p.includes("order_meta_"))v.order++;else if(p.startsWith("user_")||p.includes("user_id")||p.includes("user_name")||p.includes("user_email")||p.includes("user_meta_"))v.user++;else if(p.startsWith("post_")||p==="post_title"||p==="post_content"||p==="post_excerpt"||p==="post_author"||p==="post_date"||p==="post_modified"||p.startsWith("post_publish_date")||p.startsWith("post_modified_date")||p.startsWith("post_created_date")||p.includes("post_meta_"))v.post++;else if(p.startsWith("page_")||p==="page_title"||p==="page_content"||p==="page_excerpt"||p==="page_author"||p==="page_published_date"||p==="page_modified"||p.startsWith("page_published_date")||p.startsWith("page_modified_date")||p.includes("page_meta_"))v.page++;else if(p.startsWith("comment_")||p==="comment_content"||p==="comment_author"||p==="comment_date"||p.startsWith("comment_publish_date")||p.startsWith("comment_created_date")||p.startsWith("comment_date_")||p.includes("comment_meta_"))v.comment++;else{let M=!1,j=null;for(const B of u)if(new RegExp("^"+B+"_").test(p)){M=!0,j=B;break}!M&&(p.startsWith("cpt_")||p==="cpt_title"||p==="cpt_content"||p==="cpt_excerpt"||p==="cpt_author"||p==="cpt_date"||p==="cpt_modified"||p.startsWith("cpt_publish_date")||p.startsWith("cpt_modified_date")||p.startsWith("cpt_created_date")||p.includes("cpt_meta_"))&&(M=!0,j="legacy"),M&&(v.custom_posttype++,j&&j!=="legacy"&&(s.detectedCustomPostTypes||(s.detectedCustomPostTypes=[]),s.detectedCustomPostTypes.includes(j)||s.detectedCustomPostTypes.push(j)))}});const S=["order","product","user","post","page","custom_posttype","comment"],w=[];return S.forEach(p=>{v[p]>0&&w.push(p)}),w.length>1?w.includes("order")&&w.includes("product")?(s.order=!0,s.product=!0,w.forEach(p=>{p!=="order"&&p!=="product"&&(s[p]=!0)})):w.forEach(p=>{s[p]=!0}):w.length===1&&(s[w[0]]=!0),s},n=function(r){const s=a(r),u=[];s.product||u.push("product"),s.order||u.push("order"),s.user||u.push("user"),s.post||u.push("post"),s.page||u.push("page"),s.comment||u.push("comment"),s.custom_posttype||u.push("custom_posttype"),s.custom_posttype&&s.detectedCustomPostTypes&&C(s.detectedCustomPostTypes),u.length>0?m(u):i()},i=function(){document.querySelectorAll(".notifal-restriction-card").forEach(v=>{v.classList.remove("notifal-hidden")});const s=document.getElementById("notifal-dynamic-restrictions");s&&s.classList.remove("notifal-hidden");const u=document.querySelector(".notifal-hidden-restrictions-message");u&&u.remove(),te()},_=function(){document.querySelectorAll(".notifal-restriction-card").forEach(v=>{v.classList.add("notifal-hidden")});const s=document.getElementById("notifal-dynamic-restrictions");s&&s.classList.add("notifal-hidden");const u=document.querySelector(".notifal-hidden-restrictions-message");u&&u.remove()},m=function(r){if(!r||!Array.isArray(r))return;i();const s=document.querySelectorAll(".notifal-restriction-card");if(r.forEach((u,v)=>{if(typeof u!="string"){console.warn("Invalid restriction type:",u);return}let S=null;s.forEach(w=>{const p=w.querySelector(".notifal-form-label");if(p){const M=p.textContent.toLowerCase();(u==="product"&&M.includes("product restrictions")||u==="order"&&M.includes("order restrictions")||u==="user"&&(M.includes("user restrictions")||M.includes("user tags"))||u==="post"&&M.includes("post restrictions")||u==="page"&&M.includes("page restrictions")||u==="comment"&&M.includes("comment restrictions")||u==="custom_posttype"&&M.includes("custom post type restrictions"))&&(S=w)}}),S&&S.classList.add("notifal-hidden")}),r.length>0)try{f(r)}catch(u){console.error("Error showing hidden restrictions message:",u)}te()},f=function(r){if(!r||!Array.isArray(r)){console.warn("Invalid hiddenRestrictions data for message");return}const s=document.querySelector(".notifal-content-source-settings");if(!s)return;const u=s.querySelector(".notifal-hidden-restrictions-message");u&&u.remove();const v={product:"Product",order:"Order",user:"User",post:"Post",page:"Page",comment:"Comment",custom_posttype:"Custom Post Type"},w=`Restrictions hidden: ${r.map(j=>typeof j!="string"?(console.warn("Invalid restriction type in map:",j),"Unknown"):v[j]||j).join(", ")} (not relevant to detected tags)`,p=document.createElement("div");p.className="notifal-hidden-restrictions-message notifal-notice notifal-notice-info",p.innerHTML=`
            <div class="notifal-notice-content">
                <span class="notifal-notice-icon">ℹ️</span>
                <span class="notifal-notice-text">${w}</span>
            </div>
        `;const M=document.querySelector(".notifal-template-analysis-section");M&&M.insertAdjacentElement("afterend",p)},h=function(){const r=document.querySelector('[name="content_source_type"]'),s=document.getElementById("notifal-dynamic-restrictions"),u=document.querySelector('button[data-tab="content-source"]');if(!r||!s)return;const v=()=>{if(r.value==="static"){s.classList.add("notifal-hidden"),u&&(u.style.display="none",u.classList.add("notifal-hidden"));const w=document.getElementById("tab-content-source");if(w&&w.classList.contains("active")){const p=document.querySelector('button[data-tab="general"]');p&&p.click()}}else s.classList.remove("notifal-hidden"),u&&(u.style.display="",u.classList.remove("notifal-hidden"))};v(),r.addEventListener("change",v)},b=function(){const r=document.querySelector('[name="product_restriction_type"]'),s=document.querySelector(".notifal-product-categories"),u=document.querySelector(".notifal-product-specific"),v=document.querySelector(".notifal-product-custom");if(!r)return;function S(){const w=r.value;if(window._notifalProductRestrictionState=w,s&&(s.classList.add("notifal-hidden"),s.setAttribute("data-notifal-state","hidden")),u&&(u.classList.add("notifal-hidden"),u.setAttribute("data-notifal-state","hidden")),v&&(v.classList.add("notifal-hidden"),v.setAttribute("data-notifal-state","hidden")),w==="categories"&&s){s.classList.remove("notifal-hidden"),s.setAttribute("data-notifal-state","visible");const p=s.querySelector(".notifal-ajax-search")?.getAttribute("data-populated-values");if(p)try{const M=JSON.parse(p);setTimeout(()=>{const j=s.querySelector(".notifal-ajax-search");j&&(z(j,M),j.removeAttribute("data-populated-values"))},500)}catch(M){console.warn("Error retrying population for categories:",M)}}else if(w==="specific"&&u){u.classList.remove("notifal-hidden"),u.setAttribute("data-notifal-state","visible");const p=u.querySelector(".notifal-ajax-search")?.getAttribute("data-populated-values");if(p)try{const M=JSON.parse(p);setTimeout(()=>{const j=u.querySelector(".notifal-ajax-search");j&&(z(j,M),j.removeAttribute("data-populated-values"))},500)}catch(M){console.warn("Error retrying population for specific products:",M)}}else w==="custom"&&v&&(v.classList.remove("notifal-hidden"),v.setAttribute("data-notifal-state","visible"));te()}S(),r.addEventListener("change",function(){S()}),window._notifalProductRestrictionInitialized=!0},E=function(){const r=document.querySelector('[name="order_restriction_type"]'),s={date_range:document.querySelector(".notifal-order-date-range"),status:document.querySelector(".notifal-order-status"),products:document.querySelector(".notifal-order-products"),custom:document.querySelector(".notifal-order-custom")};if(!r)return;const u=()=>{const v=r.value;Object.values(s).forEach(S=>{S&&S.classList.add("notifal-hidden")}),v!=="all"&&s[v]&&s[v].classList.remove("notifal-hidden"),te()};u(),r.addEventListener("change",u)},k=function(){const r=document.querySelector('[name="order_date_range"]'),s=document.querySelector(".notifal-order-custom-date-range"),u=document.querySelector('[name="order_date_start"]'),v=document.querySelector('[name="order_date_end"]');if(!r||!s)return;const S=()=>{r.value==="custom"?s.classList.remove("notifal-hidden"):s.classList.add("notifal-hidden")},w=()=>{if(!u||!v)return;const B=u.value,J=v.value;B&&J&&B>J?(v.setCustomValidity("End date must be after start date"),v.reportValidity()):v.setCustomValidity("")},p=()=>{u&&v&&v.value&&(u.max=v.value)},M=()=>{u&&v&&u.value&&(v.min=u.value)};S(),r.addEventListener("change",S),u&&u.addEventListener("change",()=>{M(),w()}),v&&v.addEventListener("change",()=>{p(),w()}),document.querySelectorAll(".notifal-quick-date-btn").forEach(B=>{B.addEventListener("click",()=>{const J=parseInt(B.getAttribute("data-days")),Y=new Date,ie=new Date;ie.setDate(Y.getDate()-J),u&&(u.value=ie.toISOString().split("T")[0]),v&&(v.value=Y.toISOString().split("T")[0]),w()})})},x=function(){const r=document.querySelector('[name="user_restriction_type"]'),s={roles:document.querySelector(".notifal-user-roles"),specific:document.querySelector(".notifal-user-specific"),custom:document.querySelector(".notifal-user-custom")};if(!r)return;const u=()=>{const v=r.value;if(Object.values(s).forEach(S=>{S&&S.classList.add("notifal-hidden")}),v!=="all"&&s[v]&&(s[v].classList.remove("notifal-hidden"),v==="roles"&&s.roles)){const S=s.roles.querySelector('[name="user_roles[]"]');S&&setTimeout(()=>{const w=S.getAttribute("data-stored-values");if(w)try{const p=JSON.parse(w);O("user_roles",p),S.removeAttribute("data-stored-values")}catch(p){console.warn("Error parsing stored user roles:",p)}},50)}te()};u(),r.addEventListener("change",u)},P=function(){const r=document.querySelectorAll('input[name="notifal_template_id"]');if(!r.length)return;let s=!1;I=async v=>{if(s)return;if(!v){e([]),_();return}if(document.querySelector('[name="content_source_type"]')?.value==="static"){e([]),_();return}try{s=!0;const w=document.getElementById("notifal-template-analysis-status");if(w&&(w.innerHTML=`
                        <div class="notifal-empty-state loading">
                            <div class="notifal-empty-icon">⏳</div>
                            <h4>${NotifalOnPageStrings?.analyzing_template||"Analyzing Template..."}</h4>
                            <p>${NotifalOnPageStrings?.please_wait||"Please wait while we analyze the template content."}</p>
                            <button type="button" class="notifal-button secondary" onclick="skipTemplateAnalysis()" style="margin-top: 10px;">
                                Skip Analysis
                            </button>
                        </div>
                    `,w.classList.remove("notifal-hidden"),document.getElementById("notifal-detected-tags")?.classList.add("notifal-hidden")),_(),!NotifalOnPageAjax||!NotifalOnPageAjax.ajax_url){console.warn("AJAX URL not available, skipping analysis"),K();return}if(!NotifalOnPageAjax.nonce||!NotifalOnPageAjax.nonce.get_template_content&&!NotifalOnPageAjax.nonce.search){console.warn("Nonce not available, skipping analysis"),K();return}const p=new FormData;p.append("action","notifal_get_template_content"),p.append("nonce",NotifalOnPageAjax.nonce.get_template_content||NotifalOnPageAjax.nonce.search),p.append("template_id",v);const M=new AbortController,j=setTimeout(()=>{M.abort(),console.warn("Template analysis timed out, skipping..."),K()},1e4),B=await fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:p,signal:M.signal});if(clearTimeout(j),!B.ok)throw new Error(`HTTP error! status: ${B.status}`);const J=await B.json();if(J.success&&J.data.content){const Y=t(J.data.content);e(Y)}else{const Y=document.getElementById("notifal-template-analysis-status");Y&&(Y.innerHTML=`
                            <div class="notifal-empty-state warning">
                                <div class="notifal-empty-icon">ℹ️</div>
                                <h4>Analysis Incomplete</h4>
                                <p>Could not analyze template content. All restriction options are available.</p>
                            </div>
                        `,Y.classList.remove("notifal-hidden"),document.getElementById("notifal-detected-tags")?.classList.add("notifal-hidden")),i()}}catch(w){if(console.error("Template analysis error:",w),w.name==="AbortError"){K();return}const p=document.getElementById("notifal-template-analysis-status");p&&(p.innerHTML=`
                        <div class="notifal-empty-state error">
                            <div class="notifal-empty-icon">⚠️</div>
                            <h4>Analysis Failed</h4>
                            <p>Unable to analyze template content. Please try refreshing the page or selecting a different template.</p>
                            <button type="button" class="notifal-button secondary" onclick="location.reload()">Refresh Page</button>
                        </div>
                    `,p.classList.remove("notifal-hidden"),document.getElementById("notifal-detected-tags")?.classList.add("notifal-hidden")),i()}finally{s=!1}},r.forEach(v=>{v.addEventListener("change",S=>{S.target.checked&&(I(S.target.value),typeof window.NotifalTemplateSelection<"u"&&window.NotifalTemplateSelection.updateHiddenTemplateFields&&window.NotifalTemplateSelection.updateHiddenTemplateFields(S.target.value))})});const u=document.querySelector('input[name="notifal_template_id"]:checked');u?(document.querySelector('[name="content_source_type"]')?.value==="static"?(e([]),_()):(_(),I(u.value)),typeof window.NotifalTemplateSelection<"u"&&window.NotifalTemplateSelection.updateHiddenTemplateFields&&window.NotifalTemplateSelection.updateHiddenTemplateFields(u.value)):_()},F=function(){if(document.querySelector('[name="content_source_type"]')?.value==="static")return!0;if(document.querySelector('[name="user_restriction_type"]')?.value==="roles"){const B=document.querySelector('[name="user_roles[]"]')||document.querySelector('[name="user_roles"]');if(B){if(Array.from(B.selectedOptions).map(Y=>Y.value).length===0)return N("error",'Please select at least one user role when "User Roles" restriction is enabled.'),!1}else console.warn("User roles field not found for validation")}if(document.querySelector('[name="order_restriction_type"]')?.value==="date_range"&&document.querySelector('[name="order_date_range"]')?.value==="custom"){const B=document.querySelector('[name="order_date_start"]')?.value,J=document.querySelector('[name="order_date_end"]')?.value;if(!B||!J)return N("error","Please select both start and end dates for custom date range."),!1;if(B>J)return N("error","End date must be after start date."),!1}if(document.querySelector('[name="order_restriction_type"]')?.value==="custom"){const B=document.querySelector('[name="order_custom_filter"]')?.value;if(!B||!B.trim())return N("error","Please enter a custom filter value."),!1;const J=/[><=!&|]/.test(B),Y=B.includes(":");if(!J&&!Y)return N("error","Custom filter must include an operator (=, >, <, !=) or use format: meta_key:value"),!1}if(document.querySelector('[name="product_restriction_type"]')?.value==="custom"){const B=document.querySelector('[name="product_custom_filter"]')?.value;if(!B||!B.trim())return N("error","Please enter a custom filter value."),!1;const J=/[><=!&|]/.test(B),Y=B.includes(":");if(!J&&!Y)return N("error","Custom filter must include an operator (=, >, <, !=) or use format: meta_key:value"),!1}if(document.querySelector('[name="user_restriction_type"]')?.value==="custom"){const B=document.querySelector('[name="user_custom_filter"]')?.value;if(!B||!B.trim())return N("error","Please enter a custom filter value."),!1;if(!B.includes(":"))return N("error","Custom filter must be in format: meta_key:value (e.g., user_type:premium)"),!1}let s=[];const u=document.getElementById("notifal-product-restrictions");window.productFilterManager&&window.productFilterManager.conditions.length>0&&u&&!u.classList.contains("notifal-hidden")&&(s=s.concat(window.productFilterManager.validate()));const v=document.getElementById("notifal-order-restrictions");window.orderFilterManager&&window.orderFilterManager.conditions.length>0&&v&&!v.classList.contains("notifal-hidden")&&(s=s.concat(window.orderFilterManager.validate()));const S=document.getElementById("notifal-user-restrictions");window.userFilterManager&&window.userFilterManager.conditions.length>0&&S&&!S.classList.contains("notifal-hidden")&&(s=s.concat(window.userFilterManager.validate()));const w=document.getElementById("notifal-post-restrictions");window.postFilterManager&&window.postFilterManager.conditions.length>0&&w&&!w.classList.contains("notifal-hidden")&&(s=s.concat(window.postFilterManager.validate()));const p=document.getElementById("notifal-page-restrictions");window.pageFilterManager&&window.pageFilterManager.conditions.length>0&&p&&!p.classList.contains("notifal-hidden")&&(s=s.concat(window.pageFilterManager.validate()));const M=document.getElementById("notifal-comment-restrictions");window.commentFilterManager&&window.commentFilterManager.conditions.length>0&&M&&!M.classList.contains("notifal-hidden")&&(s=s.concat(window.commentFilterManager.validate()));const j=document.getElementById("notifal-custom-posttype-restrictions");return window.customPostTypeFilterManager&&window.customPostTypeFilterManager.conditions.length>0&&j&&!j.classList.contains("notifal-hidden")&&(s=s.concat(window.customPostTypeFilterManager.validate())),s.length>0?(N("error","Content source settings validation failed."),s.forEach(B=>N("error",B)),!1):!0},N=function(r,s){typeof window.NotifalUtils<"u"&&window.NotifalUtils.showMessage?window.NotifalUtils.showMessage(s,r,5e3):typeof NotifalUtils<"u"&&NotifalUtils.showMessage?NotifalUtils.showMessage(s,r,5e3):console.warn(`Toast message (${r}): ${s}`)},U=function(){function r(Y){let ie=document.querySelector(`[name="${Y}"]`);return ie||(ie=document.querySelector(`[name="${Y}[]"]`)),ie?ie.type==="select-multiple"?Array.from(ie.selectedOptions).map(se=>se.value):ie.type==="checkbox"?ie.checked?[ie.value]:[]:ie.value?[ie.value]:[]:(console.warn(`Field not found: ${Y}`),[])}function s(Y){const ie=document.querySelector(`[data-name="${Y}"]`);if(!ie)return[];const se=ie.querySelectorAll(".notifal-selected-item");return Array.from(se).map(oe=>{const le=oe.getAttribute("data-id");return le?parseInt(le):null}).filter(oe=>oe!==null)}let u={multiple_filters:!1,logic:"AND",conditions:[]},v={multiple_filters:!1,logic:"AND",conditions:[]},S={multiple_filters:!1,logic:"AND",conditions:[]},w={multiple_filters:!1,logic:"AND",conditions:[]},p={multiple_filters:!1,logic:"AND",conditions:[]},M={multiple_filters:!1,logic:"AND",conditions:[]},j={multiple_filters:!1,logic:"AND",conditions:[]};window.productFilterManager&&(u=window.productFilterManager.getConfig()),window.orderFilterManager&&(v=window.orderFilterManager.getConfig()),window.userFilterManager&&(S=window.userFilterManager.getConfig()),window.postFilterManager&&(w=window.postFilterManager.getConfig()),window.pageFilterManager&&(p=window.pageFilterManager.getConfig()),window.commentFilterManager&&(M=window.commentFilterManager.getConfig()),window.customPostTypeFilterManager&&(j=window.customPostTypeFilterManager.getConfig());const B={content_source_type:document.querySelector('[name="content_source_type"]')?.value||"dynamic",product_filters:u,order_filters:v,user_filters:S,post_filters:w,page_filters:p,comment_filters:M,custom_posttype_filters:j,product_restriction_type:document.querySelector('[name="product_restriction_type"]')?.value||"all",product_categories:s("product_categories"),specific_products:s("specific_products"),product_custom_filter:document.querySelector('[name="product_custom_filter"]')?.value||"",order_restriction_type:document.querySelector('[name="order_restriction_type"]')?.value||"status",order_date_range:document.querySelector('[name="order_date_range"]')?.value||"last_7d",order_date_start:document.querySelector('[name="order_date_start"]')?.value||"",order_date_end:document.querySelector('[name="order_date_end"]')?.value||"",order_statuses:r("order_statuses"),order_products:s("order_products"),order_custom_filter:document.querySelector('[name="order_custom_filter"]')?.value||"",user_restriction_type:document.querySelector('[name="user_restriction_type"]')?.value||"all",user_roles:r("user_roles"),specific_users:s("specific_users"),user_custom_filter:document.querySelector('[name="user_custom_filter"]')?.value||"",specific_custom_posttypes:s("specific_custom_posttypes"),custom_posttype_categories:s("custom_posttype_categories"),detected_tags:[]};let J=document.querySelector('input[name="content_source_settings"]');J||(J=document.createElement("input"),J.type="hidden",J.name="content_source_settings",document.querySelector(".notifal-content-source-settings")?.appendChild(J)),J.value=JSON.stringify(B),y()},$=function(r){if(!r.content_source_settings)return;const s=r.content_source_settings;if(s.content_source_type){const u=document.querySelector('[name="content_source_type"]');u&&(u.value=s.content_source_type)}if(s.product_filters&&window.productFilterManager&&window.productFilterManager.loadConfig(s.product_filters),s.order_filters&&window.orderFilterManager&&window.orderFilterManager.loadConfig(s.order_filters),s.user_filters&&window.userFilterManager&&window.userFilterManager.loadConfig(s.user_filters),s.post_filters&&window.postFilterManager&&window.postFilterManager.loadConfig(s.post_filters),s.page_filters&&window.pageFilterManager&&window.pageFilterManager.loadConfig(s.page_filters),s.comment_filters&&window.commentFilterManager&&window.commentFilterManager.loadConfig(s.comment_filters),s.custom_posttype_filters&&window.customPostTypeFilterManager&&window.customPostTypeFilterManager.loadConfig(s.custom_posttype_filters),s.product_restriction_type){const u=document.querySelector('[name="product_restriction_type"]');u&&(u.value=s.product_restriction_type)}if(s.product_custom_filter){const u=document.querySelector('[name="product_custom_filter"]');u&&(u.value=s.product_custom_filter)}if(s.order_restriction_type){const u=document.querySelector('[name="order_restriction_type"]');u&&(u.value=s.order_restriction_type)}if(s.order_date_range){const u=document.querySelector('[name="order_date_range"]');u&&(u.value=s.order_date_range)}if(s.order_date_start){const u=document.querySelector('[name="order_date_start"]');u&&(u.value=s.order_date_start)}if(s.order_date_end){const u=document.querySelector('[name="order_date_end"]');u&&(u.value=s.order_date_end)}if(s.order_custom_filter){const u=document.querySelector('[name="order_custom_filter"]');u&&(u.value=s.order_custom_filter)}if(s.user_restriction_type){const u=document.querySelector('[name="user_restriction_type"]');u&&(u.value=s.user_restriction_type)}if(s.user_custom_filter){const u=document.querySelector('[name="user_custom_filter"]');u&&(u.value=s.user_custom_filter)}O("order_statuses",s.order_statuses),O("user_roles",s.user_roles),G("product_categories",s.product_categories),G("specific_products",s.specific_products),G("order_products",s.order_products),G("specific_users",s.specific_users),G("specific_custom_posttypes",s.specific_custom_posttypes),G("custom_posttype_categories",s.custom_posttype_categories),setTimeout(()=>{["content_source_type","product_restriction_type","order_restriction_type","order_date_range","user_restriction_type"].forEach(v=>{const S=document.querySelector(`[name="${v}"]`);S&&S.dispatchEvent(new Event("change",{bubbles:!0}))}),s.user_roles&&s.user_roles.length>0&&setTimeout(()=>{O("user_roles",s.user_roles)},200),s.specific_users&&s.specific_users.length>0&&setTimeout(()=>{G("specific_users",s.specific_users)},300)},100)},O=function(r,s){if(!s||!Array.isArray(s))return;let u=document.querySelector(`[name="${r}"]`);if(u||(u=document.querySelector(`[name="${r}[]"]`)),!u)return;const v=u.closest(".notifal-field-wrapper, .notifal-restriction-field");if(!(v&&!v.classList.contains("notifal-hidden"))){u.setAttribute("data-stored-values",JSON.stringify(s));return}Array.from(u.options).forEach(w=>{w.selected=!1}),s.forEach(w=>{const p=u.querySelector(`option[value="${w}"]`);p?p.selected=!0:console.warn(`Option not found for value: ${w} in field: ${r}`)}),u.removeAttribute("data-stored-values")},G=function(r,s){if(!s||!Array.isArray(s))return;const u=document.querySelector(`[data-name="${r}"]`);if(!u)return;if(u.querySelectorAll(".notifal-selected-item").forEach(S=>S.remove()),u.removeAttribute("data-populated-values"),u.setAttribute("data-populated-values",JSON.stringify(s)),u.querySelector(".notifal-ajax-search-input"))z(u,s);else{let S=0;const w=5,p=()=>{S++,u.querySelector(".notifal-ajax-search-input")?z(u,s):S<w&&setTimeout(p,500*S)};setTimeout(p,500)}},z=function(r,s){if(!s||!Array.isArray(s)||s.length===0)return;r.querySelectorAll(".notifal-selected-item").forEach(p=>p.remove());const v=r.dataset.name,S=v==="product_categories"||v==="target_categories"||v==="custom_posttype_categories"||v==="post_categories",w=new FormData;if(S)w.append("action","notifal_get_term_titles"),w.append("nonce",NotifalOnPageAjax.nonce.search),w.append("term_ids",s.join(","));else if(v==="specific_users"||v==="post_authors"||v==="page_authors"||v==="custom_posttype_authors")w.append("action","notifal_get_user_titles"),w.append("nonce",NotifalOnPageAjax.nonce.search),w.append("user_ids",s.join(","));else{const p=r.dataset.postType||"page";w.append("action","notifal_get_post_titles"),w.append("nonce",NotifalOnPageAjax.nonce.search),w.append("post_ids",s.join(","))}fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:w}).then(p=>p.json()).then(p=>{if(p.success&&p.data){const M=new Set;p.data.forEach(j=>{M.has(j.id)||(W(r,j),M.add(j.id))})}}).catch(p=>{console.warn("Error populating AJAX search field:",p)})},W=function(r,s){const u=r.querySelector(".notifal-ajax-search-selected");if(!u||u.querySelector(`[data-id="${s.id}"]`))return;const S=document.createElement("div");S.className="notifal-selected-item",S.setAttribute("data-id",s.id),S.innerHTML=`
            <span class="notifal-selected-label">${s.title}</span>
            <input type="hidden" name="${r.dataset.name}[]" value="${s.id}" />
            <button type="button" class="notifal-remove-selected">
                <span class="notifal-icon notifal-icon-x-circle size-12"></span>
            </button>
        `,u.appendChild(S)},A=function(r){if(!r||!Array.isArray(r))return;i();const s=document.querySelectorAll(".notifal-restriction-card");if(r.forEach((u,v)=>{if(typeof u!="string"){console.warn("Invalid restriction type:",u);return}let S=null;s.forEach(w=>{const p=w.querySelector(".notifal-form-label");if(p){const M=p.textContent.toLowerCase();(u==="product"&&M.includes("product restrictions")||u==="order"&&M.includes("order restrictions")||u==="user"&&(M.includes("user restrictions")||M.includes("user tags")))&&(S=w)}}),S&&S.classList.add("notifal-hidden")}),r.length>0)try{f(r)}catch(u){console.error("Error showing hidden restrictions message:",u)}te()},d=function(){const r=document.querySelector('[name="user_roles[]"]');return r?r.options?r.options.length:0:null},T=function(){document.querySelectorAll(".notifal-available-meta-section").forEach(s=>{q(s)}),te()},q=function(r){const s=r.getAttribute("data-meta-type"),u=r.querySelector(".notifal-meta-header"),v=r.querySelector(".notifal-meta-toggle"),S=r.querySelector(".notifal-meta-content"),w=r.querySelector(".notifal-meta-search-input"),p=r.querySelector(".notifal-meta-list");if(!u||!v||!S||!w||!p)return;u.addEventListener("click",()=>{v.getAttribute("aria-expanded")==="true"?(v.setAttribute("aria-expanded","false"),S.classList.add("notifal-hidden")):(v.setAttribute("aria-expanded","true"),S.classList.remove("notifal-hidden"),r.hasAttribute("data-loaded")||(g(s,p),r.setAttribute("data-loaded","true")))}),v.addEventListener("keydown",j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u.click())});let M=null;w.addEventListener("input",j=>{const B=j.target.value.trim();M&&clearTimeout(M),M=setTimeout(()=>{B.length===0?g(s,p):L(s,B,p)},300)})},g=function(r,s){s.innerHTML='<div class="notifal-meta-loading">'+(NotifalOnPageStrings?.loading_meta_fields||"Loading available meta fields...")+"</div>";const u=window.wpApiSettings&&window.wpApiSettings.nonce||window.NotifalOnPageAjax&&window.NotifalOnPageAjax.nonce&&window.NotifalOnPageAjax.nonce.search||"",S=`${window.wpApiSettings&&window.wpApiSettings.root||`${window.location.origin}/wp-json`}notifal/v1/dynamic-keys?type=${r}`;fetch(S,{method:"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":u},credentials:"same-origin"}).then(w=>{if(!w.ok)throw new Error(`HTTP error! status: ${w.status}`);return w.json()}).then(w=>{D(w,s)}).catch(w=>{console.error("Error loading meta fields:",w),s.innerHTML='<div class="notifal-meta-error">'+(NotifalOnPageStrings?.error_loading_meta||"Error loading meta fields. Please try again.")+"</div>"})},L=function(r,s,u){u.innerHTML='<div class="notifal-meta-loading">'+(NotifalOnPageStrings?.searching_meta||"Searching...")+"</div>";const v=window.wpApiSettings&&window.wpApiSettings.nonce||window.NotifalOnPageAjax&&window.NotifalOnPageAjax.nonce&&window.NotifalOnPageAjax.nonce.search||"",w=`${window.wpApiSettings&&window.wpApiSettings.root||`${window.location.origin}/wp-json`}notifal/v1/dynamic-keys?type=${r}&search=${encodeURIComponent(s)}`;fetch(w,{method:"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":v},credentials:"same-origin"}).then(p=>{if(!p.ok)throw new Error(`HTTP error! status: ${p.status}`);return p.json()}).then(p=>{D(p,u)}).catch(p=>{console.error("Error searching meta fields:",p),u.innerHTML='<div class="notifal-meta-error">'+(NotifalOnPageStrings?.error_searching_meta||"Error searching meta fields. Please try again.")+"</div>"})},D=function(r,s){if(!r||r.length===0){s.innerHTML='<div class="notifal-meta-empty">'+(NotifalOnPageStrings?.no_meta_fields_found||"No meta fields found.")+"</div>";return}const u=r.map(v=>{const S=H(v);return`
                <div class="notifal-meta-item" tabindex="0" data-meta-key="${v}">
                    <span class="notifal-meta-name">${v}</span>
                    ${S?`<span class="notifal-meta-description">${S}</span>`:""}
                </div>
            `}).join("");s.innerHTML=u,s.querySelectorAll(".notifal-meta-item").forEach(v=>{v.addEventListener("click",()=>{Q(v)}),v.addEventListener("keydown",S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),Q(v))})})},H=function(r){return{_price:"Current price",_regular_price:"Regular price",_sale_price:"Sale price",_sku:"Product SKU",_stock:"Stock quantity",_weight:"Product weight",_length:"Product length",_width:"Product width",_height:"Product height",_billing_first_name:"Billing first name",_billing_last_name:"Billing last name",_billing_email:"Billing email",_billing_phone:"Billing phone",_billing_address_1:"Billing address",_billing_city:"Billing city",_shipping_first_name:"Shipping first name",_shipping_last_name:"Shipping last name",_shipping_address_1:"Shipping address",_order_total:"Order total",_payment_method:"Payment method",_order_currency:"Order currency",first_name:"User first name",last_name:"User last name",nickname:"User nickname",description:"User description",wp_capabilities:"User capabilities",wp_user_level:"User level"}[r]||""},Q=function(r){const s=r.getAttribute("data-meta-key");s&&(navigator.clipboard&&navigator.clipboard.writeText?navigator.clipboard.writeText(s).then(()=>Z(r)).catch(()=>V(s,r)):V(s,r))},V=function(r,s){const u=document.createElement("textarea");u.value=r,u.style.position="fixed",u.style.opacity="0",document.body.appendChild(u),u.focus(),u.select();try{document.execCommand("copy"),Z(s)}catch(v){console.error("Failed to copy meta field:",v)}document.body.removeChild(u)},Z=function(r){r.classList.add("copied"),setTimeout(()=>{r.classList.remove("copied")},1500)},te=function(){document.querySelectorAll(".notifal-available-meta-section").forEach(s=>{if(s.closest(".notifal-filter-condition")){s.classList.remove("notifal-restriction-hidden");return}const u=s.getAttribute("data-meta-type"),v=s.closest(".notifal-restriction-card");if(!v)return;const S=v.classList.contains("notifal-hidden");let w=!1;if(u==="product"){const p=document.querySelector('[name="product_restriction_type"]');w=p&&p.value==="custom"}else if(u==="order"){const p=document.querySelector('[name="order_restriction_type"]');w=p&&p.value==="custom"}else if(u==="user"){const p=document.querySelector('[name="user_restriction_type"]');w=p&&p.value==="custom"}S||!w?s.classList.add("notifal-restriction-hidden"):s.classList.remove("notifal-restriction-hidden")})},C=function(r){if(!r||r.length===0)return;const s=r[0];window.detectedCustomPostTypes=r,window.primaryCustomPostType=s,window.customPostTypeFilterManager&&(window.customPostTypeFilterManager.detectedPostType=s,window.customPostTypeFilterManager.detectedPostTypes=r);const u=document.querySelector('[data-name="specific_custom_posttypes"]');u&&u.setAttribute("data-post-type",s);const v=document.querySelector('[data-name="custom_posttype_categories"]');if(v){const w=window.NotifalOnPageConfig?.postTypes?.[s];if(w&&w.taxonomies){const p=w.taxonomies[0]||"category";v.setAttribute("data-post-type",p)}}const S=document.querySelector('[data-meta-type="custom_posttype"]');S&&(S.setAttribute("data-detected-post-type",s),R(s))},R=function(r){const s=document.querySelector('[data-meta-type="custom_posttype"]'),u=s?.querySelector(".notifal-meta-fields");if(!s||!u)return;u.innerHTML=`<div class="notifal-meta-loading">Loading meta fields for ${r}...</div>`;const v=window.wpApiSettings&&window.wpApiSettings.nonce||window.NotifalOnPageAjax&&window.NotifalOnPageAjax.nonce&&window.NotifalOnPageAjax.nonce.search||"",w=`${window.wpApiSettings&&window.wpApiSettings.root||`${window.location.origin}/wp-json`}notifal/v1/dynamic-keys?type=custom_posttype&post_type=${encodeURIComponent(r)}`;fetch(w,{method:"GET",headers:{"Content-Type":"application/json","X-WP-Nonce":v},credentials:"same-origin"}).then(p=>{if(!p.ok)throw new Error(`HTTP error! status: ${p.status}`);return p.json()}).then(p=>{D(p,u)}).catch(p=>{console.error("Error loading custom post type meta fields:",p),u.innerHTML=`<div class="notifal-meta-error">Error loading meta fields for ${r}. Please try again.</div>`})},X=function(){const r=document.querySelector('input[name="notifal_template_id"]:checked');r&&r.value&&r.dispatchEvent(new Event("change",{bubbles:!0}))},ee=function(){document.addEventListener("click",function(r){r.target&&r.target.classList.contains("notifal-retry-analysis-btn")&&(r.preventDefault(),typeof window.retryTemplateAnalysis=="function"?window.retryTemplateAnalysis():console.error("retryTemplateAnalysis function not available"))})},ae=function(){try{h(),b(),E(),k(),x(),P(),re(),de(),ne(),T(),window.analyzeTemplate=t,window.updateTemplateAnalysis=e,window.validateContentSourceSettings=F,window.saveContentSourceSettings=U,window.handleTemplateSelection=P,window.populateContentSourceSettings=$,window.skipTemplateAnalysis=K,window.handleTemplateChange=I,window.retryTemplateAnalysis=X,window.processHiddenRestrictionsManually=A,window.debugUserRolesField=d,window.ensureUserRolesSaved=y,window.showToast=N,window.initMetaFieldsUI=T,window.updateMetaFieldsVisibility=te,window.loadMetaFields=g,window.searchMetaFields=L,window.setupMetaFieldSection=q,ee()}catch(r){console.error("Content Source JS: Critical error in initContentSourceSettings:",r)}},K=function(){const r=document.getElementById("notifal-template-analysis-status");r&&(r.innerHTML=`
                <div class="notifal-empty-state warning">
                    <div class="notifal-empty-icon">ℹ️</div>
                    <h4>Analysis Skipped</h4>
                    <p>To filter used tags in your template, selected template must be analyzed.</p>
                    <button type="button" class="notifal-button secondary notifal-retry-analysis-btn">
                        Retry Analysis
                    </button>
                </div>
            `,r.classList.remove("notifal-hidden"),document.getElementById("notifal-detected-tags")?.classList.add("notifal-hidden")),_()},ne=function(){const r=document.querySelector('input[name="content_source_settings"]');if(!(!r||!r.value))try{const s=JSON.parse(r.value);s&&typeof s=="object"&&$({content_source_settings:s})}catch(s){console.warn("Error parsing content source settings:",s)}},re=function(){document.querySelectorAll(".notifal-ajax-search").forEach(u=>{const v=u.getAttribute("data-populated-values");if(v&&!u.hasAttribute("data-population-in-progress"))try{const S=JSON.parse(v);u.setAttribute("data-population-in-progress","true"),setTimeout(()=>{z(u,S),u.removeAttribute("data-populated-values"),u.removeAttribute("data-population-in-progress")},1e3)}catch(S){console.warn("Error parsing populated values:",S),u.removeAttribute("data-population-in-progress")}}),new MutationObserver(u=>{u.forEach(v=>{v.addedNodes.forEach(S=>{S.nodeType===Node.ELEMENT_NODE&&(S.querySelectorAll?S.querySelectorAll(".notifal-ajax-search"):S.classList&&S.classList.contains("notifal-ajax-search")?[S]:[]).forEach(p=>{const M=p.getAttribute("data-populated-values");if(M&&!p.hasAttribute("data-population-in-progress"))try{const j=JSON.parse(M);p.setAttribute("data-population-in-progress","true"),setTimeout(()=>{z(p,j),p.removeAttribute("data-populated-values"),p.removeAttribute("data-population-in-progress")},1e3)}catch(j){console.warn("Error parsing populated values:",j),p.removeAttribute("data-population-in-progress")}})})})}).observe(document.body,{childList:!0,subtree:!0})},de=function(){new MutationObserver(u=>{u.forEach(v=>{v.addedNodes.forEach(S=>{if(S.nodeType===Node.ELEMENT_NODE){const w=S.querySelectorAll(".notifal-restriction-card"),p=S.querySelector("#notifal-dynamic-restrictions");(w.length>0||p&&p.classList.contains("notifal-hidden"))&&S.querySelectorAll(".notifal-ajax-search").forEach(j=>{const B=j.getAttribute("data-populated-values");if(B&&!j.hasAttribute("data-population-in-progress"))try{const J=JSON.parse(B);j.setAttribute("data-population-in-progress","true"),setTimeout(()=>{z(j,J),j.removeAttribute("data-populated-values"),j.removeAttribute("data-population-in-progress")},500)}catch(J){console.warn("Error parsing populated values for retry:",J),j.removeAttribute("data-population-in-progress")}})}})})}).observe(document.body,{childList:!0,subtree:!0}),new MutationObserver(u=>{u.forEach(v=>{if(v.type==="attributes"&&v.attributeName==="class"){const S=v.target;S.classList&&(S.classList.contains("notifal-restriction-field")||S.classList.contains("notifal-field-wrapper"))&&!S.classList.contains("notifal-hidden")&&S.querySelectorAll("select[multiple]").forEach(p=>{const M=p.getAttribute("data-stored-values");if(M)try{const j=JSON.parse(M),B=p.name.replace("[]","");O(B,j)}catch(j){console.warn("Error restoring stored values:",j)}})}})}).observe(document.body,{attributes:!0,attributeFilter:["class"],subtree:!0})},y=function(){if(document.querySelector('[name="user_restriction_type"]')?.value==="roles"){let s=document.querySelector('[name="user_roles[]"]');if(s||(s=document.querySelector('[name="user_roles"]')),s){const u=Array.from(s.selectedOptions).map(S=>S.value),v=document.querySelector('input[name="content_source_settings"]');if(v&&v.value)try{const S=JSON.parse(v.value);S.user_roles=u,v.value=JSON.stringify(S)}catch(S){console.warn("Error updating content source settings:",S)}}else console.warn("User roles field not found during save")}},l=function(){typeof U=="function"&&U(),y()},c=function(){const r=document.getElementById("notifal-multi-filter-upgrade");if(!r)return;let s=0;["product","order","post","page","comment","custom_posttype"].forEach(v=>{const S=document.querySelector(`#${v}-filter-conditions`);if(S){const w=S.querySelectorAll(".notifal-filter-condition");s+=w.length}}),s===1?r.classList.remove("notifal-hidden"):r.classList.add("notifal-hidden")};var Ft=o,Dt=t,Nt=e,It=a,Mt=n,jt=i,Ot=_,Bt=m,Rt=f,Vt=h,Ut=b,Ht=E,zt=k,Wt=x,Gt=P,Jt=F,dt=N,Yt=U,Xt=$,Kt=O,Qt=G,Zt=z,ea=W,ta=A,aa=d,ia=T,oa=q,na=g,sa=L,la=D,ra=H,ca=Q,da=V,ua=Z,fa=te,pa=C,ma=R,_a=X,ga=ee,ya=ae,va=K,ha=ne,ba=re,Sa=de,wa=y,Ta=l,qa=c;let I=null;document.addEventListener("DOMContentLoaded",()=>{const r=document.querySelector(".notifal-notification-form");r&&r.addEventListener("submit",l)}),window.handleFormSubmission=l,window.ensureUserRolesSaved=y,window.updateProUpgradeBoxVisibility=c,window._notifalContentSourceScriptLoaded=!0,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{ae(),setTimeout(c,100)}):(ae(),setTimeout(c,100))}catch(o){console.error("Content Source JS: Critical error in main initialization:",o)}(function(){function o(A){const d=document.querySelector('[name="show_on_desktop"]'),T=document.querySelector('[name="show_on_tablet"]'),q=document.querySelector('[name="show_on_mobile"]'),g=d?d.checked:!0,L=T?T.checked:!0,D=q?q.checked:!0;switch(document.querySelectorAll(".notifal-position-group-for-toast, .notifal-position-group-for-floating, .notifal-position-group-for-topbar, .notifal-position-group-for-popup").forEach(Q=>{Q.classList.add("notifal-hidden")}),A){case"toast":case"floating":document.querySelectorAll(".notifal-position-group-for-toast, .notifal-position-group-for-floating").forEach(K=>{K.classList.contains("notifal-desktop-position-group")||K.classList.contains("notifal-desktop-bar-position-group")?(g||L)&&K.classList.remove("notifal-hidden"):(K.classList.contains("notifal-mobile-position-group")||K.classList.contains("notifal-mobile-bar-position-group"))&&D&&K.classList.remove("notifal-hidden")});break;case"topbar":const V=document.querySelector(".notifal-desktop-bar-position-group"),Z=document.querySelector(".notifal-mobile-bar-position-group"),te=document.querySelector(".notifal-topbar-placement-group"),C=document.querySelector('[name="desktop_bar_position"]'),R=document.querySelector('[name="mobile_bar_position"]'),X=C&&C.value==="top",ee=R&&R.value==="top";V&&(g||L)&&V.classList.remove("notifal-hidden"),Z&&D&&Z.classList.remove("notifal-hidden"),te&&(X||ee?te.classList.remove("notifal-hidden"):te.classList.add("notifal-hidden")),t();break;case"popup":const ae=document.querySelector(".notifal-popup-backdrop-group");ae&&ae.classList.remove("notifal-hidden");break}}function t(){const A=document.querySelector('[name="topbar_placement"]'),d=document.querySelector(".notifal-topbar-sticky-wrap");if(!A||!d)return;A.value==="above_header"?d.classList.remove("notifal-hidden"):d.classList.add("notifal-hidden")}function e(){n(),i(),_(),m(),k()}function a(A){const d=document.querySelector(`[name="${A}"]`);d&&(d.value="50")}function n(){const A=document.querySelector('[name="show_on_desktop"]'),d=document.querySelector('[name="show_on_tablet"]'),T=document.querySelector('[name="show_on_mobile"]');function q(){const g=document.querySelector('[name="notification_display_type"]'),L=g?g.value:"toast";o(L)}[A,d,T].forEach(g=>{g&&g.addEventListener("change",q)}),q()}function i(){const A=document.querySelector('[name="desktop_position"]'),d=document.querySelector(".notifal-desktop-distance-settings");if(!A)return;function T(){const L=A.value;switch(document.querySelectorAll(".notifal-desktop-distance-settings .notifal-distance-group").forEach(H=>H.classList.add("notifal-hidden")),d&&d.classList.remove("notifal-hidden"),L){case"top-right":q(["notifal-top-distance","notifal-right-distance"]);break;case"top-center":q(["notifal-top-distance"]);break;case"top-left":q(["notifal-top-distance","notifal-left-distance"]);break;case"bottom-right":q(["notifal-bottom-distance","notifal-right-distance"]);break;case"bottom-center":q(["notifal-bottom-distance"]);break;case"bottom-left":q(["notifal-bottom-distance","notifal-left-distance"]);break;case"center":d&&d.classList.add("notifal-hidden");break}}function q(L){L.forEach(D=>{const H=d?d.querySelector(`.${D}`):document.querySelector(`.${D}`);H&&H.classList.remove("notifal-hidden")})}function g(){switch(A.value){case"top-center":a("desktop_right_distance"),a("desktop_left_distance"),a("desktop_bottom_distance");break;case"bottom-center":a("desktop_top_distance"),a("desktop_right_distance"),a("desktop_left_distance");break;case"center":a("desktop_top_distance"),a("desktop_bottom_distance"),a("desktop_right_distance"),a("desktop_left_distance");break;case"top-right":a("desktop_left_distance"),a("desktop_bottom_distance");break;case"top-left":a("desktop_right_distance"),a("desktop_bottom_distance");break;case"bottom-right":a("desktop_left_distance"),a("desktop_top_distance");break;case"bottom-left":a("desktop_right_distance"),a("desktop_top_distance");break}}A.addEventListener("change",()=>{T(),g()}),T(),g()}function _(){const A=document.querySelector('[name="mobile_position"]'),d=document.querySelector(".notifal-mobile-distance-settings");if(!A)return;function T(){const L=A.value;switch(document.querySelectorAll(".notifal-mobile-distance-settings .notifal-distance-group").forEach(H=>H.classList.add("notifal-hidden")),d&&d.classList.remove("notifal-hidden"),L){case"top":q(["notifal-mobile-top-distance"]);break;case"bottom":q(["notifal-mobile-bottom-distance"]);break;case"center":d&&d.classList.add("notifal-hidden");break;case"same-as-desktop":d&&d.classList.add("notifal-hidden");break}}function q(L){L.forEach(D=>{const H=d?d.querySelector(`.${D}`):document.querySelector(`.${D}`);H&&H.classList.remove("notifal-hidden")})}function g(){switch(A.value){case"top":a("mobile_bottom_distance");break;case"bottom":a("mobile_top_distance");break;case"center":a("mobile_top_distance"),a("mobile_bottom_distance");break;case"same-as-desktop":a("mobile_top_distance"),a("mobile_bottom_distance");break}}A.addEventListener("change",()=>{T(),g()}),T(),g()}function m(){const A=document.querySelector('[name="notification_display_type"]');if(!A)return;function d(){const D=A.value,H=A.closest("[data-display-type]");if(H){H.setAttribute("data-display-type",D);const Q=new CustomEvent("notifal:displayTypeChanged",{detail:{displayType:D}});document.dispatchEvent(Q)}o(D)}A.addEventListener("change",d);const T=document.querySelector('[name="topbar_placement"]');T&&T.addEventListener("change",t);const q=document.querySelector('[name="desktop_bar_position"]'),g=document.querySelector('[name="mobile_bar_position"]');function L(){const D=document.querySelector('[name="notification_display_type"]');D&&D.value==="topbar"&&o("topbar")}q&&q.addEventListener("change",L),g&&g.addEventListener("change",L),d()}function f(){document.querySelectorAll('input[name*="distance"]').forEach(d=>{d.addEventListener("input",function(){const T=parseInt(this.value)||0,q=parseInt(this.min)||0,g=parseInt(this.max)||500;T<q?this.value=q:T>g&&(this.value=g)})})}function h(){document.querySelectorAll('[name="desktop_position"], [name="mobile_position"]').forEach(d=>{d.addEventListener("change",function(){const T=new CustomEvent("notifal:positionChanged",{detail:{position:this.value,device:this.name.includes("desktop")?"desktop":"mobile"}});document.dispatchEvent(T)})})}function b(){const A=document.querySelector('[name="mobile_behavior"]'),d=document.querySelector('[name="mobile_width"]');if(A&&d){let q=function(){const g=A.value,L=d.closest(".notifal-field-wrapper");L&&(g==="custom"||g==="simplified"?L.style.display="block":L.style.display="none")};var T=q;A.addEventListener("change",q),q()}}function E(){const A=document.querySelector('[name="audio_type"]')?document.querySelector('[name="audio_type"]').value:"default",d=document.querySelector('[name="audio_file"]'),T=d?d.closest(".notifal-audio-default-wrapper"):null,q=document.querySelector(".notifal-audio-preview-wrapper");let g=document.querySelector(".notifal-audio-custom-wrapper");if(!g){const H=document.querySelector('[name="custom_audio_file"]');H&&(g=H.closest(".notifal-field-wrapper"))}const L=document.querySelector(".notifal-audio-default-wrapper"),D=T||L;if(D&&(D.style.display="none",D.style.visibility="hidden"),q&&(q.style.display="none",q.style.visibility="hidden"),g&&(g.style.display="none",g.style.visibility="hidden"),A==="default"){D&&(D.style.display="block",D.style.visibility="visible"),q&&(q.style.display="block",q.style.visibility="visible");const H=document.querySelector(".notifal-audio-preview-btn");H&&d&&(H.setAttribute("data-audio",d.value),H.setAttribute("data-audio-type","default"))}else if(A==="custom"){g&&(g.style.display="block",g.style.visibility="visible");const H=document.querySelector('[name="custom_audio_file"]');H&&H.value&&q&&(q.style.display="block",q.style.visibility="visible");const Q=document.querySelector(".notifal-audio-preview-btn");Q&&H&&H.value&&(Q.setAttribute("data-audio",H.value),Q.setAttribute("data-audio-type","custom"))}}function k(){const A=document.querySelector('[name="enable_audio"]'),d=document.querySelector('[name="audio_type"]'),T=document.querySelector(".notifal-audio-settings-container");document.querySelector(".notifal-audio-default-wrapper"),document.querySelector(".notifal-audio-custom-wrapper");const q=document.querySelector('[name="audio_volume"]');document.querySelector('[name="audio_play_on_show"]'),document.querySelector('[name="audio_play_on_hide"]');const g=document.querySelector('[name="audio_file"]');function L(){const C=A?A.checked:!1;T&&(C?T.classList.remove("notifal-hidden"):T.classList.add("notifal-hidden"))}function D(){const C=document.querySelector(".notifal-audio-preview-btn"),R=document.querySelector(".notifal-audio-preview-status");if(window.currentAudioPreview||(window.currentAudioPreview=null),C){let K=function(){window.currentAudioPreview&&(window.currentAudioPreview.pause(),window.currentAudioPreview=null,re());const c=document.querySelector('[name="audio_type"]')?document.querySelector('[name="audio_type"]').value:"default",r=document.querySelector('[name="audio_file"]');if(c==="default"){const s=r?r.value:"";s&&(C.setAttribute("data-audio",s),C.setAttribute("data-audio-type","default"))}else if(c==="custom"){const s=document.querySelector('[name="custom_audio_file"]');s&&s.value&&(C.setAttribute("data-audio",s.value),C.setAttribute("data-audio-type","custom"))}},ne=function(){const c=C.getAttribute("data-audio"),r=C.getAttribute("data-audio-type");if(!c)return;window.currentAudioPreview&&(window.currentAudioPreview.pause(),window.currentAudioPreview=null,re());let s;if(r==="default")s=`${window.NotifalOnPageConfig?window.NotifalOnPageConfig.plugin_url:"/wp-content/plugins/notifal/"}app/Modules/OnPageNotification/Resources/Assets/audios/${c}`;else if(r==="custom")s=c;else return;window.currentAudioPreview=new Audio(s);const u=q?parseInt(q.value)/100:.5;if(window.currentAudioPreview.volume=u,C.classList.add("playing"),C.querySelector(".notifal-audio-preview-icon").innerHTML='<span class="notifal-icon notifal-icon-stop-circle size-18"></span>',C.querySelector(".notifal-audio-preview-text").textContent=NotifalOnPageStrings?.playing_audio||"Playing...",C.setAttribute("aria-label","Stop audio preview"),C.setAttribute("title","Click to stop audio preview"),R){const v=r==="custom"?c.split("/").pop():c;R.textContent=`Playing: ${v}`,R.className="notifal-audio-preview-status playing",R.setAttribute("aria-label",`Currently playing: ${v}`)}window.currentAudioPreview.play().catch(v=>{console.error("Audio playback failed:",v),R&&(R.textContent=NotifalOnPageStrings?.audio_play_error||"Error: Could not play audio",R.className="notifal-audio-preview-status error",R.setAttribute("aria-label",NotifalOnPageStrings?.audio_play_error||"Error: Could not play audio file")),re()}),window.currentAudioPreview.addEventListener("ended",function(){re(),window.currentAudioPreview=null}),window.currentAudioPreview.addEventListener("error",function(){console.error("Audio error:",window.currentAudioPreview.error),R&&(R.textContent=NotifalOnPageStrings?.audio_file_not_found||"Error: Audio file not found",R.className="notifal-audio-preview-status error",R.setAttribute("aria-label",NotifalOnPageStrings?.audio_file_not_found||"Error: Audio file not found")),re(),window.currentAudioPreview=null})},re=function(){C.classList.remove("playing"),C.querySelector(".notifal-audio-preview-icon").innerHTML='<span class="notifal-icon notifal-icon-play-circle size-18"></span>',C.querySelector(".notifal-audio-preview-text").textContent=NotifalOnPageStrings?.preview_audio||"Preview Audio",C.setAttribute("aria-label","Preview selected audio file"),C.setAttribute("title","Click to preview the selected audio sound"),R&&(R.textContent="",R.className="notifal-audio-preview-status",R.removeAttribute("aria-label"))};var X=K,ee=ne,ae=re;C.addEventListener("click",function(){ne()}),C.addEventListener("keydown",function(c){(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),ne())});const de=document.querySelector('[name="audio_file"]');de&&(de.addEventListener("change",K),de.addEventListener("change",function(){const c=document.querySelector(".notifal-audio-preview-btn");c&&(c.setAttribute("data-audio",this.value),c.setAttribute("data-audio-type","default"))}));const y=document.querySelector('[name="audio_type"]');y&&y.addEventListener("change",K);const l=document.querySelector('[name="custom_audio_file"]');l&&l.addEventListener("change",K),K()}}function H(){document.querySelectorAll(".notifal-media-upload-btn").forEach(R=>{R.addEventListener("click",function(){const X=this.getAttribute("data-field"),ee=document.getElementById(X),ae=wp.media({title:"Select Audio File",button:{text:"Use this audio"},multiple:!1,library:{type:["audio/mpeg","audio/wav","audio/ogg","audio/mp3","audio/mp4"]}});ae.on("select",function(){const K=ae.state().get("selection").first().toJSON();ee&&(ee.value=K.url,Q(X,K.url,K.filename||K.title))}),ae.open()})})}function Q(C,R,X){const ee=document.getElementById(C),ae=ee?ee.closest(".notifal-media-upload-wrapper").querySelector(".notifal-media-preview"):null;if(ae&&(ae.innerHTML=`
                    <div class="notifal-media-item">
                        <span class="notifal-media-filename">${X||"Audio File"}</span>
                        <button type="button" class="notifal-media-remove" data-field="${C}">
                            <span class="notifal-icon notifal-icon-x-circle size-16"></span>
                        </button>
                    </div>
                `),C==="custom_audio_file"){const K=document.querySelector(".notifal-audio-preview-wrapper"),ne=document.querySelector(".notifal-audio-preview-btn");window.currentAudioPreview&&(window.currentAudioPreview.pause(),window.currentAudioPreview=null),K&&ne&&(K.style.display="block",K.style.visibility="visible",ne.setAttribute("data-audio",R),ne.setAttribute("data-audio-type","custom"))}}function V(){document.addEventListener("click",function(C){if(C.target.closest(".notifal-media-remove")){C.preventDefault();const X=C.target.closest(".notifal-media-remove").getAttribute("data-field"),ee=document.getElementById(X),ae=ee?ee.closest(".notifal-media-upload-wrapper").querySelector(".notifal-media-preview"):null;if(ee&&(ee.value=""),ae&&(ae.innerHTML=""),X==="custom_audio_file"){const K=document.querySelector(".notifal-audio-preview-wrapper"),ne=document.querySelector(".notifal-audio-preview-btn");window.currentAudioPreview&&(window.currentAudioPreview.pause(),window.currentAudioPreview=null),K&&(K.style.display="none",K.style.visibility="hidden"),ne&&(ne.removeAttribute("data-audio"),ne.removeAttribute("data-audio-type"))}}})}function Z(){if(q){const C=q.closest(".notifal-range-wrapper").querySelector(".notifal-range-value");C&&(C.textContent=q.value)}}const te=document.querySelector('[name="custom_css"]');if(te){const C=$()||"NEW";te.addEventListener("input",function(){const R=O(this.value,C);R.valid?W():z(R.errors)}),te.addEventListener("blur",function(){const R=O(this.value,C);R.valid||z(R.errors)}),setTimeout(()=>{const R=O(te.value,C);R.valid||z(R.errors)},1e3)}A&&A.addEventListener("change",L),d&&d.addEventListener("change",function(){E();const C=document.querySelector(".notifal-audio-preview-btn");if(C){const R=this.value;if(window.currentAudioPreview&&(window.currentAudioPreview.pause(),window.currentAudioPreview=null),R==="default"){const X=g?g.value:"";X&&(C.setAttribute("data-audio",X),C.setAttribute("data-audio-type","default"))}else if(R==="custom"){const X=document.querySelector('[name="custom_audio_file"]');X&&X.value&&(C.setAttribute("data-audio",X.value),C.setAttribute("data-audio-type","custom"))}}}),q&&q.addEventListener("input",Z),L(),E(),Z(),D(),H(),V(),window.addEventListener("beforeunload",function(){window.currentAudioPreview&&(window.currentAudioPreview.pause(),window.currentAudioPreview=null)})}function x(){const A=document.querySelector('input[name="appearance_settings"]');if(A&&A.value)try{const d=JSON.parse(A.value);d&&typeof window.NotifalAppearanceSettings<"u"&&window.NotifalAppearanceSettings.populateAppearanceSettings&&window.NotifalAppearanceSettings.populateAppearanceSettings(d)}catch(d){console.warn("Error parsing saved appearance settings:",d)}}function I(A){if(!A.appearance_settings)return;const d=A.appearance_settings;if(d.show_on_desktop!==void 0){const g=document.querySelector('[name="show_on_desktop"]');g&&(g.checked=d.show_on_desktop)}if(d.show_on_tablet!==void 0){const g=document.querySelector('[name="show_on_tablet"]');g&&(g.checked=d.show_on_tablet)}if(d.show_on_mobile!==void 0){const g=document.querySelector('[name="show_on_mobile"]');g&&(g.checked=d.show_on_mobile)}const T=d.notification_display_type||"toast";if(T==="topbar"){if(d.desktop_bar_position){const g=document.querySelector('[name="desktop_bar_position"]');g&&(g.value=d.desktop_bar_position)}if(d.mobile_bar_position){const g=document.querySelector('[name="mobile_bar_position"]');g&&(g.value=d.mobile_bar_position)}if(d.desktop_bar_distance!==void 0){const g=document.querySelector('[name="desktop_bar_distance"]');g&&(g.value=d.desktop_bar_distance)}if(d.mobile_bar_distance!==void 0){const g=document.querySelector('[name="mobile_bar_distance"]');g&&(g.value=d.mobile_bar_distance)}if(d.topbar_placement){const g=document.querySelector('[name="topbar_placement"]');g&&(g.value=d.topbar_placement)}if(d.topbar_sticky_on_scroll!==void 0){const g=document.querySelector('[name="topbar_sticky_on_scroll"]');g&&(g.checked=d.topbar_sticky_on_scroll)}t()}else if(T==="popup"){if(d.backdrop_bg_color){const g=document.querySelector('[name="backdrop_bg_color"]');g&&(g.value=d.backdrop_bg_color)}if(d.backdrop_blur!==void 0){const g=document.querySelector('[name="backdrop_blur"]');g&&(g.value=d.backdrop_blur)}}else{if(d.desktop_position){const g=document.querySelector('[name="desktop_position"]');g&&(g.value=d.desktop_position)}if(d.mobile_position){const g=document.querySelector('[name="mobile_position"]');g&&(g.value=d.mobile_position)}}if(["desktop_top_distance","desktop_bottom_distance","desktop_left_distance","desktop_right_distance","mobile_top_distance","mobile_bottom_distance"].forEach(g=>{const L=document.querySelector(`[name="${g}"]`);L&&(L.value=d[g]!==void 0?d[g]:50)}),d.notification_display_type){const g=document.querySelector('[name="notification_display_type"]');g&&(g.value=d.notification_display_type)}if(d.show_animation_type){const g=document.querySelector('[name="show_animation_type"]');g&&(g.value=d.show_animation_type)}if(d.hide_animation_type){const g=document.querySelector('[name="hide_animation_type"]');g&&(g.value=d.hide_animation_type)}if(d.animation_duration!==void 0){const g=document.querySelector('[name="animation_duration"]');g&&(g.value=d.animation_duration)}if(d.enable_audio!==void 0){const g=document.querySelector('[name="enable_audio"]');g&&(g.checked=d.enable_audio)}if(d.audio_type){const g=document.querySelector('[name="audio_type"]');g&&(g.value=d.audio_type)}if(d.audio_file){const g=document.querySelector('[name="audio_file"]');let L=d.audio_file;L&&L.includes("http")&&(L=L.split("/").pop()),g&&(g.value=L)}if(d.custom_audio_file){const g=document.querySelector('[name="custom_audio_file"]');if(g){g.value=d.custom_audio_file;const L=g.closest(".notifal-media-upload-wrapper")?.querySelector(".notifal-media-preview");if(L&&d.custom_audio_file){const D=d.custom_audio_file.split("/").pop()||"Audio File";L.innerHTML=`
                        <div class="notifal-media-item">
                            <span class="notifal-media-filename">${D}</span>
                            <button type="button" class="notifal-media-remove" data-field="custom_audio_file">
                                <span class="notifal-icon notifal-icon-x-circle size-16"></span>
                            </button>
                        </div>
                    `}}}if(d.audio_volume!==void 0){const g=document.querySelector('[name="audio_volume"]');g&&(g.value=d.audio_volume)}if(d.audio_play_on_show!==void 0){const g=document.querySelector('[name="audio_play_on_show"]');g&&(g.checked=d.audio_play_on_show)}if(d.audio_play_on_hide!==void 0){const g=document.querySelector('[name="audio_play_on_hide"]');g&&(g.checked=d.audio_play_on_hide)}if(d.z_index!==void 0){const g=document.querySelector('[name="z_index"]');g&&(g.value=d.z_index)}if(d.custom_css){const g=document.querySelector('[name="custom_css"]');g&&(g.value=d.custom_css)}setTimeout(()=>{["show_on_desktop","show_on_tablet","show_on_mobile","desktop_position","mobile_position","notification_display_type","show_animation_type","hide_animation_type","animation_duration","enable_audio","audio_type","audio_file","audio_volume","audio_play_on_show","audio_play_on_hide","backdrop_bg_color","backdrop_blur","z_index","custom_css"].forEach(V=>{const Z=document.querySelector(`[name="${V}"]`);Z&&Z.dispatchEvent(new Event("change",{bubbles:!0}))}),typeof window.NotifalAppearanceSettings<"u"&&window.NotifalAppearanceSettings.updateAudioTypeFields&&window.NotifalAppearanceSettings.updateAudioTypeFields();const L=document.querySelector('[name="audio_type"]'),D=document.querySelector('[name="audio_file"]'),H=document.querySelector('[name="custom_audio_file"]'),Q=document.querySelector(".notifal-audio-preview-btn");if(Q){const V=L?L.value:"default";V==="default"&&D&&D.value?(Q.setAttribute("data-audio",D.value),Q.setAttribute("data-audio-type","default")):V==="custom"&&H&&H.value&&(Q.setAttribute("data-audio",H.value),Q.setAttribute("data-audio-type","custom"))}},100)}function P(){const A=document.querySelector('[name="audio_file"]');let d=A?A.value:"";d&&d.includes("http")&&(d=d.split("/").pop());const T=document.querySelector('[name="custom_css"]'),q=T?T.value:"",g=$()||"NEW",L=O(q,g);if(!L.valid){z(L.errors);return}const D=document.querySelector('[name="notification_display_type"]')?.value||"toast",H=document.querySelector('[name="audio_play_on_show"]'),Q=H?H.checked:!0,V={show_on_desktop:document.querySelector('[name="show_on_desktop"]')?.checked||!1,show_on_tablet:document.querySelector('[name="show_on_tablet"]')?.checked||!1,show_on_mobile:document.querySelector('[name="show_on_mobile"]')?.checked||!1,notification_display_type:D,...D==="popup"?{backdrop_bg_color:document.querySelector('[name="backdrop_bg_color"]')?.value||"rgba(0, 0, 0, 0.5)",backdrop_blur:parseInt(document.querySelector('[name="backdrop_blur"]')?.value||2)}:D==="topbar"?{desktop_bar_position:document.querySelector('[name="desktop_bar_position"]')?.value||"top",desktop_bar_distance:parseInt(document.querySelector('[name="desktop_bar_distance"]')?.value||0),mobile_bar_position:document.querySelector('[name="mobile_bar_position"]')?.value||"top",mobile_bar_distance:parseInt(document.querySelector('[name="mobile_bar_distance"]')?.value||0),topbar_placement:document.querySelector('[name="topbar_placement"]')?.value||"fixed_top",topbar_sticky_on_scroll:document.querySelector('[name="topbar_sticky_on_scroll"]')?.checked??!0}:{desktop_position:document.querySelector('[name="desktop_position"]')?.value||"top-right",...F(document.querySelector('[name="desktop_position"]')?.value||"top-right"),mobile_position:document.querySelector('[name="mobile_position"]')?.value||"top",...N(document.querySelector('[name="mobile_position"]')?.value||"top")},show_animation_type:document.querySelector('[name="show_animation_type"]')?.value||"fade",hide_animation_type:document.querySelector('[name="hide_animation_type"]')?.value||"fade",animation_duration:parseInt(document.querySelector('[name="animation_duration"]')?.value||300),enable_audio:document.querySelector('[name="enable_audio"]')?.checked||!1,audio_type:document.querySelector('[name="audio_type"]')?.value||"default",audio_file:d,custom_audio_file:document.querySelector('[name="custom_audio_file"]')?.value||"",audio_volume:parseInt(document.querySelector('[name="audio_volume"]')?.value||50),audio_play_on_show:Q,audio_play_on_hide:document.querySelector('[name="audio_play_on_hide"]')?.checked||!1,z_index:parseInt(document.querySelector('[name="z_index"]')?.value||999999),custom_css:document.querySelector('[name="custom_css"]')?.value||""};let Z=document.querySelector('input[name="appearance_settings"]');Z||(Z=document.createElement("input"),Z.type="hidden",Z.name="appearance_settings",document.querySelector(".notifal-appearance-settings")?.appendChild(Z));const te=JSON.stringify(V);Z.value=te}function F(A){const d={};switch(A){case"top-right":case"top-left":d.desktop_top_distance=parseInt(document.querySelector('[name="desktop_top_distance"]')?.value||50),A==="top-right"?d.desktop_right_distance=parseInt(document.querySelector('[name="desktop_right_distance"]')?.value||50):d.desktop_left_distance=parseInt(document.querySelector('[name="desktop_left_distance"]')?.value||50);break;case"top-center":d.desktop_top_distance=parseInt(document.querySelector('[name="desktop_top_distance"]')?.value||50);break;case"bottom-right":case"bottom-left":d.desktop_bottom_distance=parseInt(document.querySelector('[name="desktop_bottom_distance"]')?.value||50),A==="bottom-right"?d.desktop_right_distance=parseInt(document.querySelector('[name="desktop_right_distance"]')?.value||50):d.desktop_left_distance=parseInt(document.querySelector('[name="desktop_left_distance"]')?.value||50);break;case"bottom-center":d.desktop_bottom_distance=parseInt(document.querySelector('[name="desktop_bottom_distance"]')?.value||50);break;case"center":break;default:d.desktop_top_distance=parseInt(document.querySelector('[name="desktop_top_distance"]')?.value||50),d.desktop_right_distance=parseInt(document.querySelector('[name="desktop_right_distance"]')?.value||50);break}return d}function N(A){const d={};switch(A){case"top":d.mobile_top_distance=parseInt(document.querySelector('[name="mobile_top_distance"]')?.value||50);break;case"bottom":d.mobile_bottom_distance=parseInt(document.querySelector('[name="mobile_bottom_distance"]')?.value||50);break;case"center":break;case"same-as-desktop":break;default:d.mobile_top_distance=parseInt(document.querySelector('[name="mobile_top_distance"]')?.value||50);break}return d}function U(){const A=document.querySelector('[name="desktop_position"]')?.value||"top-right",d=document.querySelector('[name="mobile_position"]')?.value||"top";switch(A){case"top-center":a("desktop_right_distance"),a("desktop_left_distance"),a("desktop_bottom_distance");break;case"bottom-center":a("desktop_top_distance"),a("desktop_right_distance"),a("desktop_left_distance");break;case"center":a("desktop_top_distance"),a("desktop_bottom_distance"),a("desktop_right_distance"),a("desktop_left_distance");break;case"top-right":a("desktop_left_distance"),a("desktop_bottom_distance");break;case"top-left":a("desktop_right_distance"),a("desktop_bottom_distance");break;case"bottom-right":a("desktop_left_distance"),a("desktop_top_distance");break;case"bottom-left":a("desktop_right_distance"),a("desktop_top_distance");break}switch(d){case"top":a("mobile_bottom_distance");break;case"bottom":a("mobile_top_distance");break;case"center":a("mobile_top_distance"),a("mobile_bottom_distance");break;case"same-as-desktop":a("mobile_top_distance"),a("mobile_bottom_distance");break}}function $(){const d=new URLSearchParams(window.location.search).get("id");if(d)return d;const T=document.querySelector('input[name="notification_id"]');return T?T.value:null}function O(A,d){if(!A||!A.trim())return{valid:!0,errors:[]};const T=[],q=[`.notifal-onpage-notification-${d}`,`#notifal-onpage-notification-${d}`];return G(A).forEach((L,D)=>{L.selector.split(",").map(Q=>Q.trim()).forEach(Q=>{q.some(Z=>Q.startsWith(Z))||T.push({line:D+1,selector:Q,message:`Selector "${Q}" must start with either ".notifal-onpage-notification-${d}" (class) or "#notifal-onpage-notification-${d}" (ID)`})})}),{valid:T.length===0,errors:T}}function G(A){const d=[],T=/([^{]+)\s*\{([^}]+)\}/g;let q;for(;(q=T.exec(A))!==null;){const g=q[1].trim(),L=q[2].trim();g&&L&&d.push({selector:g,declarations:L})}return d}function z(A){const d=document.querySelector('[name="custom_css"]');if(!d){console.warn("CSS field not found");return}d.classList.remove("notifal-field-error");const T=d.parentNode.querySelector(".notifal-css-error");if(T&&T.remove(),A.length>0){d.classList.add("notifal-field-error");const q=document.createElement("div");q.className="notifal-css-error",q.style.cssText=`
                margin-top: 0.5rem;
                padding: 0.5rem;
                background: #fef2f2;
                border: 1px solid #dc2626;
                border-radius: 4px;
                color: #dc2626;
                font-size: 0.875rem;
                line-height: 1.4;
            `;let g="<strong>CSS Validation Errors:</strong><br>";A.forEach(L=>{g+=`• Line ${L.line}: ${L.message}<br>`}),q.innerHTML=g,d.parentNode.insertBefore(q,d.nextSibling)}}function W(){const A=document.querySelector('[name="custom_css"]');if(!A)return;A.classList.remove("notifal-field-error");const d=A.parentNode.querySelector(".notifal-css-error");d&&d.remove()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",function(){e(),f(),h(),b(),x()}):(e(),f(),h(),b(),x()),window.NotifalAppearanceSettings={init:e,validateDistanceInputs:f,initPositionPreview:h,handleResponsiveBehavior:b,updateAudioTypeFields:E,populateAppearanceSettings:I,loadSavedAppearanceSettings:x,saveAppearanceSettings:P,validateCustomCSS:O,showCSSValidationErrors:z,clearCSSValidationErrors:W,clearAllIrrelevantDistances:U,testCSSValidation:function(){document.querySelector('[name="custom_css"]');const A=$()||"NEW",T=O(".invalid-selector { color: red; }",A);return z(T.errors),T}},window.saveAppearanceSettings=P})();(function(){const o={showTiming:{immediate:{fields:[]},delay:{fields:["delay_seconds"]},scroll:{fields:["scroll_percentage"]},exit_intent:{fields:[]},idle:{fields:["idle_seconds"]},custom:{fields:["custom_trigger_type","custom_trigger_delay","custom-trigger-help"],subFields:{javascript_event:["custom_js_event","custom_element_selector"],element_visible:["visibility_element_selector","visibility_threshold"],custom_condition:["custom_js_condition"],multiple_triggers:["multiple_triggers_config"]}}},displayDuration:{until_dismissed:{fields:[]},auto_hide:{fields:["auto_hide_seconds"]},persistent:{fields:["persistent_duration"]}},showFrequency:{always:{fields:[]},once_per_session:{fields:["max_shows_per_session","clear_session_on_logout"]}}};function t(y,l={}){const c=typeof NotifalOnPageStrings<"u"&&NotifalOnPageStrings[y]?NotifalOnPageStrings[y]:y;return Object.keys(l).reduce((r,s)=>r.replace(`{${s}}`,l[s]),c)}function e(y){return String(y).padStart(2,"0")}function a(y){const l=y.getFullYear(),c=e(y.getMonth()+1),r=e(y.getDate()),s=e(y.getHours()),u=e(y.getMinutes());return`${l}-${c}-${r}T${s}:${u}`}function n(y){const l=typeof window.NotifalOnPageConfig<"u"?window.NotifalOnPageConfig:{},c=typeof l.scheduleDisplayTimezone=="string"?l.scheduleDisplayTimezone.trim():"";if(c!==""&&typeof Intl<"u"&&Intl.DateTimeFormat)try{const j=new Intl.DateTimeFormat("en-CA",{timeZone:c,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(y),B=le=>{const ue=j.find(fe=>fe.type===le);return ue?ue.value:""},J=B("year"),Y=B("month"),ie=B("day");let se=B("hour"),oe=B("minute");if(!J||!Y||!ie||se===""||oe==="")throw new Error("incomplete datetime parts");return se=String(se).padStart(2,"0"),oe=String(oe).padStart(2,"0"),`${J}-${Y}-${ie}T${se}:${oe}`}catch{}const r=typeof l.scheduleGmtOffsetHours=="number"?l.scheduleGmtOffsetHours:0,s=Math.round(r*60),u=new Date(y.getTime()+s*60*1e3),v=u.getUTCFullYear(),S=e(u.getUTCMonth()+1),w=e(u.getUTCDate()),p=e(u.getUTCHours()),M=e(u.getUTCMinutes());return`${v}-${S}-${w}T${p}:${M}`}function i(y){if(!y||typeof y!="string")return"";const l=y.trim();if(l==="")return"";const c=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?$/,r=/[zZ]$|[+-]\d{2}:?\d{2}$/.test(l);if(c.test(l)&&!r)return l.length>=16?l.slice(0,16):l;const s=new Date(l);return Number.isNaN(s.getTime())?"":n(s)}function _(y){if(!y||typeof y!="string")return null;const l=y.trim();if(l==="")return null;if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(l)){const M=new Date(l);return Number.isNaN(M.getTime())?null:M.getTime()}const c=l.match(/^(\d{1,2})\s*\/\s*(\d{1,2})\s*\/\s*(\d{4})\s*,?\s*(\d{1,2})\s*:\s*(\d{2})\s*(AM|PM)\s*$/i);if(!c)return null;let r=parseInt(c[4],10);const s=parseInt(c[5],10),u=parseInt(c[1],10)-1,v=parseInt(c[2],10),S=parseInt(c[3],10),w=c[6].toUpperCase();w==="PM"&&r!==12&&(r+=12),w==="AM"&&r===12&&(r=0);const p=new Date(S,u,v,r,s,0,0);return Number.isNaN(p.getTime())?null:p.getTime()}function m(y,l){if(!y||!l)return!1;const c=_(y),r=_(l);return c!==null&&r!==null?c<r:y<l}function f(y,l){const c=_(y);return c!==null&&c<l}let h={scheduleEnabled:!1,startDate:""};function b(){const y=document.querySelector('[name="schedule_enabled"]'),l=document.querySelector('[name="start_date"]'),c=document.querySelector('[name="end_date"]');h={scheduleEnabled:!!(y&&y.checked),startDate:l&&l.value?String(l.value):"",endDate:c&&c.value?String(c.value):""}}function E(){setTimeout(()=>{F(),U(),$(),O(),G(),z(),k(),x(),W(),H(),V(),K(),I(),P(),ae(),b()},50)}function k(){const y=document.querySelector('[name="schedule_enabled"]'),l=document.querySelector('[name="start_date"]'),c=document.querySelector('[name="end_date"]');if(!y||!l||!c)return;function r(){return a(new Date)}function s(){const S=y.checked,w=r(),p=Date.now();if(!S){l.removeAttribute("min"),l.removeAttribute("max"),c.removeAttribute("min"),c.removeAttribute("max");return}if(c.value&&f(c.value,p)){y.checked=!1,l.value="",c.value="",u(!1),b(),L();return}l.value&&f(l.value,p)?l.removeAttribute("min"):l.min=w,c.value?(l.max=c.value,l.value&&m(c.value,l.value)&&(l.value="")):l.removeAttribute("max"),l.value?(c.min=l.value,c.value&&m(c.value,l.value)&&(c.value="")):(c.min=w,c.value&&f(c.value,p)&&(c.value=""))}function u(S){const w=l.closest(".notifal-field-wrapper"),p=c.closest(".notifal-field-wrapper");if(S){l.disabled=!1,c.disabled=!1,l.removeAttribute("readonly"),c.removeAttribute("readonly"),w&&w.classList.remove("notifal-hidden"),p&&p.classList.remove("notifal-hidden");return}l.disabled=!0,c.disabled=!0,l.setAttribute("readonly","readonly"),c.setAttribute("readonly","readonly"),w&&w.classList.add("notifal-hidden"),p&&p.classList.add("notifal-hidden")}function v(){u(y.checked),s(),L()}y.addEventListener("change",()=>{v()}),l.addEventListener("change",()=>{y.checked&&(c.value&&l.value&&m(c.value,l.value)&&(c.value=""),s(),L())}),c.addEventListener("change",()=>{y.checked&&(l.value&&c.value&&m(c.value,l.value)&&(l.value=""),s(),L())}),v()}function x(){const y=document.querySelector('[name="notifal_campaign_id"]'),l=document.querySelector('[name="schedule_enabled"]'),c=document.querySelector('[name="start_date"]'),r=document.querySelector('[name="end_date"]'),s=document.getElementById("notifal-campaign-schedule-info");if(!y||!l||!c||!r||!s)return;let u=!!l.checked,v=c.value||"",S=r.value||"",w=0;const p={};function M(){const oe=parseInt(y.value||"0",10);return Number.isNaN(oe)?0:oe}function j(oe,le){const ue=s.querySelector(".notifal-campaign-schedule-info-lead"),fe=s.querySelector(".notifal-campaign-schedule-info-detail");ue&&(ue.textContent=oe),fe&&(fe.textContent=le)}function B(){return M()>0}function J(){u=!!l.checked,v=c.value||"",S=r.value||"",l.checked=!1,l.disabled=!0,c.disabled=!0,r.disabled=!0,c.setAttribute("readonly","readonly"),r.setAttribute("readonly","readonly");const oe=c.closest(".notifal-field-wrapper"),le=r.closest(".notifal-field-wrapper");oe&&oe.classList.add("notifal-hidden"),le&&le.classList.add("notifal-hidden"),s.classList.remove("notifal-hidden"),j(t("campaign_schedule_intro"),t("campaign_schedule_loading_detail")),l.setAttribute("title",t("campaign_schedule_toggle_title"))}function Y(){s.classList.add("notifal-hidden"),l.removeAttribute("title"),l.disabled=!1,c.disabled=!1,r.disabled=!1,c.removeAttribute("readonly"),r.removeAttribute("readonly"),l.checked=u,c.value=v,r.value=S,l.dispatchEvent(new Event("change",{bubbles:!0}))}async function ie(oe){if(p[oe])return p[oe];const le=++w,ue=new FormData;ue.append("action","notifal_get_campaign_data"),ue.append("nonce",typeof NotifalOnPageAjax<"u"&&NotifalOnPageAjax.nonce&&NotifalOnPageAjax.nonce.get_campaign_data||""),ue.append("campaign_id",String(oe));const fe=typeof NotifalOnPageAjax<"u"?NotifalOnPageAjax.ajax_url:"",pe=await(await fetch(fe,{method:"POST",body:ue,credentials:"same-origin"})).json();return le!==w||!pe||!pe.success||!pe.data?null:(p[oe]=pe.data,pe.data)}async function se(){const oe=M();if(oe<=0){Y(),L();return}J();const le=await ie(oe);if(!le||!B()){const Oe=y.options[y.selectedIndex],_t=Oe?Oe.textContent:"";j(t("campaign_schedule_intro"),t("preview_schedule_campaign",{campaign_name:_t})),L();return}const ue=le.campaign_name||"",fe=le.formatted_start_date||"",ve=le.formatted_end_date||"";let pe="";fe&&ve?pe=`${fe} - ${ve}`:fe?pe=fe:ve&&(pe=ve);const je=t("preview_schedule_campaign",{campaign_name:ue}),mt=pe?`${je} (${pe})`:je;j(t("campaign_schedule_intro"),mt),L()}l.addEventListener("change",function(){B()&&J()}),y.addEventListener("change",function(){se()}),se()}function I(){const y=document.querySelector('[name="show_timing"]');if(y){const l=y.value;Z();const c=o.showTiming[l];if(c&&c.fields&&c.fields.forEach(r=>{X(r)}),l==="custom"){const r=document.querySelector('[name="custom_trigger_type"]');if(r){const s=r.value,u=o.showTiming.custom.subFields;s==="multiple_triggers"?ee("custom_trigger_delay"):X("custom_trigger_delay"),u&&u[s]&&u[s].forEach(v=>{X(v)})}}}}function P(){const y=document.querySelector('[name="show_frequency"]');if(y){const l=y.value;R();const c=o.showFrequency[l];c&&c.fields&&c.fields.forEach(r=>{X(r)})}}function F(){const y=document.querySelector('[name="show_timing"]');if(!y)return;function l(){const c=y.value,r=o.showTiming[c];r&&(Z(),r.fields.forEach(s=>{X(s)}),c==="custom"&&r.subFields&&N())}y.addEventListener("change",l),l()}function N(){const y=document.querySelector('[name="custom_trigger_type"]');if(!y)return;function l(){const c=y.value,r=o.showTiming.custom.subFields;te(),c==="multiple_triggers"?ee("custom_trigger_delay"):X("custom_trigger_delay"),r&&r[c]&&r[c].forEach(s=>{X(s)})}y.addEventListener("change",l),l()}function U(){const y=document.querySelector('[name="display_duration"]');if(!y)return;function l(){const c=y.value,r=o.displayDuration[c];r&&(C(),r.fields.forEach(s=>{X(s)}))}y.addEventListener("change",l),l()}function $(){const y=document.querySelector('[name="show_frequency"]');if(!y)return;function l(){const c=y.value,r=o.showFrequency[c];r&&(R(),r.fields.forEach(s=>{X(s)}))}y.addEventListener("change",l),l()}function O(){const y=document.querySelector('[name="allow_retrigger_after_hide"]');if(!y)return;function l(){const c=y.checked,r=["retrigger_delay_seconds","max_retrigger_per_page"];c?r.forEach(X):r.forEach(ee)}y.addEventListener("change",l),l()}function G(){const y=document.querySelector('[name="pause_on_tab_inactive"]'),l=document.querySelector('[name="resume_on_tab_active"]');if(y&&l){let r=function(){y.checked?X("resume_on_tab_active"):(ee("resume_on_tab_active"),l.checked=!1)};var c=r;y.addEventListener("change",r),r()}}function z(){const y=document.querySelector('[name="enable_priority"]'),l=document.querySelector(".notifal-priority-level-field");if(y&&l){let r=function(){y.checked?(l.classList.remove("notifal-pro-hidden"),l.classList.add("notifal-pro-visible")):(l.classList.remove("notifal-pro-visible"),l.classList.add("notifal-pro-hidden"))};var c=r;y.addEventListener("change",r),r()}}function W(){document.querySelectorAll(['[name="show_timing"]','[name="delay_seconds"]','[name="scroll_percentage"]','[name="idle_seconds"]','[name="custom_trigger_type"]','[name="custom_js_event"]','[name="custom_element_selector"]','[name="visibility_element_selector"]','[name="visibility_threshold"]','[name="custom_js_condition"]','[name="multiple_triggers_config"]','[name="custom_trigger_delay"]','[name="display_duration"]','[name="auto_hide_seconds"]','[name="persistent_duration"]','[name="show_frequency"]','[name="custom_frequency_days"]','[name="max_shows_per_session"]','[name="allow_retrigger_after_hide"]','[name="retrigger_delay_seconds"]','[name="max_retrigger_per_page"]','[name="schedule_enabled"]','[name="start_date"]','[name="end_date"]','[name="notifal_campaign_id"]'].join(",")).forEach(l=>{l.addEventListener("change",L),l.addEventListener("input",L)}),L()}function A(y){const l=document.querySelector('[name="show_timing"]')?.value||"immediate";let c=t("preview_loading");switch(l){case"immediate":c=t("preview_trigger_immediate");break;case"delay":const r=document.querySelector('[name="delay_seconds"]')?.value||3;c=t("preview_trigger_delay",{seconds:r});break;case"scroll":const s=document.querySelector('[name="scroll_percentage"]')?.value||50;c=t("preview_trigger_scroll",{percentage:s});break;case"exit_intent":c=t("preview_trigger_exit");break;case"idle":const u=document.querySelector('[name="idle_seconds"]')?.value||30;c=t("preview_trigger_idle",{seconds:u});break;case"custom":const v=document.querySelector('[name="custom_trigger_type"]')?.value||"javascript_event",S=document.querySelector('[name="custom_trigger_delay"]')?.value||0;let w="";switch(v){case"javascript_event":const p=document.querySelector('[name="custom_js_event"]')?.value||"click",M=document.querySelector('[name="custom_element_selector"]')?.value||"";w=`JavaScript ${p} event${M?` on ${M}`:""}`;break;case"element_visible":const j=document.querySelector('[name="visibility_element_selector"]')?.value||"",B=document.querySelector('[name="visibility_threshold"]')?.value||50;w=`Element visibility: ${j} (${B}% threshold)`;break;case"custom_condition":w="Custom JavaScript condition";break;case"multiple_triggers":w="Multiple custom triggers";break;default:w="Custom trigger condition"}S>0?c=t("preview_trigger_custom_delay",{condition:w,delay:S}):c=t("preview_trigger_custom",{condition:w});break}y.textContent=c}function d(y){const l=document.querySelector('[name="display_duration"]')?.value||"until_dismissed";let c=t("preview_loading");switch(l){case"until_dismissed":c=t("preview_duration_until_dismissed");break;case"auto_hide":const r=document.querySelector('[name="auto_hide_seconds"]')?.value||5;c=t("preview_duration_auto_hide",{seconds:r});break;case"persistent":const s=document.querySelector('[name="persistent_duration"]')?.value||0;s==0?c=t("preview_duration_persistent_forever"):c=t("preview_duration_persistent",{seconds:s});break}y.textContent=c}function T(y){const l=document.querySelector('[name="show_frequency"]')?.value||"once_per_session";let c=t("preview_loading");switch(l){case"always":c=t("preview_frequency_always");break;case"once_per_session":c=t("preview_frequency_once_session");break}y.textContent=c}function q(y){return!y||typeof y!="string"?"":y.replace("T"," ")}function g(y){const l=document.querySelector('[name="notifal_campaign_id"]'),c=l&&l.value?String(l.value):"0",r=parseInt(c,10);if(!isNaN(r)&&r>0){const M=l.options[l.selectedIndex],j=M?M.textContent.trim():"";y.textContent=t("preview_schedule_campaign",{campaign_name:j});return}const s=document.querySelector('[name="schedule_enabled"]');if(!(s&&s.checked)){y.textContent=t("preview_schedule_none");return}const v=document.querySelector('[name="start_date"]'),S=document.querySelector('[name="end_date"]'),w=q(v?v.value:""),p=q(S?S.value:"");if(w&&p){y.textContent=t("preview_schedule_active",{start_date:w,end_date:p});return}if(w){y.textContent=t("preview_schedule_start_only",{start_date:w});return}if(p){y.textContent=t("preview_schedule_end_only",{end_date:p});return}y.textContent=t("preview_schedule_pending_dates")}function L(){const y=document.getElementById("notifal-timing-preview-trigger"),l=document.getElementById("notifal-timing-preview-schedule"),c=document.getElementById("notifal-timing-preview-duration"),r=document.getElementById("notifal-timing-preview-frequency");y&&A(y),l&&g(l),c&&d(c),r&&T(r)}function D(){let y=!0;const l=[],c=document.querySelector('[name="show_timing"]')?.value,r=document.querySelector('[name="delay_seconds"]');c==="delay"&&(!r||!r.value||r.value<0)&&(l.push(t("validation_delay_required")),y=!1);const s=document.querySelector('[name="scroll_percentage"]');c==="scroll"&&(!s||!s.value||s.value<1||s.value>100)&&(l.push(t("validation_scroll_required")),y=!1);const u=document.querySelector('[name="idle_seconds"]');c==="idle"&&(!u||!u.value||u.value<5)&&(l.push(t("validation_idle_required")),y=!1);const v=document.querySelector('[name="display_duration"]')?.value,S=document.querySelector('[name="auto_hide_seconds"]');v==="auto_hide"&&(!S||!S.value||S.value<1)&&(l.push(t("validation_auto_hide_required")),y=!1);const w=document.querySelector('[name="persistent_duration"]');if(v==="persistent"&&(!w||!w.value||w.value<0)&&(l.push(t("validation_persistent_required")),y=!1),document.querySelector('[name="show_frequency"]')?.value,c==="custom"){const J=document.querySelector('[name="custom_trigger_type"]')?.value;if(!J)l.push(t("validation_custom_trigger_type_required")),y=!1;else switch(J){case"javascript_event":const Y=document.querySelector('[name="custom_element_selector"]')?.value;(!Y||Y.trim()==="")&&(l.push(t("validation_custom_element_selector_required")),y=!1);break;case"element_visible":const ie=document.querySelector('[name="visibility_element_selector"]')?.value;(!ie||ie.trim()==="")&&(l.push(t("validation_visibility_element_required")),y=!1);break;case"custom_condition":const se=document.querySelector('[name="custom_js_condition"]')?.value;(!se||se.trim()==="")&&(l.push(t("validation_custom_condition_required")),y=!1);break}}const p=document.querySelector('[name="notifal_campaign_id"]'),M=p&&p.value?String(p.value):"0",j=parseInt(M,10);if(!(!isNaN(j)&&j>0)){const J=document.querySelector('[name="schedule_enabled"]'),Y=document.querySelector('[name="start_date"]'),ie=!!(J&&J.checked),se=Y&&Y.value?String(Y.value):"",oe=Date.now();ie&&se&&f(se,oe)&&(h.scheduleEnabled&&h.startDate===se||(l.push(t("validation_start_must_be_future")),y=!1))}return y?document.querySelectorAll(".notifal-timing-validation-error").forEach(Y=>Y.remove()):Q(l),y}function H(){if(!(document.querySelector(".notifal-timing-settings form")||document.querySelector("form")))return;document.querySelectorAll(['[name="show_timing"]','[name="delay_seconds"]','[name="scroll_percentage"]','[name="idle_seconds"]','[name="custom_trigger_type"]','[name="custom_js_event"]','[name="custom_element_selector"]','[name="visibility_element_selector"]','[name="visibility_threshold"]','[name="custom_js_condition"]','[name="multiple_triggers_config"]','[name="custom_trigger_delay"]','[name="display_duration"]','[name="auto_hide_seconds"]','[name="persistent_duration"]','[name="show_frequency"]','[name="custom_frequency_days"]','[name="max_shows_per_session"]','[name="allow_retrigger_after_hide"]','[name="retrigger_delay_seconds"]','[name="max_retrigger_per_page"]'].join(",")).forEach(c=>{c.addEventListener("change",D),c.addEventListener("blur",D)})}function Q(y){if(document.querySelectorAll(".notifal-timing-validation-error").forEach(s=>s.remove()),y.length===0)return;const c=document.createElement("div");c.className="notifal-timing-validation-error notifal-error-message",c.innerHTML=`
            <div class="notifal-error-header">
                <span class="notifal-error-icon"></span>
                <strong>${t("validation_errors_found",{count:y.length})}</strong>
            </div>
            <ul class="notifal-error-list">
                ${y.map(s=>`<li>${s}</li>`).join("")}
            </ul>
        `;const r=document.querySelector(".notifal-timing-settings");r&&r.insertBefore(c,r.firstChild)}function V(){document.querySelectorAll(".notifal-field-help").forEach(l=>{const c=l.getAttribute("data-help");if(!c)return;const r=document.createElement("div");r.className="notifal-help-tooltip",r.textContent=c,l.addEventListener("mouseenter",()=>{l.appendChild(r),setTimeout(()=>r.classList.add("show"),100)}),l.addEventListener("mouseleave",()=>{r.classList.remove("show"),setTimeout(()=>r.remove(),200)})})}function Z(){["delay_seconds","scroll_percentage","idle_seconds","custom_trigger_type","custom_trigger_delay","custom-trigger-help"].forEach(l=>{ee(l)}),te()}function te(){["custom_js_event","custom_element_selector","visibility_element_selector","visibility_threshold","custom_js_condition","multiple_triggers_config"].forEach(l=>{ee(l)})}function C(){["auto_hide_seconds","persistent_duration"].forEach(l=>{ee(l)})}function R(){["custom_frequency_days","max_shows_per_session","clear_session_on_logout"].forEach(l=>{ee(l)})}function X(y){let l=document.querySelector(`[name="${y}"]`);if(l||(l=document.getElementById(y)),!l)return;const c=l.closest(".notifal-field-wrapper");c&&c.classList.remove("notifal-hidden"),(l.tagName==="INPUT"||l.tagName==="SELECT"||l.tagName==="TEXTAREA")&&(l.disabled=!1,l.removeAttribute("readonly"))}function ee(y){let l=document.querySelector(`[name="${y}"]`);if(l||(l=document.getElementById(y)),!l)return;const c=l.closest(".notifal-field-wrapper");c&&c.classList.add("notifal-hidden"),(l.tagName==="INPUT"||l.tagName==="SELECT"||l.tagName==="TEXTAREA")&&(l.disabled=!0,l.setAttribute("readonly","readonly"))}function ae(){["prevent_multiple_instances","enable_priority","priority_level"].forEach(l=>{const c=document.querySelector(`[name="${l}"]`);if(c){const r=c.closest(".notifal-field-wrapper");r&&r.classList.remove("notifal-hidden"),c.disabled=!1,c.removeAttribute("readonly")}})}function K(){const y=["show_timing","delay_seconds","scroll_percentage","idle_seconds","custom_trigger_type","custom_js_event","custom_element_selector","visibility_element_selector","visibility_threshold","custom_js_condition","multiple_triggers_config","custom_trigger_delay","display_duration","auto_hide_seconds","persistent_duration","show_frequency","max_shows_per_session","respect_user_dismissal","require_user_consent","pause_on_tab_inactive","resume_on_tab_active","prevent_multiple_instances","enable_priority","priority_level","clear_session_on_logout","allow_retrigger_after_hide","retrigger_delay_seconds","max_retrigger_per_page","schedule_enabled","start_date","end_date"],l=document.querySelector('[name="notifal_campaign_id"]'),c=l&&l.value&&l.value!=="0";y.forEach(r=>{const s=document.querySelector(`[name="${r}"]`);if(s){if(c&&(r==="schedule_enabled"||r==="start_date"||r==="end_date"))return;s.disabled=!1,s.removeAttribute("readonly")}})}function ne(){K(),ae();function y(p,M,j=!1){const B=document.querySelector(`[name="${p}"]`);if(!B)return M;const J=B.disabled;B.disabled=!1;let Y;return j?Y=B.checked:Y=B.value||M,B.disabled=J,Y}const l=document.querySelector('[name="notifal_campaign_id"]'),c=l&&l.value&&l.value!=="0";let r=y("schedule_enabled",!1,!0),s=r?y("start_date",""):"",u=r?y("end_date",""):"";const v=_(u),S=Date.now();!c&&r&&v!==null&&v<S&&(r=!1,s="",u="");const w={show_timing:y("show_timing","immediate"),delay_seconds:parseInt(y("delay_seconds","3")),scroll_percentage:parseInt(y("scroll_percentage","50")),idle_seconds:parseInt(y("idle_seconds","30")),schedule_enabled:r,start_date:s,end_date:u,_pro_validation:function(){if(typeof window.NotifalOnPageConfig<"u"&&window.NotifalOnPageConfig.is_pro_active)return!0;const M=["scroll","exit_intent","idle","custom"],j=this.show_timing;return M.includes(j)?(typeof dt<"u"&&dt("error",`Show Timing option "${{scroll:"On Scroll",exit_intent:"On Exit Intent",idle:"After User Idle",custom:"Custom Trigger"}[j]}" requires Notifal Pro. Please upgrade or select a different option.`),!1):!0},custom_trigger_type:y("custom_trigger_type","javascript_event"),custom_js_event:y("custom_js_event","click"),custom_element_selector:y("custom_element_selector",""),visibility_element_selector:y("visibility_element_selector",""),visibility_threshold:parseInt(y("visibility_threshold","50")),custom_js_condition:y("custom_js_condition",""),multiple_triggers_config:y("multiple_triggers_config",""),custom_trigger_delay:parseFloat(y("custom_trigger_delay","0")),display_duration:y("display_duration","until_dismissed"),auto_hide_seconds:parseInt(y("auto_hide_seconds","15")),persistent_duration:parseInt(y("persistent_duration","0")),show_frequency:y("show_frequency","once_per_session"),max_shows_per_session:parseInt(y("max_shows_per_session","1")),respect_user_dismissal:y("respect_user_dismissal",!0,!0),allow_retrigger_after_hide:y("allow_retrigger_after_hide",!1,!0),retrigger_delay_seconds:parseInt(y("retrigger_delay_seconds","20")),max_retrigger_per_page:parseInt(y("max_retrigger_per_page","2")),require_user_consent:y("require_user_consent",!1,!0),pause_on_tab_inactive:y("pause_on_tab_inactive",!1,!0),resume_on_tab_active:y("resume_on_tab_active",!1,!0),prevent_multiple_instances:y("prevent_multiple_instances",!0,!0),enable_priority:y("enable_priority",!1,!0),priority_level:y("priority_level",5,!1),clear_session_on_logout:y("clear_session_on_logout",!0,!0)};return w._pro_validation()?(delete w._pro_validation,w):null}function re(y){if(!y.timing_settings)return;let l=y.timing_settings;if(l.display&&l.duration&&l.frequency&&l.advanced&&(l={show_timing:l.display.type||"immediate",delay_seconds:l.display.delay||3,scroll_percentage:l.display.scroll_percentage||50,idle_seconds:l.display.idle_seconds||30,custom_trigger_type:l.display.custom_trigger?.type||"javascript_event",custom_js_event:l.display.custom_trigger?.js_event||"click",custom_element_selector:l.display.custom_trigger?.element_selector||"",visibility_element_selector:l.display.custom_trigger?.visibility_element||"",visibility_threshold:l.display.custom_trigger?.visibility_threshold||50,custom_js_condition:l.display.custom_trigger?.custom_condition||"",multiple_triggers_config:l.display.custom_trigger?.multiple_triggers||"",custom_trigger_delay:l.display.custom_trigger?.delay||0,display_duration:l.duration.type||"until_dismissed",auto_hide_seconds:l.duration.auto_hide_seconds||15,persistent_duration:l.duration.persistent_duration||0,show_frequency:l.frequency.type||"once_per_session",max_shows_per_session:l.frequency.max_per_session||1,respect_user_preferences:l.advanced.respect_user_preferences||!1,pause_on_tab_inactive:l.advanced.pause_on_tab_inactive||!1,resume_on_tab_active:l.advanced.resume_on_tab_active||!1,prevent_multiple_instances:l.advanced.prevent_multiple_instances||!0,clear_session_on_logout:l.advanced.clear_session_on_logout||!0}),l.show_timing){const c=document.querySelector('[name="show_timing"]');c&&(c.value=l.show_timing)}if(l.delay_seconds!==void 0){const c=document.querySelector('[name="delay_seconds"]');c&&(c.value=l.delay_seconds)}if(l.scroll_percentage!==void 0){const c=document.querySelector('[name="scroll_percentage"]');c&&(c.value=l.scroll_percentage)}if(l.idle_seconds!==void 0){const c=document.querySelector('[name="idle_seconds"]');c&&(c.value=l.idle_seconds)}if(l.schedule_enabled!==void 0){const c=document.querySelector('[name="schedule_enabled"]');c&&(c.checked=l.schedule_enabled)}if(l.start_date!==void 0){const c=document.querySelector('[name="start_date"]');c&&(c.value=i(String(l.start_date)))}if(l.end_date!==void 0){const c=document.querySelector('[name="end_date"]');c&&(c.value=i(String(l.end_date)))}if(l.custom_trigger_type){const c=document.querySelector('[name="custom_trigger_type"]');c&&(c.value=l.custom_trigger_type)}if(l.custom_js_event){const c=document.querySelector('[name="custom_js_event"]');c&&(c.value=l.custom_js_event)}if(l.custom_element_selector){const c=document.querySelector('[name="custom_element_selector"]');c&&(c.value=l.custom_element_selector)}if(l.visibility_element_selector){const c=document.querySelector('[name="visibility_element_selector"]');c&&(c.value=l.visibility_element_selector)}if(l.visibility_threshold!==void 0){const c=document.querySelector('[name="visibility_threshold"]');c&&(c.value=l.visibility_threshold)}if(l.custom_js_condition){const c=document.querySelector('[name="custom_js_condition"]');c&&(c.value=l.custom_js_condition)}if(l.multiple_triggers_config){const c=document.querySelector('[name="multiple_triggers_config"]');c&&(c.value=l.multiple_triggers_config)}if(l.custom_trigger_delay!==void 0){const c=document.querySelector('[name="custom_trigger_delay"]');c&&(c.value=l.custom_trigger_delay)}if(l.display_duration){const c=document.querySelector('[name="display_duration"]');c&&(c.value=l.display_duration)}if(l.auto_hide_seconds!==void 0){const c=document.querySelector('[name="auto_hide_seconds"]');c&&(c.value=l.auto_hide_seconds)}if(l.persistent_duration!==void 0){const c=document.querySelector('[name="persistent_duration"]');c&&(c.value=l.persistent_duration)}if(l.show_frequency){const c=document.querySelector('[name="show_frequency"]');c&&(c.value=l.show_frequency)}if(l.custom_frequency_days!==void 0){const c=document.querySelector('[name="custom_frequency_days"]');c&&(c.value=l.custom_frequency_days)}if(l.max_shows_per_session!==void 0){const c=document.querySelector('[name="max_shows_per_session"]');c&&(c.value=l.max_shows_per_session)}if(l.respect_user_dismissal!==void 0){const c=document.querySelector('[name="respect_user_dismissal"]');c&&(c.checked=l.respect_user_dismissal)}if(l.allow_retrigger_after_hide!==void 0){const c=document.querySelector('[name="allow_retrigger_after_hide"]');c&&(c.checked=l.allow_retrigger_after_hide)}if(l.retrigger_delay_seconds!==void 0){const c=document.querySelector('[name="retrigger_delay_seconds"]');c&&(c.value=l.retrigger_delay_seconds)}if(l.max_retrigger_per_page!==void 0){const c=document.querySelector('[name="max_retrigger_per_page"]');c&&(c.value=l.max_retrigger_per_page)}if(l.require_user_consent!==void 0){const c=document.querySelector('[name="require_user_consent"]');c&&(c.checked=l.require_user_consent)}if(l.pause_on_tab_inactive!==void 0){const c=document.querySelector('[name="pause_on_tab_inactive"]');c&&(c.checked=l.pause_on_tab_inactive)}if(l.resume_on_tab_active!==void 0){const c=document.querySelector('[name="resume_on_tab_active"]');c&&(c.checked=l.resume_on_tab_active)}if(l.prevent_multiple_instances!==void 0){const c=document.querySelector('[name="prevent_multiple_instances"]');c&&(c.checked=l.prevent_multiple_instances)}if(l.enable_priority!==void 0){const c=document.querySelector('[name="enable_priority"]');c&&(c.checked=l.enable_priority)}if(l.priority_level!==void 0){const c=document.querySelector('[name="priority_level"]');c&&(c.value=l.priority_level)}if(l.clear_session_on_logout!==void 0){const c=document.querySelector('[name="clear_session_on_logout"]');c&&(c.checked=l.clear_session_on_logout)}setTimeout(()=>{["show_timing","display_duration","show_frequency","custom_trigger_type","require_user_consent","pause_on_tab_inactive","resume_on_tab_active","prevent_multiple_instances","enable_priority","priority_level","clear_session_on_logout","schedule_enabled"].forEach(r=>{const s=document.querySelector(`[name="${r}"]`);s&&s.dispatchEvent(new Event("change",{bubbles:!0}))}),b(),L()},100)}window.NotifalTiming={init:E,generateConfig:ne,validate:function(){return D()},updatePreview:function(){W()},populateSettings:re,captureScheduleValidationSnapshot:b},window.validateTimingFields=D,window.generateTimingConfig=ne,window.populateTimingSettings=re,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",E):setTimeout(E,100);function de(){const y=document.querySelector('input[name="timing_settings"]');if(!(!y||!y.value))try{const l=JSON.parse(y.value);l&&typeof l=="object"&&re({timing_settings:l})}catch{return}}document.addEventListener("DOMContentLoaded",function(){const y=document.querySelector('[data-tab="timing"]'),l=document.querySelector("#tab-timing");y&&l&&l.classList.contains("active")&&setTimeout(de,100),window.addEventListener("hashchange",function(){window.location.hash==="#timing"&&setTimeout(de,100)})}),setTimeout(()=>{de(),P()},500)})();class $t{constructor(){this.init()}init(){document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{this.initBehaviorSettings(),this.loadSavedBehaviorSettings()}):setTimeout(()=>{this.initBehaviorSettings(),this.loadSavedBehaviorSettings()},100),document.addEventListener("DOMContentLoaded",()=>{this.setupTabActivation()}),setTimeout(()=>this.loadExistingBehaviorSettings(),500)}initBehaviorSettings(){this.initTabBadgeConditionalVisibility(),this.initCloseOnFormSubmitDelayVisibility(),this.initCloseOnActionButtonClickDelayVisibility()}initCloseOnFormSubmitDelayVisibility(){const t=document.querySelector('input[name="close_on_form_submit"]'),e=document.querySelector(".notifal-close-on-form-submit-delay-container");if(!t||!e)return;const a=()=>{const n=t.checked;e.classList.toggle("notifal-hidden",!n);const i=e.querySelector('input[name="close_on_form_submit_delay_seconds"]');i&&(i.disabled=!n,n?i.removeAttribute("readonly"):i.setAttribute("readonly","readonly"))};a(),t.addEventListener("change",a)}initCloseOnActionButtonClickDelayVisibility(){const t=document.querySelector('input[name="close_on_action_button_click"]'),e=document.querySelector(".notifal-close-on-action-button-click-delay-container");if(!t||!e)return;const a=()=>{const n=t.checked;e.classList.toggle("notifal-hidden",!n);const i=e.querySelector('input[name="close_on_action_button_click_delay_seconds"]');i&&(i.disabled=!n,n?i.removeAttribute("readonly"):i.setAttribute("readonly","readonly"))};a(),t.addEventListener("change",a)}initTabBadgeConditionalVisibility(){const t=document.querySelector('input[name="enable_tab_badge"]'),e=document.querySelector(".notifal-tab-badge-settings-container");t&&e&&(e.classList.toggle("notifal-hidden",!t.checked),t.addEventListener("change",function(){e.classList.toggle("notifal-hidden",!this.checked)}));const a=document.querySelector('select[name="tab_badge_display_mode"]');a&&(this.updateAutoClearVisibility(a.value),a.addEventListener("change",m=>{this.updateAutoClearVisibility(m.target.value)}));const n=document.querySelector('select[name="tab_badge_style"]');n&&(this.updateTabBadgeCustomTextVisibility(n.value),this.updateTabBadgeColorVisibility(n.value),this.updateTabBadgeTextPositionVisibility(n.value),n.addEventListener("change",m=>{this.updateTabBadgeCustomTextVisibility(m.target.value),this.updateTabBadgeColorVisibility(m.target.value),this.updateTabBadgeTextPositionVisibility(m.target.value)}));const i=document.querySelector('select[name="tab_badge_animation_style"]');i&&(this.updateTabBadgeAnimationSpeedOptions(i.value),i.addEventListener("change",m=>{this.updateTabBadgeAnimationSpeedOptions(m.target.value)}));const _=document.querySelector('input[name="tab_badge_title_animation"]');_&&(this.updateTabBadgeAnimationSettingsVisibility(_.checked),_.addEventListener("change",m=>{this.updateTabBadgeAnimationSettingsVisibility(m.target.checked)}))}updateTabBadgeCustomTextVisibility(t){const e=document.querySelector('[name="tab_badge_custom_text"]');if(!e)return;const a=e.closest(".notifal-field-wrapper");a&&(t==="custom"||t==="both"?(a.classList.remove("notifal-hidden"),e.disabled=!1,e.removeAttribute("readonly")):(a.classList.add("notifal-hidden"),e.disabled=!0,e.setAttribute("readonly","readonly")))}updateTabBadgeColorVisibility(t){const e=document.querySelector('[name="tab_badge_color"]');if(!e)return;const a=e.closest(".notifal-field-wrapper");a&&(t==="count"||t==="both"?(a.classList.remove("notifal-hidden"),e.disabled=!1,e.removeAttribute("readonly")):(a.classList.add("notifal-hidden"),e.disabled=!0,e.setAttribute("readonly","readonly")))}updateTabBadgeTextPositionVisibility(t){const e=document.querySelector(".notifal-tab-badge-text-position-field");e&&(t==="custom"||t==="both"?e.classList.remove("notifal-hidden"):e.classList.add("notifal-hidden"))}updateAutoClearVisibility(t){const e=document.querySelector('[name="tab_badge_auto_clear_on_focus"]');if(!e)return;const a=e.closest(".notifal-field-wrapper");a&&(t==="always"?(a.classList.add("notifal-hidden"),e.disabled=!0):(a.classList.remove("notifal-hidden"),e.disabled=!1))}updateTabBadgeAnimationSettingsVisibility(t){const e=document.querySelector(".notifal-tab-badge-animation-settings-container");e&&(t?e.classList.remove("notifal-hidden"):e.classList.add("notifal-hidden"))}updateTabBadgeAnimationSpeedOptions(t){const e=document.querySelector('select[name="tab_badge_animation_speed"]');if(!e)return;const a=e.value;e.innerHTML="";let n;if(t==="marquee"?n=[{value:"fast",label:"Fast (50ms)"},{value:"normal",label:"Normal (100ms)"},{value:"slow",label:"Slow (150ms)"}]:n=[{value:"fast",label:"Fast (0.5s)"},{value:"normal",label:"Normal (1s)"},{value:"slow",label:"Slow (2s)"}],n.forEach(i=>{const _=document.createElement("option");_.value=i.value,_.textContent=i.label,e.appendChild(_)}),a&&n.find(i=>i.value===a))e.value=a;else{const i=e.getAttribute("data-current-value");i&&n.find(_=>_.value===i)&&(e.value=i)}}getBehaviorFields(){return["dismiss_on_click_outside","dismiss_on_escape_key","dismiss_on_scroll","enable_aria_labels","focus_trap","announce_to_screen_reader","prevent_page_scroll","close_on_form_submit","close_on_form_submit_delay_seconds","close_on_action_button_click","close_on_action_button_click_delay_seconds","maintain_state_on_refresh","mobile_optimized","swipe_to_dismiss","touch_friendly","prevent_zoom_on_touch","enable_tab_badge","tab_badge_display_mode","tab_badge_style","tab_badge_color","tab_badge_custom_text","tab_badge_title_animation","tab_badge_text_position","tab_badge_animation_style","tab_badge_animation_speed","tab_badge_auto_clear_on_focus"]}populateBehaviorSettings(t){if(!t)return;this.getBehaviorFields().forEach(a=>{if(t[a]!==void 0){const n=document.querySelector(`[name="${a}"]`);n&&(n.type==="checkbox"?n.checked=t[a]:n.value=t[a])}}),setTimeout(()=>{this.updateConditionalVisibility()},100)}updateConditionalVisibility(){const t=document.querySelector('select[name="tab_badge_display_mode"]');t&&this.updateAutoClearVisibility(t.value);const e=document.querySelector('select[name="tab_badge_style"]');e&&(this.updateTabBadgeCustomTextVisibility(e.value),this.updateTabBadgeColorVisibility(e.value),this.updateTabBadgeTextPositionVisibility(e.value));const a=document.querySelector('input[name="enable_tab_badge"]'),n=document.querySelector(".notifal-tab-badge-settings-container");a&&n&&n.classList.toggle("notifal-hidden",!a.checked);const i=document.querySelector('input[name="tab_badge_title_animation"]');i&&this.updateTabBadgeAnimationSettingsVisibility(i.checked);const _=document.querySelector('input[name="close_on_form_submit"]'),m=document.querySelector(".notifal-close-on-form-submit-delay-container");if(_&&m){m.classList.toggle("notifal-hidden",!_.checked);const b=m.querySelector('input[name="close_on_form_submit_delay_seconds"]');b&&(b.disabled=!_.checked,_.checked?b.removeAttribute("readonly"):b.setAttribute("readonly","readonly"))}const f=document.querySelector('input[name="close_on_action_button_click"]'),h=document.querySelector(".notifal-close-on-action-button-click-delay-container");if(f&&h){h.classList.toggle("notifal-hidden",!f.checked);const b=h.querySelector('input[name="close_on_action_button_click_delay_seconds"]');b&&(b.disabled=!f.checked,f.checked?b.removeAttribute("readonly"):b.setAttribute("readonly","readonly"))}}saveBehaviorSettings(){const t={};this.getBehaviorFields().forEach(n=>{const i=document.querySelector(`[name="${n}"]`);i&&(i.type==="checkbox"?t[n]=i.checked:t[n]=i.value)});const a=document.querySelector('[name="behavior_settings"]');a&&(a.value=JSON.stringify(t))}getBehaviorConfig(){const t={};return this.getBehaviorFields().forEach(a=>{const n=document.querySelector(`[name="${a}"]`);n&&(n.type==="checkbox"?t[a]=n.checked:t[a]=n.value)}),t}validateBehaviorSettings(){const t=[],e={};return this.getBehaviorConfig(),{valid:t.length===0,message:t.join(". "),errors:e}}resetBehaviorSettings(){const t={dismiss_on_click_outside:!1,dismiss_on_escape_key:!1,dismiss_on_scroll:!1,enable_aria_labels:!0,focus_trap:!1,announce_to_screen_reader:!1,prevent_page_scroll:!1,close_on_form_submit:!0,close_on_form_submit_delay_seconds:5,close_on_action_button_click:!1,close_on_action_button_click_delay_seconds:5,maintain_state_on_refresh:!0,mobile_optimized:!0,swipe_to_dismiss:!0,touch_friendly:!0,prevent_zoom_on_touch:!0,enable_tab_badge:!1,tab_badge_display_mode:"inactive_only",tab_badge_style:"count",tab_badge_color:"#dc3545",tab_badge_custom_text:"",tab_badge_title_animation:!0,tab_badge_text_position:"prefix",tab_badge_animation_style:"flash",tab_badge_animation_speed:"normal",tab_badge_auto_clear_on_focus:!0};Object.keys(t).forEach(e=>{const a=document.querySelector(`[name="${e}"]`);a&&(a.type==="checkbox"?a.checked=t[e]:a.value=t[e])}),this.saveBehaviorSettings()}loadExistingBehaviorSettings(){const t=document.querySelector('input[name="behavior_settings"]');if(!(!t||!t.value))try{const e=JSON.parse(t.value);e&&typeof e=="object"&&this.populateBehaviorSettings(e)}catch(e){console.warn("Error parsing behavior settings:",e)}}loadSavedBehaviorSettings(){const t=document.querySelector('input[name="behavior_settings"]');if(t&&t.value)try{const e=JSON.parse(t.value);e&&typeof window.NotifalBehaviorSettings<"u"&&window.NotifalBehaviorSettings.populateBehaviorSettings&&window.NotifalBehaviorSettings.populateBehaviorSettings(e)}catch(e){console.warn("Error parsing saved behavior settings:",e)}}initBehaviorTab(){this.loadExistingBehaviorSettings(),this.initTabBadgeConditionalVisibility()}setupTabActivation(){const t=document.querySelector('[data-tab="behavior"]'),e=document.querySelector("#tab-behavior");t&&e&&e.classList.contains("active")&&setTimeout(()=>this.initBehaviorTab(),100),window.addEventListener("hashchange",()=>{window.location.hash==="#behavior"&&setTimeout(()=>this.initBehaviorTab(),100)})}}const me=new $t;window.NotifalBehaviorSettings={initBehaviorSettings:()=>me.initBehaviorSettings(),populateBehaviorSettings:o=>me.populateBehaviorSettings(o),loadSavedBehaviorSettings:()=>me.loadSavedBehaviorSettings(),saveBehaviorSettings:()=>me.saveBehaviorSettings(),getBehaviorConfig:()=>me.getBehaviorConfig(),validateBehaviorSettings:()=>me.validateBehaviorSettings(),resetBehaviorSettings:()=>me.resetBehaviorSettings(),updateConditionalVisibility:()=>me.updateConditionalVisibility()};window.populateBehaviorSettings=o=>me.populateBehaviorSettings(o);window.saveBehaviorSettings=()=>me.saveBehaviorSettings();window.updateBehaviorConditionalVisibility=()=>me.updateConditionalVisibility();(function(){function o(d,T={}){const q=typeof NotifalOnPageStrings<"u"&&NotifalOnPageStrings[d]?NotifalOnPageStrings[d]:d;return Object.keys(T).reduce((g,L)=>g.replace(`{${L}}`,T[L]),q)}let t=!1,e=null,a="",n=null;function i(){if(e=document.querySelector(".notifal-save-notification-btn"),!e){console.warn("Save button not found");return}if(a=e.textContent,n=document.querySelector(".notifal-notification-form"),!n){console.warn("Notification form not found");return}e.addEventListener("click",_),n.addEventListener("submit",m),n.addEventListener("keydown",f),h()}function _(d){d.preventDefault(),d.stopPropagation(),b()}function m(d){return d.preventDefault(),d.stopPropagation(),!1}function f(d){d.key==="Enter"&&d.target.tagName!=="TEXTAREA"&&(d.preventDefault(),d.stopPropagation())}function h(){document.querySelectorAll(".notifal-tabs button").forEach(T=>{T.addEventListener("click",q=>{q.preventDefault(),q.stopPropagation()})})}async function b(){if(t)return;z(!0),P();const d=await x();if(!d.valid){z(!1),I(d.errors),A("error",d.message);return}window.NotifalAppearanceSettings&&window.NotifalAppearanceSettings.clearAllIrrelevantDistances&&window.NotifalAppearanceSettings.clearAllIrrelevantDistances();const T=await F();if(!T){z(!1),A("error",o("invalid_json"));return}$(T)}async function E(d,T=500){const q=Date.now();return new Promise(g=>{const L=()=>{if(d.filter(H=>typeof window[H]=="function").length===d.length){g();return}if(Date.now()-q>=T){console.warn("Notifal: Timeout waiting for functions:",d.filter(H=>typeof window[H]!="function")),g();return}setTimeout(L,50)};L()})}async function k(d=1e3){const T=Date.now();return new Promise(q=>{const g=()=>{const L=document.getElementById("notifal-display-rule-list"),D=L&&L.querySelectorAll(".notifal-rule-row").length>0,H=typeof window.saveRulesData=="function",Q=window.notifalRulesReady===!0;if(D||H||Q){q(!0);return}if(Date.now()-T>=d){console.warn("Notifal: Timeout waiting for rules to be ready"),q(!1);return}setTimeout(g,100)};g()})}async function x(){const d=[],T={},q=["validateContentSourceSettings","validateTimingFields"];q.filter(V=>typeof window[V]=="function").length<q.length&&await E(q,150);const D=document.querySelector('[name="notif_title"]')?.value?.trim();if(D?D.length>255&&(d.push(o("title_too_long")),T.notif_title=o("title_too_long")):(d.push(o("title_required")),T.notif_title=o("title_required")),U().length===0){const V=o("labels_required");d.push(V),T.notifal_labels=V}if(typeof window.NotifalTemplateSelection<"u"&&window.NotifalTemplateSelection.validateTemplateSelection){const V=document.querySelector('[name="notif_enabled"]');V&&(V.checked||V.value),window.NotifalTemplateSelection.validateTemplateSelection(!1)}if(typeof window.validateContentSourceSettings=="function")try{if(!window.validateContentSourceSettings()){const V="Content source settings validation failed.";d.push(V),T.content_source_settings=V}}catch(V){console.warn("Content source validation error:",V)}if(typeof window.validateTimingFields=="function")try{if(!window.validateTimingFields()){const V="Timing settings validation failed.";d.push(V),T.timing_settings=V}}catch(V){console.warn("Timing validation error:",V)}if(typeof window.NotifalAppearanceSettings<"u"&&window.NotifalAppearanceSettings.validateCustomCSS)try{const V=document.querySelector('[name="custom_css"]'),Z=V?V.value:"",te=N()||"NEW",C=window.NotifalAppearanceSettings.validateCustomCSS(Z,te);if(!C.valid){const R="Custom CSS contains invalid selectors. Please ensure all selectors start with the required prefix.";d.push(R),T.custom_css=R,window.NotifalAppearanceSettings.showCSSValidationErrors&&window.NotifalAppearanceSettings.showCSSValidationErrors(C.errors)}}catch(V){console.warn("CSS validation error:",V)}else console.warn("CSS validation function not available");if(typeof window.validateDisplayRules=="function")try{const V=window.validateDisplayRules();V.isValid||(d.push(V.message),T.display_rules_data=V.message)}catch(V){console.warn("Display rules validation error:",V)}else console.warn("Display rules validation function not available");return["appearance_settings","behavior_settings","timing_settings","content_source_settings","display_rules_data"].forEach(V=>{const Z=document.querySelector(`[name="${V}"]`);if(Z&&Z.value)try{JSON.parse(Z.value)}catch{const C=`${V.replace(/_/g," ")} contains invalid data`;d.push(C),T[V]=C}}),{valid:d.length===0,message:d.join(". "),errors:T}}function I(d){Object.keys(d).forEach(T=>{let q=document.querySelector(`[name="${T}"]`);if(T==="notifal_labels"){const g=document.querySelector("#notifal_labels_container");if(g){g.classList.add("notifal-field-error");let L=g.parentNode.querySelector(".notifal-field-error-container");L||(L=document.createElement("div"),L.className="notifal-field-error-container",g.parentNode.appendChild(L));let D=L.querySelector(".notifal-field-error-message");D||(D=document.createElement("div"),D.className="notifal-field-error-message",L.appendChild(D)),D.textContent=d[T],D.style.display="block"}}else if(T==="notifal_template_id"){const g=document.querySelector(".notifal-template-selection-container")||document.querySelector("[data-template-selection]")||document.querySelector(".notifal-templates-section");if(g){g.classList.add("notifal-field-error");let L=g.parentNode.querySelector(".notifal-field-error-container");L||(L=document.createElement("div"),L.className="notifal-field-error-container",g.parentNode.appendChild(L));let D=L.querySelector(".notifal-field-error-message");D||(D=document.createElement("div"),D.className="notifal-field-error-message",L.appendChild(D)),D.textContent=d[T],D.style.display="block"}}else if(T==="display_rules_data"){const g=document.querySelector(".notifal-display-rules-settings");if(g){g.classList.add("notifal-field-error");let L=g.querySelector(".notifal-field-error-container");L||(L=document.createElement("div"),L.className="notifal-field-error-container",g.appendChild(L));let D=L.querySelector(".notifal-field-error-message");D||(D=document.createElement("div"),D.className="notifal-field-error-message",L.appendChild(D)),D.textContent=d[T],D.style.display="block"}}else if(q){q.classList.add("notifal-field-error");let g=q.parentNode.querySelector(".notifal-field-error-container");g||(g=document.createElement("div"),g.className="notifal-field-error-container",q.parentNode.appendChild(g));let L=g.querySelector(".notifal-field-error-message");L||(L=document.createElement("div"),L.className="notifal-field-error-message",g.appendChild(L)),L.textContent=d[T],L.style.display="block"}})}function P(){document.querySelectorAll(".notifal-field-error").forEach(d=>{d.classList.remove("notifal-field-error")}),document.querySelectorAll(".notifal-field-error-container").forEach(d=>{d.remove()}),document.querySelectorAll(".notifal-field-error-message").forEach(d=>{d.style.display="none"})}async function F(){try{const d=new FormData;d.append("action","notifal_save_notification"),d.append("nonce",NotifalOnPageAjax.nonce.save_notification);const T=N();T&&d.append("notification_id",T);const q=["notif_title","notif_enabled","content_source_type","template_id","template_content","rule_combination_logic"],g=document.querySelector('input[name="notifal_template_id"]:checked'),L=g!==null;g&&d.append("template_id",g.value),q.forEach(C=>{const R=document.querySelector(`[name="${C}"]`);if(R)if(R.type==="checkbox"){let X=R.checked?"1":"0";C==="notif_enabled"&&X==="1"&&!L&&(X="0",R.checked=!1),d.append(C,X)}else d.append(C,R.value||"")});const D=U();D.length>0&&D.forEach(C=>{d.append("notifal_labels[]",C)});const H=["saveContentSourceSettings","generateTimingConfig","saveRulesData","saveAppearanceSettings","saveBehaviorSettings"];H.filter(C=>typeof window[C]=="function").length<H.length&&await E(H,200),await k();let V=!1;if(typeof window.saveRulesData=="function")try{window.saveRulesData(),V=!0}catch(C){console.error("Notifal: Rules data save error via window:",C)}if(!V&&typeof saveRulesData=="function")try{saveRulesData(),V=!0}catch(C){console.error("Notifal: Rules data save error direct call:",C)}if(!V&&typeof NotifalOnPage<"u"&&typeof NotifalOnPage.saveRulesData=="function")try{NotifalOnPage.saveRulesData(),V=!0}catch(C){console.error("Notifal: Rules data save error via NotifalOnPage:",C)}if(!V){console.error("Notifal: saveRulesData function is not available through any method!");try{const C=document.getElementById("notifal-display-rule-list");if(C){const R={};C.querySelectorAll(".notifal-rule-row").forEach((ae,K)=>{const ne=ae.dataset.type,re=ae.dataset.ruleData;if(ne&&re)try{const de=JSON.parse(re);R[ne]=de}catch(de){console.error("Notifal: Fallback error parsing rule data:",de)}});let ee=document.querySelector('input[name="display_rules_data"]');if(!ee){ee=document.createElement("input"),ee.type="hidden",ee.name="display_rules_data";const ae=document.querySelector(".notifal-display-rules-settings");ae&&ae.appendChild(ee)}ee.value=JSON.stringify(R),V=!0}}catch(C){console.error("Notifal: Fallback rules data collection failed:",C)}}const Z=document.querySelector('input[name="display_rules_data"]');if(Z)try{const C=JSON.parse(Z.value)}catch(C){console.error("Notifal: Error parsing final rules data:",C)}else console.error("Notifal: display_rules_data input not found after save attempt!");if(typeof window.saveContentSourceSettings=="function")try{window.saveContentSourceSettings()}catch(C){console.warn("Content source settings save error:",C)}if(typeof window.generateTimingConfig=="function")try{const C=window.generateTimingConfig();if(C===null)return null;if(C){const R=document.querySelector('[name="timing_settings"]');R&&(R.value=JSON.stringify(C))}}catch(C){console.warn("Timing settings save error:",C)}if(typeof window.saveAppearanceSettings=="function")try{window.saveAppearanceSettings()}catch(C){console.warn("Appearance settings save error:",C)}if(typeof window.saveBehaviorSettings=="function")try{window.saveBehaviorSettings()}catch(C){console.warn("Behavior settings save error:",C)}return["appearance_settings","behavior_settings","timing_settings","content_source_settings","display_rules_data"].forEach(C=>{const R=document.querySelector(`[name="${C}"]`);R&&R.value?d.append(C,R.value):d.append(C,"{}")}),d}catch(d){return console.error("Error preparing save data:",d),null}}function N(){const T=new URLSearchParams(window.location.search).get("id");if(T)return T;const q=document.querySelector('input[name="notification_id"]');return q?q.value:null}function U(){const d=[];return document.querySelectorAll(".notifal-label-badge.active").forEach(q=>{const g=q.dataset.slug;g&&d.push(g)}),d}function $(d){fetch(NotifalOnPageAjax.ajax_url,{method:"POST",body:d,credentials:"same-origin"}).then(T=>{if(!T.ok)throw new Error(`HTTP ${T.status}: ${T.statusText}`);return T.json()}).then(T=>{T.success?O(T.data):G(T.data?.message||o("save_error"))}).catch(T=>{console.error("Notifal: Save request error:",T),G(o("network_error"))}).finally(()=>{z(!1)})}function O(d){const q=document.querySelector('input[name="notifal_template_id"]:checked')!==null,g=document.querySelector('[name="notif_enabled"]'),L=g?!g.checked&&g.value!=="1":!0;let D=d.message||o("save_success");L&&!q&&(D=o("draft_saved_no_template")),A("success",D),d.post_id&&!N()&&W(d.post_id),d.redirect_url&&setTimeout(()=>{window.location.href=d.redirect_url},1500),document.dispatchEvent(new CustomEvent("notifal:notification:saved",{detail:d}))}function G(d){A("error",d)}function z(d){t=d,e&&(d?(e.disabled=!0,e.textContent=o("saving"),e.classList.add("notifal-loading")):(e.disabled=!1,e.textContent=a,e.classList.remove("notifal-loading")))}function W(d){let T=document.querySelector('input[name="notification_id"]');T||(T=document.createElement("input"),T.type="hidden",T.name="notification_id",n?.appendChild(T)),T.value=d;const q=new URL(window.location);q.searchParams.set("id",d),window.history.replaceState({},"",q)}function A(d,T){typeof window.NotifalUtils<"u"&&window.NotifalUtils.showMessage?window.NotifalUtils.showMessage(T,d,5e3):typeof NotifalUtils<"u"&&NotifalUtils.showMessage?NotifalUtils.showMessage(T,d,5e3):console.warn(`Toast message (${d}): ${T}`)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{setTimeout(i,100)}):setTimeout(i,100)})();(function(){const o={toast:"Small notification that slides in from the side. Perfect for quick confirmations and alerts.",popup:"Modal dialog in the center with backdrop. Ideal for important messages and forms.",topbar:"Full-width banner sliding from top. Great for site-wide announcements and promotions.",floating:"Fixed circular element that stays in position. Perfect for chat widgets and help buttons.",inline:"Content within page flow like banners. Integrates naturally with your content.",corner:"Small badge in corner for notifications count. Minimal visual impact but noticeable."};typeof notifalL10n<"u"&&notifalL10n.displayTypes&&Object.keys(o).forEach(n=>{notifalL10n.displayTypes[n]?.conciseDescription&&(o[n]=notifalL10n.displayTypes[n].conciseDescription)});function t(){const n=document.getElementById("notification_display_type");if(!n)return;const i=e(n);i&&(n.addEventListener("change",function(){a(this.value,i)}),a(n.value,i))}function e(n){const i=n.closest(".notifal-field-wrapper");if(i){const _=i.querySelector(".notifal-dynamic-tooltip");if(_)return _}return document.querySelector(".notifal-dynamic-tooltip")}function a(n,i=null){if(i||(i=document.querySelector(".notifal-dynamic-tooltip")),!i)return;const _=i.querySelector(".notifal-tooltip-content");if(!_)return;const m=o[n];m&&(i.classList.add("notifal-tooltip-bounce"),_.style.opacity="0.3",_.style.transform="scale(0.9)",_.style.color="#6366f1",_.style.transition="all 0.15s ease",_.innerHTML=m,setTimeout(()=>{_.style.opacity="1",_.style.transform="scale(1)",_.style.color="",i.classList.add("notifal-tooltip-updated")},150),setTimeout(()=>{i.classList.remove("notifal-tooltip-bounce","notifal-tooltip-updated")},600))}document.addEventListener("DOMContentLoaded",function(){t()}),setTimeout(function(){const n=document.querySelector(".notifal-dynamic-tooltip");n&&!n.hasAttribute("data-initialized")&&(n.setAttribute("data-initialized","true"),t())},500),window.NotifalDynamicTooltips={initDynamicTooltips:t,updateTooltipContent:a,displayTypeDescriptions:o,testTooltip:function(n){a(n)}}})();
