function onReadySchedule(callback) {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', callback);
  } else {
    callback();
  }
}

let currentCategory = 'all';
let currentDay = 'all';
let currentGenre = 'all';
let currentStatus = 'all';
let currentYear = 'all';
let currentSort = 'all';
let currentPage = 1;
const itemsPerPage = 24;

// Trạng thái theo dõi lịch phát sóng trực tuyến
let liveScheduleVersion = null;
let isCheckingLiveSchedule = false;
let liveScheduleTimer = null;

const dayTitleMap = {
  't2': 'Thứ Hai',
  't3': 'Thứ Ba',
  't4': 'Thứ Tư',
  't5': 'Thứ Năm',
  't6': 'Thứ Sáu',
  't7': 'Thứ Bảy',
  'cn': 'Chủ Nhật'
};

function updateSectionTitle(dayKey) {
  const titleEl = document.getElementById('mainSectionTitle');
  const subEl = document.getElementById('mainSectionSubtitle');
  if (!titleEl) return;

  const catNames = {
    'hoathinh3d': 'Hoạt Hình 3D',
    '3d': 'Hoạt Hình 3D',
    'anime': 'Anime',
    'phimtruyenhinh': 'Phim Truyền Hình',
    'series': 'Phim Truyền Hình'
  };
  const catLabel = catNames[currentCategory] || '';

  if (dayKey && dayKey !== 'all' && dayTitleMap[dayKey]) {
    titleEl.innerHTML = `<i class="fa-solid fa-calendar-day" style="color: var(--accent);"></i> ${catLabel ? catLabel + ' - ' : ''}Phim Chiếu ${dayTitleMap[dayKey]}`;
    if (subEl) {
      subEl.innerHTML = `<i class="fa-solid fa-clock"></i> Lịch phát sóng trong ngày ${dayTitleMap[dayKey]}`;
    }
  } else if (catLabel) {
    titleEl.innerHTML = `<i class="fa-solid fa-bolt" style="color: var(--accent);"></i> ${catLabel} Mới Cập Nhật`;
    if (subEl) {
      subEl.innerHTML = `<i class="fa-solid fa-rotate"></i> Tự động cập nhật theo tập mới nhất`;
    }
  } else {
    titleEl.innerHTML = `<i class="fa-solid fa-bolt" style="color: var(--accent);"></i> Phim Mới Cập Nhật`;
    if (subEl) {
      subEl.innerHTML = `<i class="fa-solid fa-rotate"></i> Tự động cập nhật theo tập mới`;
    }
  }
}

onReadySchedule(() => {
  const urlParams = new URLSearchParams(window.location.search);
  const p = parseInt(urlParams.get('page'));
  if (p && p > 1) {
    currentPage = p;
  }
  const dayParam = urlParams.get('day');
  if (dayParam && ['t2', 't3', 't4', 't5', 't6', 't7', 'cn'].includes(dayParam)) {
    currentDay = dayParam;
    syncActiveDay(dayParam);
    updateSectionTitle(dayParam);
  } else {
    currentDay = 'all';
    syncActiveDay('all');
    updateSectionTitle('all');
  }

  const typeParam = urlParams.get('type');
  if (typeParam && ['3d', 'hoathinh3d', 'anime', 'series', 'phimtruyenhinh'].includes(typeParam)) {
    currentCategory = (typeParam === '3d') ? 'hoathinh3d' : ((typeParam === 'series') ? 'phimtruyenhinh' : typeParam);
    syncActiveCategory(currentCategory);
    updateSectionTitle(currentDay);
  }

  const genreParam = urlParams.get('genre');
  if (genreParam) {
    currentGenre = genreParam;
    syncDesktopFilter('filterGenre', genreParam);
    syncSheetFilter('genre', genreParam);
  }

  const statusParam = urlParams.get('status');
  if (statusParam) {
    currentStatus = statusParam;
    syncDesktopFilter('filterStatus', statusParam);
    syncSheetFilter('status', statusParam);
  }

  const yearParam = urlParams.get('year');
  if (yearParam) {
    currentYear = yearParam;
    syncDesktopFilter('filterYear', yearParam);
    syncSheetFilter('year', yearParam);
  }

  const sortParam = urlParams.get('sort');
  if (sortParam) {
    currentSort = sortParam;
    syncDesktopFilter('filterSort', sortParam);
    syncSheetFilter('sort', sortParam);
  }

  initScheduleTabs();
  initCategorySwitch();
  initHeaderFilters();
  highlightCurrentDay();
  initScheduleScrollArrows();
  initIosScheduleModal();
  initIosCategoryModal();

  const hasUrlFilter = (currentPage > 1 || currentDay !== 'all' || currentCategory !== 'all' || currentGenre !== 'all' || currentStatus !== 'all' || currentYear !== 'all' || currentSort !== 'all');
  if (hasUrlFilter) {
    filterMovies();
  } else {
    initInitialPagination();
  }

  // Khởi động trình theo dõi cập nhật lịch phát sóng tự động (Live Real-time Watcher)
  initLiveScheduleWatcher();
});

function syncActiveCategory(cat) {
  const norm = (cat === '3d') ? 'hoathinh3d' : ((cat === 'series') ? 'phimtruyenhinh' : cat);
  const catButtons = document.querySelectorAll('.pill-btn');
  catButtons.forEach(b => {
    const t = b.getAttribute('data-type');
    const bNorm = (t === '3d') ? 'hoathinh3d' : ((t === 'series') ? 'phimtruyenhinh' : t);
    if (bNorm === norm) {
      b.classList.add('active');
    } else {
      b.classList.remove('active');
    }
  });

  const sheetCatButtons = document.querySelectorAll('#sheetFilterCategory .filter-sheet-btn');
  sheetCatButtons.forEach(b => {
    const v = b.getAttribute('data-value');
    const vNorm = (v === '3d') ? 'hoathinh3d' : ((v === 'series') ? 'phimtruyenhinh' : v);
    if (vNorm === norm) {
      b.classList.add('active');
    } else {
      b.classList.remove('active');
    }
  });
}

function syncDesktopFilter(selectId, value) {
  const el = document.getElementById(selectId);
  if (!el) return;
  for (let opt of el.options) {
    if (opt.value.toLowerCase() === value.toLowerCase()) {
      el.value = opt.value;
      break;
    }
  }
}

function syncSheetFilter(type, value) {
  const btns = document.querySelectorAll(`.filter-sheet-btn[data-type="${type}"]`);
  btns.forEach(b => {
    if (b.getAttribute('data-value').toLowerCase() === value.toLowerCase()) {
      const parent = b.parentElement;
      if (parent) {
        parent.querySelectorAll('.filter-sheet-btn').forEach(btn => btn.classList.remove('active'));
      }
      b.classList.add('active');
    }
  });
}

function initCategorySwitch() {
  const catButtons = document.querySelectorAll('.pill-btn');
  if (!catButtons.length) return;

  catButtons.forEach(btn => {
    btn.addEventListener('click', function() {
      catButtons.forEach(b => b.classList.remove('active'));
      this.classList.add('active');

      currentCategory = this.getAttribute('data-type') || 'all';
      currentDay = 'all';
      syncActiveDay('all');
      updateSectionTitle('all');
      currentPage = 1;
      filterMovies();

      const url = new URL(window.location.href);
      if (currentCategory && currentCategory !== 'all') {
        url.searchParams.set('type', currentCategory);
      } else {
        url.searchParams.delete('type');
      }
      url.searchParams.delete('day');
      url.searchParams.delete('page');
      window.history.replaceState({}, '', url.toString());
    });
  });
}

function initScheduleTabs() {
  const dayTabs = document.querySelectorAll('.day-tab');
  if (!dayTabs.length) return;

  dayTabs.forEach(tab => {
    tab.addEventListener('click', function() {
      const selectedDay = this.getAttribute('data-day') || 'all';
      syncActiveDay(selectedDay);
      currentDay = selectedDay;
      currentPage = 1;
      filterMovies();

      updateSectionTitle(selectedDay);

      const url = new URL(window.location.href);
      if (selectedDay && selectedDay !== 'all') {
        url.searchParams.set('day', selectedDay);
      } else {
        url.searchParams.delete('day');
      }
      url.searchParams.delete('page');
      window.history.replaceState({}, '', url.toString());
    });
  });
}

function initHeaderFilters() {
  const gSelect = document.getElementById('filterGenre');
  const sSelect = document.getElementById('filterStatus');
  const ySelect = document.getElementById('filterYear');
  const oSelect = document.getElementById('filterSort');

  [gSelect, sSelect, ySelect, oSelect].forEach(selectEl => {
    if (!selectEl) return;
    selectEl.addEventListener('change', () => {
      applyFilterSelection(true);
    });
  });
}

function applyFilterSelection(fromUser = false) {
  const gSelect = document.getElementById('filterGenre');
  const sSelect = document.getElementById('filterStatus');
  const ySelect = document.getElementById('filterYear');
  const oSelect = document.getElementById('filterSort');

  if (gSelect) currentGenre = gSelect.value;
  if (sSelect) currentStatus = sSelect.value;
  if (ySelect) currentYear = ySelect.value;
  if (oSelect) currentSort = oSelect.value;

  if (gSelect && currentGenre) syncSheetFilter('genre', currentGenre);
  if (sSelect && currentStatus) syncSheetFilter('status', currentStatus);
  if (ySelect && currentYear) syncSheetFilter('year', currentYear);
  if (oSelect && currentSort) syncSheetFilter('sort', currentSort);

  const moviesGrid = document.getElementById('moviesGrid');
  if (!moviesGrid) {
    if (fromUser) {
      const p = new URLSearchParams();
      if (currentGenre && currentGenre !== 'Tất Cả Thể Loại') p.set('genre', currentGenre);
      if (currentStatus && currentStatus !== 'Trạng Thái') p.set('status', currentStatus);
      if (currentYear && currentYear !== 'Năm Phát Hành') p.set('year', currentYear);
      if (currentSort && currentSort !== 'Sắp Xếp') p.set('sort', currentSort);
      window.location.href = 'index.php?' + p.toString();
    }
    return;
  }

  currentPage = 1;
  filterMovies();

  if (fromUser) {
    const moviesCol = document.querySelector('.main-movies-column');
    if (moviesCol) {
      moviesCol.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    const url = new URL(window.location.href);
    if (currentGenre && currentGenre !== 'Tất Cả Thể Loại') url.searchParams.set('genre', currentGenre);
    else url.searchParams.delete('genre');

    if (currentStatus && currentStatus !== 'Trạng Thái') url.searchParams.set('status', currentStatus);
    else url.searchParams.delete('status');

    if (currentYear && currentYear !== 'Năm Phát Hành') url.searchParams.set('year', currentYear);
    else url.searchParams.delete('year');

    if (currentSort && currentSort !== 'Sắp Xếp') url.searchParams.set('sort', currentSort);
    else url.searchParams.delete('sort');

    url.searchParams.delete('page');
    window.history.replaceState({}, '', url.toString());
  }
}

function initIosScheduleModal() {
  const openBtn = document.getElementById('openScheduleModalBtn');
  const overlay = document.getElementById('scheduleModalOverlay');
  const closeBtn = document.getElementById('closeScheduleModalBtn');
  const handleClose = document.getElementById('sheetHandleClose');
  const sheetContent = document.getElementById('scheduleBottomSheet');
  const iosDayButtons = document.querySelectorAll('.ios-day-btn');

  if (!openBtn || !overlay) return;

  openBtn.addEventListener('click', (e) => {
    e.preventDefault();
    overlay.classList.add('active');
    document.body.style.overflow = 'hidden';
  });

  function closeModal() {
    overlay.classList.remove('active');
    document.body.style.overflow = '';
  }

  if (closeBtn) closeBtn.addEventListener('click', closeModal);
  if (handleClose) handleClose.addEventListener('click', closeModal);

  if (sheetContent) {
    sheetContent.addEventListener('click', (e) => {
      e.stopPropagation();
    });
  }

  overlay.addEventListener('click', (e) => {
    if (e.target === overlay) {
      closeModal();
    }
  });

  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && overlay.classList.contains('active')) {
      closeModal();
    }
  });

  iosDayButtons.forEach(btn => {
    btn.addEventListener('click', function() {
      const selectedDay = this.getAttribute('data-day') || 'all';
      syncActiveDay(selectedDay);
      currentDay = selectedDay;
      currentPage = 1;
      filterMovies();

      updateSectionTitle(selectedDay);

      const url = new URL(window.location.href);
      if (selectedDay && selectedDay !== 'all') {
        url.searchParams.set('day', selectedDay);
      } else {
        url.searchParams.delete('day');
      }
      url.searchParams.delete('page');
      window.history.replaceState({}, '', url.toString());

      closeModal();

      const moviesCol = document.querySelector('.main-movies-column');
      if (moviesCol) {
        moviesCol.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    });
  });
}

function initIosCategoryModal() {
  const openBtn = document.getElementById('openCategoryModalBtn');
  const overlay = document.getElementById('categoryModalOverlay');
  const closeBtn = document.getElementById('closeCategoryModalBtn');
  const handleClose = document.getElementById('categorySheetHandleClose');
  const sheetContent = document.getElementById('categoryBottomSheet');
  const applyBtn = document.getElementById('applyCategoryFilterBtn');
  const filterBtns = document.querySelectorAll('.filter-sheet-btn');

  if (!openBtn || !overlay) return;

  openBtn.addEventListener('click', (e) => {
    e.preventDefault();
    overlay.classList.add('active');
    document.body.style.overflow = 'hidden';
  });

  function closeModal() {
    overlay.classList.remove('active');
    document.body.style.overflow = '';
  }

  if (closeBtn) closeBtn.addEventListener('click', closeModal);
  if (handleClose) handleClose.addEventListener('click', closeModal);

  if (sheetContent) {
    sheetContent.addEventListener('click', (e) => {
      e.stopPropagation();
    });
  }

  overlay.addEventListener('click', (e) => {
    if (e.target === overlay) {
      closeModal();
    }
  });

  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && overlay.classList.contains('active')) {
      closeModal();
    }
  });

  filterBtns.forEach(btn => {
    btn.addEventListener('click', function() {
      const parentGroup = this.parentElement;
      if (parentGroup) {
        parentGroup.querySelectorAll('.filter-sheet-btn').forEach(b => b.classList.remove('active'));
      }
      this.classList.add('active');

      const filterType = this.getAttribute('data-type');
      const filterVal = this.getAttribute('data-value');

      if (filterType === 'category') {
        currentCategory = filterVal;
        currentDay = 'all';
        syncActiveDay('all');
        updateSectionTitle('all');
        syncActiveCategory(filterVal);
      } else if (filterType === 'genre') {
        const desktopSelect = document.getElementById('filterGenre');
        if (desktopSelect) desktopSelect.value = filterVal;
      } else if (filterType === 'status') {
        const desktopSelect = document.getElementById('filterStatus');
        if (desktopSelect) desktopSelect.value = filterVal;
      } else if (filterType === 'year') {
        const desktopSelect = document.getElementById('filterYear');
        if (desktopSelect) desktopSelect.value = filterVal;
      } else if (filterType === 'sort') {
        const desktopSelect = document.getElementById('filterSort');
        if (desktopSelect) desktopSelect.value = filterVal;
      }
    });
  });

  if (applyBtn) {
    applyBtn.addEventListener('click', () => {
      closeModal();
      applyFilterSelection(true);
    });
  }
}

function syncActiveDay(selectedDay) {
  document.querySelectorAll('.day-tab').forEach(tab => {
    if (tab.getAttribute('data-day') === selectedDay) {
      tab.classList.add('active');
    } else {
      tab.classList.remove('active');
    }
  });

  document.querySelectorAll('.ios-day-btn').forEach(btn => {
    if (btn.getAttribute('data-day') === selectedDay) {
      btn.classList.add('active');
    } else {
      btn.classList.remove('active');
    }
  });
}

function highlightCurrentDay() {
  const today = new Date().getDay();
  const dayMap = {
    0: 'cn',
    1: 't2',
    2: 't3',
    3: 't4',
    4: 't5',
    5: 't6',
    6: 't7'
  };

  const currentDayKey = dayMap[today];
  const targetTab = document.querySelector(`.day-tab[data-day="${currentDayKey}"]`);
  const targetIosBtn = document.querySelector(`.ios-day-btn[data-day="${currentDayKey}"]`);
  
  if (targetTab) {
    targetTab.classList.add('is-today');
  }
  if (targetIosBtn) {
    targetIosBtn.classList.add('is-today');
  }
}

function escapeMovieHtml(str) {
  if (str === null || str === undefined) return '';
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function initInitialPagination() {
  const container = document.getElementById('moviesPagination');
  if (!container) return;
  const total = parseInt(container.getAttribute('data-total') || '0', 10);
  const pages = parseInt(container.getAttribute('data-pages') || '1', 10);
  if (total > 0 && pages > 1) {
    renderPagination(total, pages);
  }
}

async function filterMovies(isBackgroundSync = false) {
  const moviesGrid = document.getElementById('moviesGrid');
  if (!moviesGrid) return;

  // Thu thập danh sách ID và tập phim hiện tại trước khi refresh ngầm
  const existingMoviesMap = new Map();
  if (isBackgroundSync) {
    moviesGrid.querySelectorAll('.movie-card[data-id]').forEach(card => {
      const mid = card.getAttribute('data-id');
      const epEl = card.querySelector('.movie-badge-ep');
      existingMoviesMap.set(String(mid), epEl ? epEl.textContent.trim() : '');
    });
  }

  const params = new URLSearchParams();
  params.set('action', 'list');
  params.set('page', currentPage);
  params.set('limit', itemsPerPage);
  if (currentCategory && currentCategory !== 'all') params.set('type', currentCategory);
  if (currentDay && currentDay !== 'all') params.set('day', currentDay);
  if (currentGenre && currentGenre !== 'all' && currentGenre !== 'Tất Cả Thể Loại') params.set('genre', currentGenre);
  if (currentStatus && currentStatus !== 'all' && currentStatus !== 'Trạng Thái') params.set('status', currentStatus);
  if (currentYear && currentYear !== 'all' && currentYear !== 'Năm Phát Hành') params.set('year', currentYear);
  if (currentSort && currentSort !== 'Sắp Xếp' && currentSort !== 'all') params.set('sort', currentSort);

  try {
    const res = await fetch(`api/movies.php?${params.toString()}`);
    const data = await res.json();
    if (!data.success || !Array.isArray(data.movies)) return;

    if (data.movies.length === 0) {
      moviesGrid.innerHTML = `
        <div id="emptyScheduleNotice" style="grid-column: 1 / -1; padding: 40px 20px; text-align: center; background: rgba(255, 255, 255, 0.02); border: 1px dashed var(--border-color); border-radius: var(--radius-md); color: var(--text-muted);">
          <i class="fa-solid fa-filter-circle-xmark" style="font-size: 2rem; color: var(--text-dim); margin-bottom: 12px; display: block;"></i>
          <p style="font-size: 1rem; font-weight: 600; color: #fff; margin-bottom: 4px;">Không tìm thấy bộ phim phù hợp</p>
          <p style="font-size: 0.85rem; color: var(--text-dim);">Hãy thử chọn lại thể loại, năm hoặc trạng thái khác nhé.</p>
        </div>
      `;
      renderPagination(0, 1);
      return;
    }

    let hasNewlyUpdated = false;

    moviesGrid.innerHTML = data.movies.map(movie => {
      let isLiveUpdated = false;
      if (isBackgroundSync) {
        const mKey = String(movie.id);
        if (!existingMoviesMap.has(mKey) || existingMoviesMap.get(mKey) !== movie.current_ep) {
          isLiveUpdated = true;
          hasNewlyUpdated = true;
        }
      }

      return `
      <article class="movie-card ${isLiveUpdated ? 'card-live-glow' : ''}" style="display: flex; animation: fadeInUp 0.3s ease forwards;" data-id="${movie.id}">
        <div class="movie-thumb-wrapper">
          <img src="${escapeMovieHtml(movie.poster)}" alt="${escapeMovieHtml(movie.title)}" class="movie-thumb" loading="lazy" onerror="this.src='assets/images/wang_lin_cultivate.jpg'">
          <div class="movie-badge-top">
            <span class="badge ${movie.type === 'hoathinh3d' || movie.type === '3d' ? 'badge-hot' : (movie.type === 'phimtruyenhinh' || movie.type === 'series' ? 'badge-series' : 'badge-hd')}">
              ${escapeMovieHtml(movie.badge)}
            </span>
            ${movie.day !== 'none' ? `
              <span class="badge" style="background: rgba(0, 0, 0, 0.65); backdrop-filter: blur(4px); border: 1px solid rgba(255, 255, 255, 0.15); margin-left: 4px;">
                ${escapeMovieHtml(movie.day_name)}
              </span>
            ` : ''}
            ${isLiveUpdated ? `
              <span class="badge badge-live-new" style="background: linear-gradient(135deg, #10b981, #059669); color: #fff; margin-left: 4px; box-shadow: 0 0 10px rgba(16,185,129,0.5);">
                <i class="fa-solid fa-bolt"></i> Vừa lên sóng
              </span>
            ` : ''}
          </div>
          <button type="button" class="card-fav-btn" data-id="${movie.id}" data-slug="${escapeMovieHtml(movie.slug)}" data-title="${escapeMovieHtml(movie.title)}" data-thumb="${escapeMovieHtml(movie.poster)}" data-type="${escapeMovieHtml(movie.type)}" data-ep="${escapeMovieHtml(movie.current_ep)}" data-rating="${movie.rating}" data-views="${escapeMovieHtml(movie.views)}" title="Thêm vào Tủ Phim" aria-label="Thêm vào Tủ Phim">
            <i class="fa-solid fa-heart"></i>
          </button>
          <div class="movie-badge-ep ${isLiveUpdated ? 'ep-live-pulse' : ''}">${escapeMovieHtml(movie.current_ep)}</div>
          <a href="phim/${escapeMovieHtml(movie.slug || movie.id)}" class="movie-play-hover" title="Xem chi tiết phim ${escapeMovieHtml(movie.title)}">
            <div class="play-icon-circle"><i class="fa-solid fa-play"></i></div>
          </a>
        </div>
        <div class="movie-info">
          <h4 class="movie-title" title="${escapeMovieHtml(movie.title)}">
            <a href="phim/${escapeMovieHtml(movie.slug || movie.id)}">${escapeMovieHtml(movie.title)}</a>
          </h4>
          <div class="movie-extra">
            <span class="movie-rating"><i class="fa-solid fa-star"></i> ${movie.rating}</span>
            <span class="movie-views"><i class="fa-solid fa-eye"></i> ${movie.views}</span>
          </div>
        </div>
      </article>
      `;
    }).join('');

    renderPagination(data.total, data.total_pages);
    if (typeof initGlobalFavoriteButtons === 'function') {
      initGlobalFavoriteButtons();
    }

    if (isBackgroundSync) {
      animateSubtitleLiveSync(hasNewlyUpdated);
      if (hasNewlyUpdated) {
        showLiveScheduleToast();
      }
    }
  } catch (err) {
  }
}

function renderPagination(totalItems, totalPages) {
  const container = document.getElementById('moviesPagination');
  if (!container) return;

  if (totalPages <= 1) {
    container.innerHTML = '';
    container.style.display = 'none';
    return;
  }

  container.style.display = 'block';

  let html = '<div class="pagination-bar" style="display: flex; align-items: center; justify-content: center; gap: 8px; flex-wrap: wrap;">';

  const prevDisabled = currentPage <= 1 ? 'disabled style="opacity: 0.35; cursor: not-allowed;"' : '';
  html += `<button type="button" class="page-nav-btn prev" ${prevDisabled} data-page="${currentPage - 1}"><i class="fa-solid fa-chevron-left"></i> Trước</button>`;

  let startPage = Math.max(1, currentPage - 2);
  let endPage = Math.min(totalPages, currentPage + 2);

  if (startPage > 1) {
    html += `<button type="button" class="page-num-btn" data-page="1">1</button>`;
    if (startPage > 2) {
      html += `<span class="page-dots" style="color: var(--text-dim); padding: 0 4px; font-weight: 700;">...</span>`;
    }
  }

  for (let p = startPage; p <= endPage; p++) {
    const isActive = (p === currentPage) ? 'active' : '';
    html += `<button type="button" class="page-num-btn ${isActive}" data-page="${p}">${p}</button>`;
  }

  if (endPage < totalPages) {
    if (endPage < totalPages - 1) {
      html += `<span class="page-dots" style="color: var(--text-dim); padding: 0 4px; font-weight: 700;">...</span>`;
    }
    html += `<button type="button" class="page-num-btn" data-page="${totalPages}">${totalPages}</button>`;
  }

  const nextDisabled = currentPage >= totalPages ? 'disabled style="opacity: 0.35; cursor: not-allowed;"' : '';
  html += `<button type="button" class="page-nav-btn next" ${nextDisabled} data-page="${currentPage + 1}">Tiếp <i class="fa-solid fa-chevron-right"></i></button>`;
  html += '</div>';

  html += `<div class="pagination-info" style="text-align: center; font-size: 0.82rem; color: var(--text-dim); margin-top: 12px; display: flex; align-items: center; justify-content: center; gap: 8px;"><span>Trang <strong style="color: var(--secondary);">${currentPage}</strong> / ${totalPages}</span><span>&bull;</span><span>Hiển thị ${totalItems} phim</span></div>`;

  container.innerHTML = html;

  container.querySelectorAll('button[data-page]').forEach(btn => {
    btn.addEventListener('click', function() {
      if (this.disabled) return;
      const targetP = parseInt(this.getAttribute('data-page'));
      if (targetP && targetP !== currentPage && targetP >= 1 && targetP <= totalPages) {
        currentPage = targetP;
        filterMovies();
        const moviesCol = document.querySelector('.main-movies-column');
        if (moviesCol) {
          moviesCol.scrollIntoView({ behavior: 'smooth', block: 'start' });
        }
        const url = new URL(window.location.href);
        if (currentPage > 1) {
          url.searchParams.set('page', currentPage);
        } else {
          url.searchParams.delete('page');
        }
        window.history.replaceState({}, '', url.toString());
      }
    });
  });
}

const styleSheet = document.createElement("style");
styleSheet.innerText = `
  @keyframes fadeInUp {
    from {
      opacity: 0;
      transform: translateY(10px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
`;
document.head.appendChild(styleSheet);

function initScheduleScrollArrows() {
  const leftBtn = document.getElementById('schedScrollLeft');
  const rightBtn = document.getElementById('schedScrollRight');
  const scrollContainer = document.getElementById('scheduleDaysBar');

  if (!leftBtn || !rightBtn || !scrollContainer) return;

  leftBtn.addEventListener('click', () => {
    scrollContainer.scrollBy({
      left: -200,
      behavior: 'smooth'
    });
  });

  rightBtn.addEventListener('click', () => {
    scrollContainer.scrollBy({
      left: 200,
      behavior: 'smooth'
    });
  });
}

/**
 * ========================================================
 * REAL-TIME LIVE SCHEDULE WATCHER (Tự động cập nhật không tải lại trang)
 * ========================================================
 */
function initLiveScheduleWatcher() {
  const moviesGrid = document.getElementById('moviesGrid');
  if (!moviesGrid) return; // Chỉ kích hoạt khi đang ở trang có lưới lịch phim

  // Lấy phiên bản dữ liệu hiện tại ngay khi vào trang
  checkScheduleVersion(true);

  // Thiết lập chu kỳ kiểm tra tự động mỗi 25 giây
  if (liveScheduleTimer) clearInterval(liveScheduleTimer);
  liveScheduleTimer = setInterval(() => {
    // Chỉ check khi người dùng đang active trên tab (tiết kiệm pin & CPU & băng thông)
    if (!document.hidden) {
      checkScheduleVersion(false);
    }
  }, 25000);

  // Khi người dùng chuyển tab và quay lại, lập tức kiểm tra ngay
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) {
      checkScheduleVersion(false);
    }
  });

  window.addEventListener('focus', () => {
    checkScheduleVersion(false);
  });
}

async function checkScheduleVersion(isInitial = false) {
  if (isCheckingLiveSchedule) return;
  isCheckingLiveSchedule = true;

  try {
    const res = await fetch('api/movies.php?action=check_latest_update&_t=' + Date.now(), {
      cache: 'no-store'
    });
    const data = await res.json();

    if (data && data.success && data.version) {
      if (isInitial) {
        liveScheduleVersion = data.version;
      } else if (liveScheduleVersion && liveScheduleVersion !== data.version) {
        // Phát hiện có phim mới hoặc tập mới được cập nhật vào CSDL!
        liveScheduleVersion = data.version;
        // Tự động tải và cập nhật DOM mượt mà không reload trang
        await filterMovies(true);
      } else if (!liveScheduleVersion) {
        liveScheduleVersion = data.version;
      }
    }
  } catch (err) {
    // Không làm gián đoạn trải nghiệm nếu mất mạng tạm thời
  } finally {
    isCheckingLiveSchedule = false;
  }
}

function animateSubtitleLiveSync(hasNew = false) {
  const subEl = document.getElementById('mainSectionSubtitle');
  if (!subEl) return;

  const originalContent = subEl.innerHTML;
  if (hasNew) {
    subEl.innerHTML = `<i class="fa-solid fa-bolt-lightning fa-beat" style="color: #10b981;"></i> <span style="color: #10b981; font-weight: 700;">Vừa cập nhật tập phim mới!</span>`;
  } else {
    subEl.innerHTML = `<i class="fa-solid fa-rotate fa-spin" style="color: var(--secondary);"></i> <span>Đã đồng bộ lịch chiếu mới nhất</span>`;
  }

  setTimeout(() => {
    subEl.innerHTML = originalContent;
  }, 4500);
}

function showLiveScheduleToast() {
  let toast = document.getElementById('liveScheduleToast');
  if (!toast) {
    toast = document.createElement('div');
    toast.id = 'liveScheduleToast';
    toast.className = 'live-schedule-toast';
    document.body.appendChild(toast);
  }

  toast.innerHTML = `
    <div class="toast-glow-bar"></div>
    <div class="toast-body">
      <div class="toast-icon">
        <i class="fa-solid fa-bolt-lightning"></i>
      </div>
      <div class="toast-text">
        <h5 class="toast-title">Lịch Chiếu Vừa Cập Nhật!</h5>
        <p class="toast-desc">Vừa có phim hoặc tập mới được lên sóng.</p>
      </div>
      <button type="button" class="toast-close" onclick="this.closest('#liveScheduleToast').classList.remove('show')" aria-label="Đóng">
        <i class="fa-solid fa-xmark"></i>
      </button>
    </div>
  `;

  // Kích hoạt class show
  setTimeout(() => {
    toast.classList.add('show');
  }, 50);

  // Tự động ẩn sau 5 giây
  if (toast._timer) clearTimeout(toast._timer);
  toast._timer = setTimeout(() => {
    toast.classList.remove('show');
  }, 5000);
}

