
document.addEventListener("DOMContentLoaded",()=>{

const tree=document.getElementById("coaTree")

tree.addEventListener("click",(e)=>{

let row=e.target.closest(".coa-row")
if(!row) return

let node=row.parentElement

if(e.target.classList.contains("add")){
  addInline(node)
  return
}

if(e.target.classList.contains("edit")){
  alert("edit "+node.dataset.id)
  return
}

if(e.target.classList.contains("del")){
  if(confirm("حذف الحساب؟")){
    node.remove()
  }
  return
}

node.classList.toggle("open")

})

function addInline(node){

if(node.querySelector(".inline-form")) return

let form=document.createElement("div")
form.className="inline-form"
form.innerHTML=`
<input placeholder="الكود">
<input placeholder="اسم الحساب">
<button class="save">حفظ</button>
`

node.appendChild(form)

form.querySelector(".save").onclick=()=>{

let li=document.createElement("li")
li.className="coa-node new-node"
li.innerHTML=`
<div class="coa-row">
<span class="toggle"></span>
<span class="code">0000</span>
<span class="name">حساب جديد</span>
<span class="actions"></span>
</div>`

let ul=node.querySelector("ul")
if(!ul){
 ul=document.createElement("ul")
 node.appendChild(ul)
}

ul.appendChild(li)

li.classList.add("highlight")
setTimeout(()=>li.classList.remove("highlight"),2000)

form.remove()

}

}

document.getElementById("coaSearch").addEventListener("input",(e)=>{

let q=e.target.value.toLowerCase()

document.querySelectorAll(".coa-node").forEach(n=>{

let name=n.innerText.toLowerCase()

n.style.display=name.includes(q)?"block":"none"

})

})

})
