let grid;
let isEditMode = false;
let currentSectionId = null;
let currentTingIndex = null;
let currentSectionForEdit = null;

let config = JSON.parse(localStorage.getItem('tingsConfig')) || {
  sections: [
    { id: "main", title: "Main", color: "#00ffcc", bgImage: "", customCSS: "", x:0, y:0, w:6, h:3,
      tings: [{name:"The Hub", url:"#", icon:"🌐", tint:"", target:"_blank"}] },
    { id: "general", title: "General", color: "#4488ff", bgImage: "", customCSS: "", x:6, y:0, w:6, h:4,
      tings: [{name:"Training Program", url:"#", icon:"👨‍🏫", tint:"", target:"_blank"}] }
  ]
};

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

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

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

  grid = GridStack.init({
    float: true,
    cellHeight: 90,
    margin: 14,
    draggable: { handle: '.section-header' },
    resizable: isEditMode,
    disableResize: !isEditMode,
    disableDrag: !isEditMode
  });

  config.sections.forEach(sec => renderTings(sec.id));

  // Make tings sortable + cross-section drag
  setupSortable();
  attachGlobalListeners();
}

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;

  // Auto icon size based on section width/height (rough heuristic)
  const iconSize = Math.max(42, Math.min(78, section.w * 12));

  section.tings.forEach((ting, i) => {
    const div = document.createElement('div');
    div.className = 'ting';
    div.draggable = isEditMode;
    div.dataset.section = sectionId;
    div.dataset.index = i;
    div.style.setProperty('--icon-size', iconSize + 'px');
    div.style.setProperty('--ting-tint', ting.tint || 'none');

    div.innerHTML = `
      ${ting.icon?.startsWith('http') ? `<img src="${ting.icon}" alt="">` : `<div class="icon-placeholder">${ting.icon || '🔗'}</div>`}
      <span>${ting.name}</span>
      ${isEditMode ? `<span class="delete-ting" data-index="${i}">×</span>` : ''}
    `;

    div.onclick = (e) => {
      if (isEditMode) return;
      handleTingClick(ting);
    };

    // Delete button
    const delBtn = div.querySelector('.delete-ting');
    if (delBtn) delBtn.onclick = (e) => { e.stopImmediatePropagation(); deleteTing(sectionId, i); };

    container.appendChild(div);
  });

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

function setupSortable() {
  document.querySelectorAll('.tings-grid').forEach(gridEl => {
    new Sortable(gridEl, {
      group: 'tings',
      animation: 180,
      ghostClass: 'sortable-ghost',
      onEnd: (evt) => {
        const fromSection = evt.from.id.replace('tings-', '');
        const toSection = evt.to.id.replace('tings-', '');

        const sectionFrom = config.sections.find(s => s.id === fromSection);
        const sectionTo = config.sections.find(s => s.id === toSection);

        if (!sectionFrom || !sectionTo) return;

        const [movedTing] = sectionFrom.tings.splice(evt.oldIndex, 1);
        sectionTo.tings.splice(evt.newIndex, 0, movedTing);

        saveConfig();
        renderTings(fromSection);
        if (fromSection !== toSection) renderTings(toSection);
      }
    });
  });
}

function handleTingClick(ting) {
  const target = ting.target || '_blank';
  if (target === 'overlay') {
    showOverlay(ting.url, ting.name);
  } else if (target === 'media') {
    showMediaPlayer(ting.url, ting.name);
  } else {
    window.open(ting.url, target);
  }
}

function showOverlay(url, title) {
  const body = document.getElementById('overlay-body');
  body.innerHTML = `<iframe src="${url}" allowfullscreen></iframe>`;
  document.getElementById('overlay').classList.remove('hidden');
}

function showMediaPlayer(url, title) {
  const body = document.getElementById('overlay-body');
  let html = `<video id="player" controls autoplay style="width:100%;height:640px;"></video>`;
  body.innerHTML = html;
  const video = document.getElementById('player');

  if (url.includes('.m3u8') && typeof Hls !== 'undefined' && Hls.isSupported()) {
    const hls = new Hls();
    hls.loadSource(url);
    hls.attachMedia(video);
  } else {
    video.src = url;
  }
  document.getElementById('overlay').classList.remove('hidden');
}

// Section & Ting modals, export/import, edit mode, etc.
function attachGlobalListeners() {
  document.getElementById('edit-btn').onclick = () => {
    isEditMode = !isEditMode;
    document.getElementById('edit-btn').textContent = `Edit Mode: ${isEditMode ? 'ON' : 'OFF'}`;
    initGrid();
  };

  document.getElementById('add-section-btn').onclick = addNewSection;
  document.getElementById('export-btn').onclick = exportConfig;
  document.getElementById('import-btn').onclick = () => document.getElementById('import-file').click();
  document.getElementById('import-file').onchange = importConfig;
  document.getElementById('save-btn').onclick = () => { saveConfig(); alert('Saved to browser storage'); };

  // Overlay close
  document.getElementById('close-overlay').onclick = () => document.getElementById('overlay').classList.add('hidden');

  // Modal listeners
  document.getElementById('close-modal-btn').onclick = closeTingModal;
  document.getElementById('save-ting-btn').onclick = saveTing;
  document.getElementById('ting-target').onchange = updateTargetDesc;

  document.getElementById('close-sec-modal-btn').onclick = () => document.getElementById('section-modal').style.display = 'none';
  document.getElementById('save-section-btn').onclick = saveSectionChanges;

  // Click on section edit buttons (event delegation)
  document.addEventListener('click', e => {
    if (e.target.classList.contains('edit-section-btn')) {
      editSection(e.target.dataset.id);
    }
  });
}

function addNewSection() {
  const newSec = {
    id: 'sec-' + Date.now(),
    title: 'New Section',
    color: '#ff8800',
    bgImage: '',
    customCSS: '',
    x: 0, y: 999, w: 5, h: 3,
    tings: []
  };
  config.sections.push(newSec);
  initGrid();
  saveConfig();
}

function editSection(id) {
  currentSectionForEdit = config.sections.find(s => s.id === id);
  if (!currentSectionForEdit) return;

  document.getElementById('sec-title').value = currentSectionForEdit.title;
  document.getElementById('sec-color').value = currentSectionForEdit.color;
  document.getElementById('sec-bgimg').value = currentSectionForEdit.bgImage || '';
  document.getElementById('sec-customcss').value = currentSectionForEdit.customCSS || '';

  document.getElementById('section-modal').style.display = 'flex';
}

function saveSectionChanges() {
  if (!currentSectionForEdit) return;
  currentSectionForEdit.title = document.getElementById('sec-title').value || 'Section';
  currentSectionForEdit.color = document.getElementById('sec-color').value;
  currentSectionForEdit.bgImage = document.getElementById('sec-bgimg').value.trim();
  currentSectionForEdit.customCSS = document.getElementById('sec-customcss').value.trim();

  document.getElementById('section-modal').style.display = 'none';
  initGrid();
  saveConfig();
}

function addNewTing(sectionId) {
  currentSectionId = sectionId;
  currentTingIndex = null;
  document.getElementById('modal-title').textContent = 'Add New Ting';
  clearTingModal();
  document.getElementById('ting-modal').style.display = 'flex';
  updateTargetDesc();
}

function editTing(sectionId, index) { /* stub if you want full edit from right-click later */ }

function saveTing() {
  if (!currentSectionId) return;
  const section = config.sections.find(s => s.id === currentSectionId);
  if (!section) return;

  const ting = {
    name: document.getElementById('ting-name').value || 'Untitled',
    url: document.getElementById('ting-url').value,
    icon: document.getElementById('ting-icon').value || '🔗',
    tint: document.getElementById('ting-tint').value,
    hint: document.getElementById('ting-hint').value,
    target: document.getElementById('ting-target').value
  };

  if (currentTingIndex !== null) {
    section.tings[currentTingIndex] = ting;
  } else {
    section.tings.push(ting);
  }

  closeTingModal();
  renderTings(currentSectionId);
  saveConfig();
}

function deleteTing(sectionId, index) {
  if (!confirm('Delete this ting?')) return;
  const section = config.sections.find(s => s.id === sectionId);
  section.tings.splice(index, 1);
  renderTings(sectionId);
  saveConfig();
}

function closeTingModal() {
  document.getElementById('ting-modal').style.display = 'none';
}

function clearTingModal() {
  ['ting-name','ting-url','ting-icon','ting-tint','ting-hint'].forEach(id => document.getElementById(id).value = '');
  document.getElementById('ting-target').value = '_blank';
}

function updateTargetDesc() {
  const val = document.getElementById('ting-target').value;
  const map = {
    '_blank': 'Opens in a new browser tab',
    '_self': 'Replaces the current page',
    'overlay': 'Opens inside a modal overlay without leaving the dashboard',
    'media': 'Opens video / live m3u8 stream with media controls',
    'inline': 'Embeds content directly inside the section'
  };
  document.getElementById('target-desc').textContent = map[val] || '';
}

function exportConfig() {
  const dataStr = JSON.stringify(config, null, 2);
  const blob = new Blob([dataStr], {type: 'application/json'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'tings-config.json';
  a.click();
  URL.revokeObjectURL(url);
}

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

// Keyboard support
document.addEventListener('keydown', e => {
  if (e.key === 'Escape') {
    const overlay = document.getElementById('overlay');
    if (!overlay.classList.contains('hidden')) overlay.classList.add('hidden');
    else {
      document.getElementById('ting-modal').style.display = 'none';
      document.getElementById('section-modal').style.display = 'none';
    }
  }
});

window.onload = initGrid;