import{S as q}from"./sortable.esm-D-EvzYhP.js";import{g as S,r as A}from"./api-DZ3cXm1m.js";document.addEventListener("DOMContentLoaded",()=>{const l=window.menuEditConfig;if(!l)return;const m=document.getElementById("menuItemsTree");if(!m)return;const T=document.getElementById("menuItemModal"),v=new bootstrap.Modal(T),r=document.getElementById("menuItemForm"),f=r.querySelector('[name="link_type"]'),w=r.querySelector("#linkTargetFields");q.create(m,{handle:".drag-handle",animation:150,onEnd:()=>y()});async function y(){const e=[...m.children].map((t,a)=>({id:parseInt(t.dataset.itemId),parent_id:t.dataset.parentId?parseInt(t.dataset.parentId):null,sort_order:a}));await k(l.routes.reorder,"POST",{items:e})}m.addEventListener("click",async e=>{const t=e.target.closest("button[data-action]");if(!t)return;const a=t.closest("li"),s=parseInt(a.dataset.itemId),o=t.dataset.action;if(o==="edit")$(a);else if(o==="delete"){if(!confirm(l.translations.confirm_delete))return;await k(l.routes.itemDestroy.replace(":item",s),"DELETE"),a.remove()}else if(o==="indent"){const n=a.previousElementSibling;if(!n||n.dataset.parentId)return;a.dataset.parentId=n.dataset.itemId,a.classList.add("ms-4"),await y()}else o==="outdent"&&(a.dataset.parentId="",a.classList.remove("ms-4"),await y())}),document.querySelectorAll("button[data-add-type]").forEach(e=>{e.addEventListener("click",()=>{r.reset(),r.querySelector('[name="item_id"]').value="",f.value=e.dataset.addType,_(e.dataset.addType,{}),v.show()})}),f.addEventListener("change",()=>_(f.value,{}));function _(e,t){let a="";e==="url"?a=l.locales.map(s=>`
                <div class="mb-2">
                    <label class="form-label small">URL (${s})</label>
                    <input type="text" name="link_target[url][${s}]" class="form-control" value="${i(t.url&&t.url[s]||"")}">
                </div>`).join(""):e==="route"?a=`<div class="mb-2">
                <label class="form-label">${h(l.translations.route_picker_label||"Route name")}</label>
                <input type="text" id="routeSearch" class="form-control" autocomplete="off"
                    placeholder="${i(l.translations.route_picker_placeholder||"Type to search routes...")}"
                    value="${i(t.route||"")}">
                <input type="hidden" name="link_target[route]" value="${i(t.route||"")}">
                <ul id="routeResults" class="list-group mt-1"></ul>
                <div class="form-text small">${h(l.translations.route_picker_help||"Pick a registered named route (store.* etc.).")}</div>
            </div>`:e==="post"?a=`
                <div class="mb-2">
                    <label class="form-label">Post type</label>
                    <select name="link_target[post_type]" class="form-select" id="postTypeSel">
                        <option value="announcement">Announcement</option>
                        <option value="kb_article">KB Article</option>
                        <option value="blog_post">Blog Post</option>
                    </select>
                </div>
                <div class="mb-2">
                    <label class="form-label">Search</label>
                    <input type="text" id="postSearch" class="form-control" placeholder="Type to search...">
                    <input type="hidden" name="link_target[post_id]" value="${i(t.post_id||"")}">
                    <ul id="postResults" class="list-group mt-1"></ul>
                </div>`:e==="product_group"?a=`<div class="mb-2">
                <input type="text" id="groupSearch" class="form-control" placeholder="Search groups...">
                <input type="hidden" name="link_target[group_id]" value="${i(t.group_id||"")}">
                <ul id="groupResults" class="list-group mt-1"></ul>
            </div>`:e==="product"&&(a=`<div class="mb-2">
                <input type="text" id="productSearch" class="form-control" placeholder="Search products...">
                <input type="hidden" name="link_target[product_id]" value="${i(t.product_id||"")}">
                <ul id="productResults" class="list-group mt-1"></ul>
            </div>`),w.innerHTML=a,E()}function E(){g("#postSearch","#postResults",'[name="link_target[post_id]"]',()=>{var e;return(e=document.getElementById("postTypeSel"))==null?void 0:e.value}),g("#groupSearch","#groupResults",'[name="link_target[group_id]"]',()=>"product_group"),g("#productSearch","#productResults",'[name="link_target[product_id]"]',()=>"product"),g("#routeSearch","#routeResults",'[name="link_target[route]"]',()=>"route")}function g(e,t,a,s){const o=r.querySelector(e),n=r.querySelector(t),d=r.querySelector(a);if(!o)return;let u;o.addEventListener("input",()=>{clearTimeout(u),u=setTimeout(async()=>{const p=new URL(l.routes.search,window.location.origin);p.searchParams.set("type",s()),p.searchParams.set("q",o.value);const b=await fetch(p,{headers:{Authorization:`Bearer ${S()}`,Accept:"application/json"}});if(!b.ok)return;const L=await b.json();n.innerHTML=(L.data||[]).map(c=>`
                    <li class="list-group-item list-group-item-action" data-id="${i(c.id)}" data-label="${i(c.label)}" style="cursor:pointer;">
                        ${h(c.label)} <small class="text-muted">${h(c.sub_label)}</small>
                    </li>`).join(""),n.querySelectorAll("li").forEach(c=>{c.addEventListener("click",()=>{d.value=c.dataset.id,o.value=c.dataset.label||c.textContent.trim(),n.innerHTML=""})})},300)})}r.addEventListener("submit",async e=>{e.preventDefault();const t=new FormData(r),a=t.get("item_id"),s=a?l.routes.itemUpdate.replace(":item",a):l.routes.itemStore,o=a?"PUT":"POST",n={};for(const[u,p]of t.entries())u!=="item_id"&&I(n,u,p);n.target_blank=n.target_blank?1:0,n.is_mega=n.is_mega?1:0,(await k(s,o,n)).ok?(v.hide(),window.location.reload()):alert("Save failed")});function I(e,t,a){const s=t.replace(/\]/g,"").split("[");let o=e;for(let n=0;n<s.length-1;n++){const d=s[n];o[d]=o[d]??{},o=o[d]}o[s[s.length-1]]=a}function $(e){r.reset(),r.querySelector('[name="item_id"]').value=e.dataset.itemId;const t=e.dataset.linkType;f.value=t;const a=e.dataset.linkTarget?JSON.parse(e.dataset.linkTarget):{};_(t,a),r.querySelector('[name="icon"]').value=e.dataset.icon||"",r.querySelector('[name="target_blank"]').checked=e.dataset.targetBlank==="1",r.querySelector('[name="visible_when"]').value=e.dataset.visibleWhen||"always",r.querySelector('[name="is_mega"]').checked=e.dataset.isMega==="1",r.querySelector('[name="mega_columns"]').value=e.dataset.megaColumns||1,v.show()}function h(e){const t=document.createElement("div");return t.textContent=e??"",t.innerHTML}function i(e){return String(e??"").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}async function k(e,t,a=null){const s={method:t,headers:{Authorization:`Bearer ${S()}`,Accept:"application/json","Content-Type":"application/json"}};a&&(s.body=JSON.stringify(a));let o=await fetch(e,s);if(o.status===401){const n=await A();n&&(s.headers.Authorization=`Bearer ${n}`,o=await fetch(e,s))}return{ok:o.ok,status:o.status,body:await o.json().catch(()=>null)}}});
