// Secure Admin Dashboard Logic

let token = localStorage.getItem('sportzx_admin_token');
let categories = [];
let channels = [];
let events = [];
let highlights = [];
let playlistsList = [];
let activeEditItem = null; // Holds reference to currently edited row
let activeCrudType = '';   // 'channels', 'categories', 'events', 'highlights'

document.addEventListener('DOMContentLoaded', () => {
  verifyToken();
  initLogin();
  initPanelNavigation();
  initMobileSidebar();
  initM3UImporter();
  initDatabaseCleaner();
  initCrudButtons();
  initSettingsPanel();
});

// --- AUTHENTICATION ROUTINES ---
async function verifyToken() {
  if (!token) {
    showLoginOverlay();
    return;
  }

  try {
    const res = await fetch('/api/admin/verify', {
      headers: { 'Authorization': `Bearer ${token}` }
    });
    
    if (res.ok) {
      showMainContainer();
      loadData();
    } else {
      localStorage.removeItem('sportzx_admin_token');
      token = null;
      showLoginOverlay();
    }
  } catch {
    showLoginOverlay();
  }
}

function verifyTokenSync() {
  if (!token) {
    showLoginOverlay();
    return false;
  }
  return true;
}

function showLoginOverlay() {
  document.getElementById('login-overlay').classList.remove('hidden');
  document.getElementById('admin-main-container').classList.add('hidden');
}

function showMainContainer() {
  document.getElementById('login-overlay').classList.add('hidden');
  document.getElementById('admin-main-container').classList.remove('hidden');
}

function initLogin() {
  const form = document.getElementById('login-form');
  const alertPlaceholder = document.getElementById('login-alert-placeholder');

  form.addEventListener('submit', async () => {
    const username = document.getElementById('login-username').value;
    const password = document.getElementById('login-password').value;

    try {
      const res = await fetch('/api/admin/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      });

      const data = await res.json();
      if (res.ok) {
        token = data.token;
        localStorage.setItem('sportzx_admin_token', token);
        alertPlaceholder.innerHTML = '';
        showMainContainer();
        loadData();
      } else {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">${data.error || 'Login failed'}</div>`;
      }
    } catch (err) {
      alertPlaceholder.innerHTML = `<div class="alert alert-error">Network error: ${err.message}</div>`;
    }
  });

  document.getElementById('btn-logout').addEventListener('click', () => {
    localStorage.removeItem('sportzx_admin_token');
    token = null;
    showLoginOverlay();
  });
}


// --- MAIN PANEL NAVIGATION ---
function initPanelNavigation() {
  const menuItems = document.querySelectorAll('.admin-menu-item');
  const panels = document.querySelectorAll('.admin-panel');

  menuItems.forEach(item => {
    item.addEventListener('click', () => {
      const targetPanel = item.getAttribute('data-panel');
      if (!targetPanel) return;

      menuItems.forEach(mi => mi.classList.remove('active'));
      item.classList.add('active');

      panels.forEach(panel => {
        if (panel.getAttribute('id') === `panel-${targetPanel}`) {
          panel.classList.add('active');
        } else {
          panel.classList.remove('active');
        }
      });
    });
  });
}

function initMobileSidebar() {
  const hamburger = document.getElementById('btn-admin-hamburger');
  const sidebar = document.querySelector('.admin-sidebar');
  const overlay = document.getElementById('admin-sidebar-overlay');
  
  if (hamburger && sidebar && overlay) {
    hamburger.addEventListener('click', () => {
      sidebar.classList.add('open');
      overlay.classList.add('active');
    });
    
    overlay.addEventListener('click', () => {
      sidebar.classList.remove('open');
      overlay.classList.remove('active');
    });
    
    const menuItems = sidebar.querySelectorAll('.admin-menu-item');
    menuItems.forEach(item => {
      item.addEventListener('click', () => {
        sidebar.classList.remove('open');
        overlay.classList.remove('active');
      });
    });
  }
}

function initDatabaseCleaner() {
  const btnClear = document.getElementById('btn-clear-db');
  const alertPlaceholder = document.getElementById('clear-db-alert-placeholder');
  if (!btnClear) return;

  btnClear.addEventListener('click', async () => {
    if (!confirm('Are you absolutely sure you want to delete ALL channels and categories? This cannot be undone.')) {
      return;
    }
    
    if (!verifyTokenSync()) return;

    btnClear.textContent = 'Clearing...';
    btnClear.disabled = true;
    if (alertPlaceholder) alertPlaceholder.innerHTML = '';

    try {
      const res = await fetch('/api/channels/clear', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      });

      const data = await res.json();
      if (res.ok) {
        if (alertPlaceholder) {
          alertPlaceholder.innerHTML = `<div class="alert alert-success">Database cleared successfully!</div>`;
        }
        loadData();
      } else {
        if (alertPlaceholder) {
          alertPlaceholder.innerHTML = `<div class="alert alert-error">Clear failed: ${data.error || 'Server error'}</div>`;
        }
      }
    } catch (err) {
      if (alertPlaceholder) {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">Network error: ${err.message}</div>`;
      }
    } finally {
      btnClear.textContent = 'Clear All Channels & Categories';
      btnClear.disabled = false;
    }
  });
}


// --- REST API FETCH & RENDER ROUTINES ---
async function loadData() {
  if (!verifyTokenSync()) return;

  try {
    const [resCats, resChans, resEvs, resHls, resPlaylists] = await Promise.all([
      fetch('/api/categories').then(r => r.json()),
      fetch('/api/channels').then(r => r.json()),
      fetch('/api/events').then(r => r.json()),
      fetch('/api/highlights').then(r => r.json()),
      fetch('/api/playlists').then(r => r.json()).catch(() => [])
    ]);

    categories = resCats;
    channels = resChans;
    events = resEvs;
    highlights = resHls;
    playlistsList = resPlaylists;

    // Update dashboard statistics
    const statChans = document.getElementById('stat-channels');
    const statCats = document.getElementById('stat-categories');
    const statEvs = document.getElementById('stat-events');
    const statHls = document.getElementById('stat-highlights');
    
    if (statChans) statChans.textContent = channels.length;
    if (statCats) statCats.textContent = categories.length;
    if (statEvs) statEvs.textContent = events.filter(e => e.status.toLowerCase() === 'live').length;
    if (statHls) statHls.textContent = highlights.length;

    renderCategoriesTable();
    renderChannelsTable();
    renderEventsTable();
    renderHighlightsTable();
    renderPlaylistsTable();

    // Load current system settings
    loadSettings();
  } catch (err) {
    console.error('Error loading data:', err.message);
  }
}

// 1. Render Categories Table
function renderCategoriesTable() {
  const tbody = document.querySelector('#categories-table tbody');
  tbody.innerHTML = '';

  categories.forEach(cat => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td style="font-weight:600;">${cat.name}</td>
      <td>${cat.display_order}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-category" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-category" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `;

    tr.querySelector('.btn-edit-category').addEventListener('click', () => openEditModal('categories', cat));
    tr.querySelector('.btn-delete-category').addEventListener('click', () => deleteItem('categories', cat.id));

    tbody.appendChild(tr);
  });
}

// 2. Render Channels Table
function renderChannelsTable() {
  const tbody = document.querySelector('#channels-table tbody');
  tbody.innerHTML = '';

  channels.forEach(chan => {
    const tr = document.createElement('tr');
    const firstLetter = chan.name.substring(0, 2).toUpperCase();
    const logoHtml = chan.logo_url 
      ? `<img src="${chan.logo_url}" onerror="this.outerHTML='<div class=\\'category-icon-fallback\\' style=\\'width:32px; height:32px; font-size:0.75rem; border-radius:6px;\\'>${firstLetter}</div>'">`
      : `<div class="category-icon-fallback" style="width:32px; height:32px; font-size:0.75rem; border-radius:6px;">${firstLetter}</div>`;

    tr.innerHTML = `
      <td>${logoHtml}</td>
      <td style="font-weight:600;">${chan.name}</td>
      <td>${chan.category_name || 'Uncategorized'}</td>
      <td style="font-family:monospace; font-size:0.75rem; max-width: 250px; text-overflow:ellipsis; overflow:hidden; white-space:nowrap;">${chan.stream_url}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-channel" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-channel" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `;

    tr.querySelector('.btn-edit-channel').addEventListener('click', () => openEditModal('channels', chan));
    tr.querySelector('.btn-delete-channel').addEventListener('click', () => deleteItem('channels', chan.id));

    tbody.appendChild(tr);
  });
}

// 3. Render Events Table
function renderEventsTable() {
  const tbody = document.querySelector('#events-table tbody');
  tbody.innerHTML = '';

  events.forEach(ev => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td style="color:var(--accent-cyan); font-weight:600;">${ev.league || 'Event'}</td>
      <td style="font-weight:600;">${ev.title}</td>
      <td><span class="badge ${ev.status.toLowerCase() === 'live' ? 'badge-live' : ''}">${ev.status}</span></td>
      <td>${ev.category}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-event" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-event" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `;

    tr.querySelector('.btn-edit-event').addEventListener('click', () => openEditModal('events', ev));
    tr.querySelector('.btn-delete-event').addEventListener('click', () => deleteItem('events', ev.id));

    tbody.appendChild(tr);
  });
}

// 4. Render Highlights Table
function renderHighlightsTable() {
  const tbody = document.querySelector('#highlights-table tbody');
  tbody.innerHTML = '';

  highlights.forEach(hl => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td style="color:var(--text-secondary);">${hl.league || 'Highlight'}</td>
      <td style="font-weight:600;">${hl.title}</td>
      <td style="font-family:monospace; font-weight:700;">${hl.score1} : ${hl.score2}</td>
      <td>${hl.date || ''}</td>
      <td class="actions">
        <button class="btn btn-secondary btn-edit-hl" style="padding: 6px 12px; font-size: 0.75rem;">Edit</button>
        <button class="btn btn-danger btn-delete-hl" style="padding: 6px 12px; font-size: 0.75rem;">Delete</button>
      </td>
    `;

    tr.querySelector('.btn-edit-hl').addEventListener('click', () => openEditModal('highlights', hl));
    tr.querySelector('.btn-delete-hl').addEventListener('click', () => deleteItem('highlights', hl.id));

    tbody.appendChild(tr);
  });
}


// --- DELETE OPERATION ---
async function deleteItem(type, id) {
  if (!confirm('Are you sure you want to delete this item?')) return;
  if (!verifyTokenSync()) return;

  try {
    const res = await fetch(`/api/${type}/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    });

    if (res.ok) {
      loadData();
    } else {
      const data = await res.json();
      alert('Delete failed: ' + (data.error || 'Unknown error'));
    }
  } catch (err) {
    alert('Network error: ' + err.message);
  }
}


// --- CRUD MODAL & SAVE SYSTEM ---
function initCrudButtons() {
  // Add triggers
  document.getElementById('btn-add-category-modal').addEventListener('click', () => openAddModal('categories'));
  document.getElementById('btn-add-channel-modal').addEventListener('click', () => openAddModal('channels'));
  document.getElementById('btn-add-event-modal').addEventListener('click', () => openAddModal('events'));
  document.getElementById('btn-add-highlight-modal').addEventListener('click', () => openAddModal('highlights'));

  // Close triggers
  document.getElementById('btn-modal-close').addEventListener('click', closeCrudModal);
  document.getElementById('btn-modal-save').addEventListener('click', saveCrudItem);
}

function openAddModal(type) {
  activeEditItem = null;
  activeCrudType = type;
  document.getElementById('crud-modal-title').textContent = `Add New ${type.slice(0, -1).toUpperCase()}`;
  renderFormFields(type);
  document.getElementById('crud-modal').classList.add('active');
}

function openEditModal(type, item) {
  activeEditItem = item;
  activeCrudType = type;
  document.getElementById('crud-modal-title').textContent = `Edit ${type.slice(0, -1).toUpperCase()}`;
  renderFormFields(type, item);
  document.getElementById('crud-modal').classList.add('active');
}

function closeCrudModal() {
  document.getElementById('crud-modal').classList.remove('active');
}

// Render dynamic form fields inside the CRUD modal based on schema
function renderFormFields(type, item = null) {
  const container = document.getElementById('crud-modal-body');
  container.innerHTML = '';

  if (type === 'categories') {
    container.innerHTML = `
      <div class="form-group">
        <label>Category Name</label>
        <input type="text" class="form-control" id="f-cat-name" value="${item ? item.name : ''}" required>
      </div>
      <div class="form-group">
        <label>Display Order</label>
        <input type="number" class="form-control" id="f-cat-order" value="${item ? item.display_order : 0}">
      </div>
      <div class="form-group">
        <label>Category Logo URL (Optional)</label>
        <input type="url" class="form-control" id="f-cat-logo" value="${item ? item.logo_url || '' : ''}">
      </div>
    `;
  } else if (type === 'channels') {
    const catOptions = categories.map(cat => 
      `<option value="${cat.id}" ${item && item.category_id === cat.id ? 'selected' : ''}>${cat.name}</option>`
    ).join('');

    container.innerHTML = `
      <div class="form-group">
        <label>Channel Name</label>
        <input type="text" class="form-control" id="f-chan-name" value="${item ? item.name : ''}" required>
      </div>
      <div class="form-group">
        <label>Category</label>
        <select class="form-control" id="f-chan-category">
          <option value="">Select Category</option>
          ${catOptions}
        </select>
      </div>
      <div class="form-group">
        <label>Logo URL (Optional)</label>
        <input type="url" class="form-control" id="f-chan-logo" value="${item ? item.logo_url || '' : ''}">
      </div>
      <div class="form-group">
        <label>Default Stream URL</label>
        <input type="text" class="form-control" id="f-chan-url" value="${item ? item.stream_url : ''}" placeholder="http://...m3u8" required>
      </div>
      
      ${!item ? `
      <div class="form-group" style="display:flex; align-items:center; gap:12px; margin-bottom: 24px;">
        <label class="switch" style="margin-bottom:0; flex-shrink:0;">
          <input type="checkbox" id="f-chan-merge">
          <span class="slider"></span>
        </label>
        <span style="font-size:0.9rem; font-weight:600; color:var(--text-secondary);">Merge if Channel exists (Same Name & Category)</span>
      </div>
      ` : ''}
      
      <!-- Multi-server stream settings -->
      <div class="form-group">
        <label style="display:flex; justify-content:space-between; align-items:center;">
          <span>Streaming Servers List</span>
          <button class="btn btn-secondary" id="btn-add-server-input" style="padding: 2px 8px; font-size: 0.75rem;">+ Add Server</button>
        </label>
        <div id="servers-input-list" style="margin-top: 10px;">
          <!-- Dynamically populated server rows -->
        </div>
      </div>
    `;

    // Populate server input lists
    const serversList = item && item.servers ? item.servers : [{ name: 'Primary Server', url: item ? item.stream_url : '' }];
    serversList.forEach(srv => addServerInputRow(srv.name, srv.url));

    document.getElementById('btn-add-server-input').addEventListener('click', (e) => {
      e.preventDefault();
      addServerInputRow('', '');
    });
  } else if (type === 'events') {
    container.innerHTML = `
      <div class="form-group">
        <label>Event Match Title</label>
        <input type="text" class="form-control" id="f-event-title" value="${item ? item.title : ''}" placeholder="Argentina VS Honduras" required>
      </div>
      <div class="form-group">
        <label>League Name</label>
        <input type="text" class="form-control" id="f-event-league" value="${item ? item.league || '' : ''}" placeholder="National Friendly Games">
      </div>
      <div class="form-group">
        <label>Sports Category</label>
        <select class="form-control" id="f-event-category">
          <option value="Football" ${item && item.category === 'Football' ? 'selected' : ''}>Football</option>
          <option value="Cricket" ${item && item.category === 'Cricket' ? 'selected' : ''}>Cricket</option>
          <option value="WWE" ${item && item.category === 'WWE' ? 'selected' : ''}>WWE</option>
          <option value="IPL" ${item && item.category === 'IPL' ? 'selected' : ''}>IPL</option>
        </select>
      </div>
      <div class="form-group">
        <label>Status</label>
        <select class="form-control" id="f-event-status">
          <option value="Upcoming" ${item && item.status === 'Upcoming' ? 'selected' : ''}>Upcoming</option>
          <option value="Live" ${item && item.status === 'Live' ? 'selected' : ''}>Live</option>
          <option value="Ended" ${item && item.status === 'Ended' ? 'selected' : ''}>Ended</option>
        </select>
      </div>
      <div class="form-group">
        <label>Start Date/Time String</label>
        <input type="text" class="form-control" id="f-event-time" value="${item ? item.start_time || '' : ''}" placeholder="e.g. 06:00 AM 07/06/2026">
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Name</label>
          <input type="text" class="form-control" id="f-event-t1name" value="${item ? item.team1_name || '' : ''}">
        </div>
        <div class="form-group">
          <label>Team 2 Name</label>
          <input type="text" class="form-control" id="f-event-t2name" value="${item ? item.team2_name || '' : ''}">
        </div>
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Logo URL</label>
          <input type="url" class="form-control" id="f-event-t1logo" value="${item ? item.team1_logo || '' : ''}">
        </div>
        <div class="form-group">
          <label>Team 2 Logo URL</label>
          <input type="url" class="form-control" id="f-event-t2logo" value="${item ? item.team2_logo || '' : ''}">
        </div>
      </div>
      
      <!-- Live event multiple streaming servers setup -->
      <div class="form-group">
        <label style="display:flex; justify-content:space-between; align-items:center;">
          <span>Event Streaming Servers</span>
          <button class="btn btn-secondary" id="btn-add-event-srv" style="padding: 2px 8px; font-size: 0.75rem;">+ Add Server</button>
        </label>
        <div id="servers-input-list" style="margin-top: 10px;">
          <!-- Dynamically populated server rows -->
        </div>
      </div>
    `;

    const serversList = item && item.servers ? item.servers : [];
    serversList.forEach(srv => addServerInputRow(srv.name, srv.url));

    document.getElementById('btn-add-event-srv').addEventListener('click', (e) => {
      e.preventDefault();
      addServerInputRow('', '');
    });
  } else if (type === 'highlights') {
    container.innerHTML = `
      <div class="form-group">
        <label>Highlights Video Title</label>
        <input type="text" class="form-control" id="f-hl-title" value="${item ? item.title : ''}" placeholder="Argentina vs Honduras Highlights" required>
      </div>
      <div class="form-group">
        <label>League Name</label>
        <input type="text" class="form-control" id="f-hl-league" value="${item ? item.league || '' : ''}">
      </div>
      <div class="form-group">
        <label>Sports Category</label>
        <select class="form-control" id="f-hl-category">
          <option value="Football" ${item && item.category === 'Football' ? 'selected' : ''}>Football</option>
          <option value="Cricket" ${item && item.category === 'Cricket' ? 'selected' : ''}>Cricket</option>
          <option value="IPL" ${item && item.category === 'IPL' ? 'selected' : ''}>IPL</option>
        </select>
      </div>
      <div class="form-group">
        <label>Date String</label>
        <input type="text" class="form-control" id="f-hl-date" value="${item ? item.date || '' : ''}" placeholder="e.g. 06/06/2026">
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Name</label>
          <input type="text" class="form-control" id="f-hl-t1name" value="${item ? item.team1_name || '' : ''}">
        </div>
        <div class="form-group">
          <label>Team 2 Name</label>
          <input type="text" class="form-control" id="f-hl-t2name" value="${item ? item.team2_name || '' : ''}">
        </div>
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Logo URL</label>
          <input type="url" class="form-control" id="f-hl-t1logo" value="${item ? item.team1_logo || '' : ''}">
        </div>
        <div class="form-group">
          <label>Team 2 Logo URL</label>
          <input type="url" class="form-control" id="f-hl-t2logo" value="${item ? item.team2_logo || '' : ''}">
        </div>
      </div>
      <div style="display:grid; grid-template-columns: 1fr 1fr; gap:16px;">
        <div class="form-group">
          <label>Team 1 Score</label>
          <input type="text" class="form-control" id="f-hl-score1" value="${item ? item.score1 || '0' : '0'}">
        </div>
        <div class="form-group">
          <label>Team 2 Score</label>
          <input type="text" class="form-control" id="f-hl-score2" value="${item ? item.score2 || '0' : '0'}">
        </div>
      </div>
      <div class="form-group">
        <label>Highlight Video URL (HLS .m3u8)</label>
        <input type="text" class="form-control" id="f-hl-video" value="${item ? item.video_url : ''}" placeholder="http://...m3u8" required>
      </div>
    `;
  }
}

function addServerInputRow(name = '', url = '') {
  const list = document.getElementById('servers-input-list');
  const div = document.createElement('div');
  div.className = 'server-input-row';
  div.innerHTML = `
    <input type="text" class="form-control srv-name" value="${name}" placeholder="Server Name (e.g. SportzX MLB)" style="flex:1;">
    <input type="text" class="form-control srv-url" value="${url}" placeholder="HLS Stream URL (.m3u8)" style="flex:2;">
    <button class="btn btn-danger btn-remove-srv" style="padding: 10px;">✕</button>
  `;

  div.querySelector('.btn-remove-srv').addEventListener('click', (e) => {
    e.preventDefault();
    div.remove();
  });

  list.appendChild(div);
}

// Gather server list input details
function collectServerInputs() {
  const list = document.getElementById('servers-input-list');
  if (!list) return [];
  const rows = list.querySelectorAll('.server-input-row');
  const servers = [];
  rows.forEach(row => {
    const name = row.querySelector('.srv-name').value.trim();
    const url = row.querySelector('.srv-url').value.trim();
    if (name && url) {
      servers.push({ name, url });
    }
  });
  return servers;
}

// --- SAVE FORM DATA OPERATION ---
async function saveCrudItem() {
  if (!verifyTokenSync()) return;

  let url = `/api/${activeCrudType}`;
  let method = 'POST';
  let body = {};

  if (activeEditItem) {
    url = `/api/${activeCrudType}/${activeEditItem.id}`;
    method = 'PUT';
  }

  // 1. Categories parsing
  if (activeCrudType === 'categories') {
    const name = document.getElementById('f-cat-name').value.trim();
    const order = Number(document.getElementById('f-cat-order').value);
    const logo = document.getElementById('f-cat-logo').value.trim();
    
    if (!name) return alert('Name is required');
    body = { name, display_order: order, logo_url: logo };
  } 
  // 2. Channels parsing
  else if (activeCrudType === 'channels') {
    const name = document.getElementById('f-chan-name').value.trim();
    const cat = document.getElementById('f-chan-category').value;
    const logo = document.getElementById('f-chan-logo').value.trim();
    const defaultUrl = document.getElementById('f-chan-url').value.trim();
    const servers = collectServerInputs();
    const mergeEl = document.getElementById('f-chan-merge');
    const merge = mergeEl ? mergeEl.checked : false;

    if (!name || !defaultUrl) return alert('Name and Stream URL are required');
    
    body = { 
      name, 
      stream_url: defaultUrl, 
      logo_url: logo, 
      category_id: cat ? Number(cat) : null,
      servers: servers.length > 0 ? servers : [{ name: 'Primary Server', url: defaultUrl }],
      merge
    };
  } 
  // 3. Events parsing
  else if (activeCrudType === 'events') {
    const title = document.getElementById('f-event-title').value.trim();
    const league = document.getElementById('f-event-league').value.trim();
    const category = document.getElementById('f-event-category').value;
    const status = document.getElementById('f-event-status').value;
    const time = document.getElementById('f-event-time').value.trim();
    
    const t1name = document.getElementById('f-event-t1name').value.trim();
    const t2name = document.getElementById('f-event-t2name').value.trim();
    const t1logo = document.getElementById('f-event-t1logo').value.trim();
    const t2logo = document.getElementById('f-event-t2logo').value.trim();
    const servers = collectServerInputs();

    if (!title) return alert('Title is required');

    body = {
      title,
      league,
      category,
      status,
      start_time: time,
      team1_name: t1name,
      team2_name: t2name,
      team1_logo: t1logo,
      team2_logo: t2logo,
      servers
    };
  } 
  // 4. Highlights parsing
  else if (activeCrudType === 'highlights') {
    const title = document.getElementById('f-hl-title').value.trim();
    const league = document.getElementById('f-hl-league').value.trim();
    const category = document.getElementById('f-hl-category').value;
    const date = document.getElementById('f-hl-date').value.trim();
    
    const t1name = document.getElementById('f-hl-t1name').value.trim();
    const t2name = document.getElementById('f-hl-t2name').value.trim();
    const t1logo = document.getElementById('f-hl-t1logo').value.trim();
    const t2logo = document.getElementById('f-hl-t2logo').value.trim();
    
    const score1 = document.getElementById('f-hl-score1').value.trim();
    const score2 = document.getElementById('f-hl-score2').value.trim();
    const videoUrl = document.getElementById('f-hl-video').value.trim();

    if (!title || !videoUrl) return alert('Title and Video URL are required');

    body = {
      title,
      league,
      category,
      date,
      team1_name: t1name,
      team2_name: t2name,
      team1_logo: t1logo,
      team2_logo: t2logo,
      score1,
      score2,
      video_url: videoUrl
    };
  }

  try {
    const res = await fetch(url, {
      method: method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(body)
    });

    if (res.ok) {
      closeCrudModal();
      loadData();
    } else {
      const data = await res.json();
      alert('Save failed: ' + (data.error || 'Server error'));
    }
  } catch (err) {
    alert('Network error: ' + err.message);
  }
}


// --- BULK M3U IMPORT TRIGGER ---
function initM3UImporter() {
  const tabPaste = document.getElementById('tab-import-paste');
  const tabFile = document.getElementById('tab-import-file');
  const tabUrl = document.getElementById('tab-import-url');
  
  const contentPaste = document.getElementById('content-import-paste');
  const contentFile = document.getElementById('content-import-file');
  const contentUrl = document.getElementById('content-import-url');

  const dragDropZone = document.getElementById('m3u-drag-drop');
  const fileInput = document.getElementById('m3u-file-input');
  const fileNameDisplay = document.getElementById('m3u-file-name');
  const playlistNameInput = document.getElementById('playlist-name-input');
  const urlInput = document.getElementById('playlist-url-input');

  const btnImport = document.getElementById('btn-import-m3u');
  const alertPlaceholder = document.getElementById('m3u-alert-placeholder');
  const textarea = document.getElementById('m3u-textarea');

  let activeTab = 'paste'; // 'paste', 'file', 'url'
  let uploadedFileContent = '';
  let uploadedFileName = '';

  // Tab switching logic
  if (tabPaste && tabFile && tabUrl) {
    tabPaste.addEventListener('click', () => {
      activeTab = 'paste';
      tabPaste.classList.add('active');
      tabFile.classList.remove('active');
      tabUrl.classList.remove('active');
      contentPaste.classList.remove('hidden');
      contentFile.classList.add('hidden');
      contentUrl.classList.add('hidden');
    });

    tabFile.addEventListener('click', () => {
      activeTab = 'file';
      tabFile.classList.add('active');
      tabPaste.classList.remove('active');
      tabUrl.classList.remove('active');
      contentFile.classList.remove('hidden');
      contentPaste.classList.add('hidden');
      contentUrl.classList.add('hidden');
    });

    tabUrl.addEventListener('click', () => {
      activeTab = 'url';
      tabUrl.classList.add('active');
      tabPaste.classList.remove('active');
      tabFile.classList.remove('active');
      contentUrl.classList.remove('hidden');
      contentPaste.classList.add('hidden');
      contentFile.classList.add('hidden');
    });
  }

  // File Upload drag & drop
  if (dragDropZone && fileInput) {
    dragDropZone.addEventListener('click', () => fileInput.click());

    fileInput.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (file) {
        handleFileSelect(file);
      }
    });

    dragDropZone.addEventListener('dragover', (e) => {
      e.preventDefault();
      dragDropZone.style.borderColor = 'var(--accent-secondary)';
      dragDropZone.style.background = 'rgba(255, 255, 255, 0.06)';
    });

    dragDropZone.addEventListener('dragleave', () => {
      dragDropZone.style.borderColor = 'rgba(255, 255, 255, 0.15)';
      dragDropZone.style.background = 'rgba(255, 255, 255, 0.02)';
    });

    dragDropZone.addEventListener('drop', (e) => {
      e.preventDefault();
      dragDropZone.style.borderColor = 'rgba(255, 255, 255, 0.15)';
      dragDropZone.style.background = 'rgba(255, 255, 255, 0.02)';
      const file = e.dataTransfer.files[0];
      if (file) {
        handleFileSelect(file);
      }
    });
  }

  function handleFileSelect(file) {
    uploadedFileName = file.name;
    if (fileNameDisplay) {
      fileNameDisplay.textContent = `Selected: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
    }
    
    // Auto-fill Playlist name with file name (without extension) if empty
    if (playlistNameInput && !playlistNameInput.value.trim()) {
      playlistNameInput.value = file.name.replace(/\.[^/.]+$/, "");
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      uploadedFileContent = e.target.result;
    };
    reader.readAsText(file);
  }

  // Import Action Trigger
  btnImport.addEventListener('click', async () => {
    let payload = {};
    const playlistName = playlistNameInput ? playlistNameInput.value.trim() : '';
    const mergeEl = document.getElementById('m3u-merge-toggle');
    const merge = mergeEl ? mergeEl.checked : false;

    if (activeTab === 'paste') {
      const text = textarea.value.trim();
      if (!text) {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">Please paste M3U playlist content first.</div>`;
        return;
      }
      payload = { m3u: text, playlist_name: playlistName, merge };
    } else if (activeTab === 'file') {
      if (!uploadedFileContent) {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">Please select or upload an M3U file first.</div>`;
        return;
      }
      payload = { m3u: uploadedFileContent, playlist_name: playlistName || uploadedFileName, merge };
    } else if (activeTab === 'url') {
      const url = urlInput ? urlInput.value.trim() : '';
      if (!url) {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">Please enter a valid remote playlist URL.</div>`;
        return;
      }
      payload = { playlist_url: url, playlist_name: playlistName, merge };
    }

    if (!verifyTokenSync()) return;

    btnImport.textContent = 'Importing... Please wait';
    btnImport.disabled = true;
    alertPlaceholder.innerHTML = '';

    try {
      const res = await fetch('/api/channels/import', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(payload)
      });

      const data = await res.json();
      if (res.ok) {
        alertPlaceholder.innerHTML = `<div class="alert alert-success">Playlist "${data.playlistName || 'IPTV'}" imported successfully! Channels and Categories synced.</div>`;
        
        // Reset inputs
        textarea.value = '';
        if (urlInput) urlInput.value = '';
        if (playlistNameInput) playlistNameInput.value = '';
        if (fileNameDisplay) fileNameDisplay.textContent = '';
        uploadedFileContent = '';
        uploadedFileName = '';
        
        loadData();
      } else {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">Import failed: ${data.error || 'Server error'}</div>`;
      }
    } catch (err) {
      alertPlaceholder.innerHTML = `<div class="alert alert-error">Network error: ${err.message}</div>`;
    } finally {
      btnImport.textContent = 'Start Bulk Import';
      btnImport.disabled = false;
    }
  });
}

// --- PLAYLIST MANAGER RENDER & ACTIONS ---
function renderPlaylistsTable() {
  const tbody = document.querySelector('#playlists-table tbody');
  if (!tbody) return;
  tbody.innerHTML = '';

  if (playlistsList.length === 0) {
    tbody.innerHTML = `<tr><td colspan="3" style="text-align:center; color:var(--text-muted); padding:20px 0; font-size:0.85rem;">No playlists uploaded yet.</td></tr>`;
    return;
  }

  playlistsList.forEach(pl => {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td style="font-weight:600;">${pl.name}</td>
      <td style="font-family:monospace; font-size:0.75rem; color:var(--text-secondary); max-width: 250px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${pl.url || 'Direct File / Paste'}</td>
      <td class="actions">
        <button class="btn btn-danger btn-delete-playlist" style="padding: 6px 12px; font-size: 0.75rem;" data-id="${pl.id}">Delete</button>
      </td>
    `;

    tr.querySelector('.btn-delete-playlist').addEventListener('click', () => deletePlaylist(pl.id, pl.name));
    tbody.appendChild(tr);
  });
}

async function deletePlaylist(id, name) {
  if (!confirm(`Are you absolutely sure you want to delete playlist "${name}"? This will permanently delete all channels associated with it.`)) {
    return;
  }
  
  if (!verifyTokenSync()) return;
  
  const alertPlaceholder = document.getElementById('playlist-mgr-alert-placeholder');
  if (alertPlaceholder) alertPlaceholder.innerHTML = '';

  try {
    const res = await fetch(`/api/playlists/${id}`, {
      method: 'DELETE',
      headers: { 'Authorization': `Bearer ${token}` }
    });

    if (res.ok) {
      if (alertPlaceholder) {
        alertPlaceholder.innerHTML = `<div class="alert alert-success">Playlist "${name}" deleted successfully!</div>`;
      }
      loadData();
    } else {
      const data = await res.json();
      alert('Delete failed: ' + (data.error || 'Unknown error'));
    }
  } catch (err) {
    alert('Network error: ' + err.message);
  }
}

// --- SYSTEM SETTINGS PANEL ---
async function loadSettings() {
  try {
    const res = await fetch('/api/settings/announcement');
    if (res.ok) {
      const data = await res.json();
      document.getElementById('announcement-input').value = data.value || '';
    }
  } catch (err) {
    console.error('Error fetching announcement setting:', err.message);
  }
}

function initSettingsPanel() {
  const btnSave = document.getElementById('btn-save-announcement');
  const alertPlaceholder = document.getElementById('settings-alert-placeholder');
  const input = document.getElementById('announcement-input');

  btnSave.addEventListener('click', async () => {
    const value = input.value.trim();
    if (!verifyTokenSync()) return;

    btnSave.textContent = 'Saving...';
    btnSave.disabled = true;
    alertPlaceholder.innerHTML = '';

    try {
      const res = await fetch('/api/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({ key: 'announcement', value })
      });

      const data = await res.json();
      if (res.ok) {
        alertPlaceholder.innerHTML = `<div class="alert alert-success">Announcement saved successfully!</div>`;
      } else {
        alertPlaceholder.innerHTML = `<div class="alert alert-error">Save failed: ${data.error || 'Server error'}</div>`;
      }
    } catch (err) {
      alertPlaceholder.innerHTML = `<div class="alert alert-error">Network error: ${err.message}</div>`;
    } finally {
      btnSave.textContent = 'Save Announcement';
      btnSave.disabled = false;
    }
  });
}
