let editMode = false;
let data;

document.getElementById("editToggle").onclick = () => {
  editMode = !editMode;
  document.body.classList.toggle("edit", editMode);
};

fetch("sections.php").then(r=>r.json()).then(d=>{
  data=d;
  render();
});

function render(){
  const dash=document.getElementById("dashboard");
  dash.innerHTML="";

  data.sections.sort((a,b)=>a.order-b.order).forEach(sec=>{
    const el=document.createElement("div");
    el.className="section";
    el.style.gridColumn="span "+sec.cols;
    el.style.gridRow="span "+sec.rows;
    el.dataset.id=sec.id;
    el.draggable=editMode;

    const title=document.createElement("div");
    title.className="section-title";
    title.innerText=sec.name;
    el.appendChild(title);

    const grid=document.createElement("div");
    grid.className="tings";

    sec.tings.sort((a,b)=>a.order-b.order).forEach(t=>{
      const te=document.createElement("div");
      te.className="ting";
      te.innerText=t.name;
      te.dataset.id=t.id;
      te.draggable=editMode;

      te.onclick=()=>handleOpen(t);

      grid.appendChild(te);
    });

    el.appendChild(grid);
    dash.appendChild(el);
  });

  enableDrag();
}

function handleOpen(t){
  if(editMode) return;

  if(t.target==="overlay"){
    openOverlay(t.url);
  } else {
    window.open(t.url,"_blank");
  }
}

function openOverlay(url){
  const o=document.getElementById("overlay");
  const c=document.getElementById("overlayContent");
  c.innerHTML=`<iframe src="${url}"></iframe>`;
  o.classList.remove("hidden");
}

function closeOverlay(){
  document.getElementById("overlay").classList.add("hidden");
}

let dragEl=null;

function enableDrag(){
  document.querySelectorAll(".ting").forEach(el=>{
    el.ondragstart=e=>{ dragEl=el; };
  });

  document.querySelectorAll(".tings").forEach(container=>{
    container.ondragover=e=>{
      e.preventDefault();
      const target=e.target.closest(".ting");
      if(!target||target===dragEl) return;
      container.insertBefore(dragEl,target);
    };
  });

  document.addEventListener("drop", save);
}

function save(){
  const sections=[...document.querySelectorAll(".section")];

  sections.forEach((sec,i)=>{
    const secData=data.sections.find(s=>s.id===sec.dataset.id);
    secData.order=i;

    const tings=[...sec.querySelectorAll(".ting")];
    tings.forEach((t,j)=>{
      const td=secData.tings.find(x=>x.id===t.dataset.id);
      td.order=j;
    });
  });

  fetch("save.php",{
    method:"POST",
    headers:{"Content-Type":"application/json"},
    body:JSON.stringify(data)
  });
}
