import { apiList, apiCreate, toast } from './api.js'; export function initCreate(){ const btn=document.getElementById('btn-new'), dlg=document.getElementById('createDialog'), form=document.getElementById('createForm'), fields=document.getElementById('createFields'), hint=document.getElementById('createHint'); if(!btn||!dlg||!form||!fields) return; const curTab=()=>{ const a=document.querySelector('nav [data-tab].bg-sky-50')||document.querySelector('nav [data-tab]'); return a?a.getAttribute('data-tab'):'templates'; }; btn.onclick = async ()=>{ fields.innerHTML=''; const tab=curTab(); const name=document.createElement('input'); name.type='text'; name.required=true; name.placeholder='Name*'; name.className='w-full border rounded-lg px-3 py-2'; name.id='f-name'; fields.appendChild(name); async function addSel(id,label,res){ const sel=document.createElement('select'); sel.id=id; sel.className='w-full border rounded-lg px-3 py-2'; sel.innerHTML=``; const data=await apiList(res); (data||[]).forEach(t=>{ const o=document.createElement('option'); o.value=t.id; o.textContent=`#${t.id} ยท ${t.name||''}`; sel.appendChild(o); }); fields.appendChild(sel); } if(tab==='sections') await addSel('f-template','Template','templates'); if(tab==='blocks') await addSel('f-section','Section','sections'); if(tab==='snippets') await addSel('f-block','Block','blocks'); hint.textContent=`Neues ${tab} anlegen`; dlg.showModal(); form.onsubmit=async(e)=>{ e.preventDefault(); const payload={ name:(document.getElementById('f-name')?.value||'').trim() }; if(!payload.name) return; if(tab==='snippets') payload.content=''; else payload.html=''; if(tab==='sections') payload.template_id=document.getElementById('f-template')?.value||null; if(tab==='blocks') payload.section_id =document.getElementById('f-section')?.value ||null; if(tab==='snippets') payload.block_id =document.getElementById('f-block')?.value ||null; const r=await apiCreate(tab,payload); if(r&&r.id){ dlg.close(); toast('Erstellt',true); window.loadList && window.loadList(tab); } else { toast('Erstellen fehlgeschlagen',false,{duration:3000}); console.error('Create failed',r); } }; }; const cancel=document.getElementById('createCancel'); cancel && (cancel.onclick=()=>dlg.close()); }