let dashboard = document.getElementById("dashboard");
let marketplace = document.getElementById("marketplace");

let layoutData = JSON.parse(localStorage.getItem("layout")) || [];

function saveLayout(){
  localStorage.setItem("layout", JSON.stringify(layoutData));
}

function setLayout(mode){
  dashboard.className = mode;
}

function addSection(content){
  let div = document.createElement("div");
  div.className = "section";
  div.innerHTML = content;
  dashboard.appendChild(div);

  interact(div)
    .draggable({
      listeners:{
        move(event){
          let x = (parseFloat(div.getAttribute('x'))||0)+event.dx;
          let y = (parseFloat(div.getAttribute('y'))||0)+event.dy;
          div.style.transform = `translate(${x}px,${y}px)`;
          div.setAttribute('x',x);
          div.setAttribute('y',y);
        }
      }
    })
    .resizable({
      edges:{left:true,right:true,bottom:true,top:true}
    })
    .on('resizemove', event=>{
      div.style.width = event.rect.width+'px';
      div.style.height = event.rect.height+'px';
    });

  layoutData.push(content);
  saveLayout();
}

function openMarketplace(){
  marketplace.classList.toggle("hidden");
}

function loadWidgets(){
  let widgets = [
    {name:"Clock", html:"<h3>Clock</h3><div id='clock'></div>"},
    {name:"Snake", html:"<iframe src='https://playsnake.org'></iframe>"},
    {name:"Calculator", html:"<iframe src='https://www.desmos.com/scientific'></iframe>"}
  ];

  widgets.forEach(w=>{
    let btn = document.createElement("button");
    btn.innerText = w.name;
    btn.onclick = ()=>addSection(w.html);
    marketplace.appendChild(btn);
  });
}

function loadLayout(){
  layoutData.forEach(c=>addSection(c));
}

setInterval(()=>{
  let el = document.getElementById("clock");
  if(el) el.innerText = new Date().toLocaleTimeString();
},1000);

loadWidgets();
loadLayout();
