let grid = null;
let isEditMode = false;
let config = {};

const defaultConfig = {
  sections: [{
    id: "main",
    title: "Main",
    color: "#00ffcc",
    bgImage: "",
    customCSS: "",
    x: 0, y: 0, w: 6, h: 4,
    tings: [{ name: "The Hub", url: "https://idontbyte.com", icon: "🌐", tint: "", target: "_blank" }]
  }]
};

function loadConfig() {
  const saved = localStorage.getItem('tingsConfig');
  config = saved ? JSON.parse(saved) : JSON.parse(JSON.stringify(defaultConfig));
}

function saveConfig() {
  localStorage.setItem('tingsConfig', JSON.stringify(config));
}

function initGrid() {
  if (grid) grid.destroy(true);
  const gridEl = document.getElementById('grid');
  if (!gridEl) return;
  gridEl.innerHTML = '';

  config.sections.forEach(sec => {
    const bg = sec.bgImage ? `background-image:url('${sec.bgImage}');background-size:cover;` : '';
    gridEl.innerHTML += `
      <div class="grid-stack-item" data-gs-id="${sec.id}" data-gs-x="${sec.x}" data-gs-y="${sec.y}" data-gs-w="${sec.w}" data-gs-h="${sec.h}">
        <div class="grid-stack-item-content" style="${bg} ${sec.customCSS||''}">
          <div class="section-header" style="color:${sec.color}">
            <span>${sec.title}</span>
            ${isEditMode ? `<button class="edit-section-btn" data-id="${sec.id}">⚙️</button>` : ''}
          </div>
          <div class="tings-grid" id="tings-${sec.id}"></div>
        </div>
      </div>`;
  });

  grid = GridStack.init({
    cellHeight: 100,
    margin: 12,
    draggable: { handle: '.section-header' },
    resizable: isEditMode,
    disableDrag: !isEditMode,
    disableResize: !isEditMode,
    column: 12,
    animate: true
  });

  config.sections.forEach(s => renderTings(s.id));
  setupSortable();
}

function renderTings(sectionId) {
  const container = document.getElementById(`tings-${sectionId}`);
  if (!container) return;
  container.innerHTML = '';
  const section = config.sections.find(s => s.id === sectionId);
  if (!section) return;

  section.tings.forEach((ting) => {
    const div = document.createElement('div');
    div.className = 'ting';
    div.innerHTML = `<div style="font-size:2.8rem">${ting.icon || '🔗'}</div><span>${ting.name}</span>`;
    div.onclick = () => { if (!isEditMode) handleTingClick(ting); };
    container.appendChild(div);
  });

  if (isEditMode) {
    const add = document.createElement('div');
    add.className = 'ting';
    add.innerHTML = `<div style="font-size:2.8rem">+</div><span>Add Ting</span>`;
    add.onclick = () => addNewTing(sectionId);
    container.appendChild(add);
  }
}

function setupSortable() {
  document.querySelectorAll('.tings-grid').forEach(el => {
    new Sortable(el, {
      group: 'tings',
      animation: 150,
      onEnd: (evt) => {
        const from = evt.from.id.replace('tings-', '');
        const to = evt.to.id.replace('tings-', '');
        const secFrom = config.sections.find(s => s.id === from);
        const secTo = config.sections.find(s => s.id === to);
        if (!secFrom || !secTo) return;
        const [moved] = secFrom.tings.splice(evt.oldIndex, 1);
        secTo.tings.splice(evt.newIndex, 0, moved);
        saveConfig();
        renderTings(from);
        if (from !== to) renderTings(to);
      }
    });
  });
}

function handleTingClick(ting) {
  window.open(ting.url, ting.target || '_blank');
}

function addNewTing(sectionId) {
  const name = prompt("Ting Name:");
  if (!name) return;
  const url = prompt("URL:", "https://");
  if (!url) return;
  const section = config.sections.find(s => s.id === sectionId);
  if (section) {
    section.tings.push({name, url, icon: "🔗", tint: "", target: "_blank"});
    renderTings(sectionId);
    saveConfig();
  }
}

// Attach all button listeners safely
function attachListeners() {
  const editBtn = document.getElementById('edit-btn');
  if (editBtn) {
    editBtn.onclick = () => {
      isEditMode = !isEditMode;
      editBtn.textContent = `Edit Mode: ${isEditMode ? 'ON' : 'OFF'}`;
      console.log('Edit mode toggled to:', isEditMode);
      initGrid();
    };
  }

  const addSectionBtn = document.getElementById('add-section-btn');
  if (addSectionBtn) {
    addSectionBtn.onclick = () => {
      config.sections.push({id: 'sec-' + Date.now(), title: 'New Section', color: '#ff8800', bgImage: '', customCSS: '', x:0, y:999, w:5, h:3, tings:[]});
      initGrid();
      saveConfig();
      console.log('New section added');
    };
  }

  const exportBtn = document.getElementById('export-btn');
  if (exportBtn) {
    exportBtn.onclick = () => {
      const dataStr = JSON.stringify(config, null, 2);
      const blob = new Blob([dataStr], {type: "application/json"});
      const a = document.createElement("a");
      a.href = URL.createObjectURL(blob);
      a.download = "tings-config.json";
      a.click();
      console.log('Config exported');
    };
  }

  const importBtn = document.getElementById('import-btn');
  if (importBtn) {
    importBtn.onclick = () => document.getElementById('import-file').click();
  }

  const importFile = document.getElementById('import-file');
  if (importFile) {
    importFile.onchange = (e) => {
      const file = e.target.files[0];
      if (!file) return;
      const reader = new FileReader();
      reader.onload = ev => {
        try {
          config = JSON.parse(ev.target.result);
          saveConfig();
          initGrid();
          alert('Config imported successfully!');
        } catch(err) {
          alert('Invalid config file');
        }
      };
      reader.readAsText(file);
    };
  }

  const resetBtn = document.getElementById('reset-btn');
  if (resetBtn) {
    resetBtn.onclick = () => {
      if (confirm('Reset to default clean dashboard?')) {
        localStorage.removeItem('tingsConfig');
        location.reload();
      }
    };
  }

  const closeOverlay = document.getElementById('close-overlay');
  if (closeOverlay) {
    closeOverlay.onclick = () => document.getElementById('overlay').classList.add('hidden');
  }
}

window.addEventListener('load', () => {
  console.log('%cTings Dashboard loading...', 'color:#00ffcc');
  loadConfig();
  initGrid();
  attachListeners();
  console.log('%cTings Dashboard ready - Try clicking Edit Mode', 'color:#00ffcc');
});