/* =============================================
   app.js — E-Book SMA Global JS
   ============================================= */

'use strict';

// -----------------------------------------------
// Sidebar Toggle
// -----------------------------------------------
function initSidebar() {
  const sidebar  = document.getElementById('sidebar');
  const overlay  = document.getElementById('sidebarOverlay');
  const toggle   = document.getElementById('sidebarToggle');

  if (!sidebar) return;

  function openSidebar() {
    sidebar.classList.add('open');
    overlay.classList.add('show');
    document.body.style.overflow = 'hidden';
  }
  function closeSidebar() {
    sidebar.classList.remove('open');
    overlay.classList.remove('show');
    document.body.style.overflow = '';
  }

  toggle  && toggle.addEventListener('click', () => sidebar.classList.contains('open') ? closeSidebar() : openSidebar());
  overlay && overlay.addEventListener('click', closeSidebar);

  // Close on resize > 768
  window.addEventListener('resize', () => { if (window.innerWidth > 768) closeSidebar(); });
}

// -----------------------------------------------
// Toast Notification System
// -----------------------------------------------
function showToast(type, title, message, duration = 3500) {
  const icons = { success: 'fa-check-circle', danger: 'fa-times-circle', warning: 'fa-exclamation-triangle', info: 'fa-info-circle' };
  const container = document.getElementById('toastContainer');
  if (!container) return;

  const toast = document.createElement('div');
  toast.className = `toast-item ${type}`;
  toast.innerHTML = `
    <i class="fas ${icons[type] || icons.info} toast-icon"></i>
    <div class="toast-body">
      <div class="toast-title">${title}</div>
      ${message ? `<div class="toast-text">${message}</div>` : ''}
    </div>
    <button class="toast-close" onclick="dismissToast(this.parentElement)"><i class="fas fa-times"></i></button>
  `;
  container.appendChild(toast);
  setTimeout(() => dismissToast(toast), duration);
}

function dismissToast(toast) {
  if (!toast || toast.classList.contains('hiding')) return;
  toast.classList.add('hiding');
  setTimeout(() => toast.remove(), 350);
}

// -----------------------------------------------
// API Helper
// -----------------------------------------------
async function apiGet(url) {
  const res  = await fetch(BASE_URL + url);
  return res.json();
}

async function apiPost(url, formData) {
  const res = await fetch(BASE_URL + url, { method: 'POST', body: formData });
  return res.json();
}

async function apiDelete(url) {
  const res = await fetch(BASE_URL + url, { method: 'DELETE' });
  return res.json();
}

// -----------------------------------------------
// Debounce
// -----------------------------------------------
function debounce(fn, delay = 350) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), delay); };
}

// -----------------------------------------------
// PDF Modal Viewer
// -----------------------------------------------
function viewEbook(id) {
  const modal     = new bootstrap.Modal(document.getElementById('pdfModal'));
  const frame     = document.getElementById('pdfFrame');
  const loading   = document.getElementById('pdfLoading');
  const titleEl   = document.getElementById('pdfModalTitle');
  const authorEl  = document.getElementById('pdfModalAuthor');
  const downloadEl= document.getElementById('btnDownload');
  const detailsEl = document.getElementById('ebookDetails');

  // Reset state
  frame.classList.add('d-none');
  loading.style.display = 'flex';
  frame.src = '';
  modal.show();

  apiGet(`api/ebooks/${id}`).then(res => {
    if (!res.status) {
      showToast('danger', 'Error', 'E-Book tidak ditemukan');
      modal.hide(); return;
    }
    const e = res.data;
    titleEl.textContent  = e.judul;
    authorEl.textContent = `Penulis: ${e.penulis} · Kategori: ${e.kategori}`;
    downloadEl.href      = e.file_url;
    downloadEl.setAttribute('download', e.judul + '.pdf');

    if (detailsEl && e.deskripsi) {
      detailsEl.innerHTML = `<div class="modal-ebook-desc"><i class="fas fa-info-circle me-2 text-primary-color"></i>${e.deskripsi}</div>`;
      detailsEl.style.display = '';
    } else if (detailsEl) {
      detailsEl.style.display = 'none';
    }

    // Load PDF in iframe
    frame.src = e.file_url;
    frame.onload = () => {
      loading.style.display = 'none';
      frame.classList.remove('d-none');
    };
    // Fallback timeout
    setTimeout(() => {
      if (frame.classList.contains('d-none')) {
        loading.style.display = 'none';
        frame.classList.remove('d-none');
      }
    }, 3000);
  }).catch(() => {
    showToast('danger', 'Koneksi gagal', 'Tidak dapat memuat ebook.');
    modal.hide();
  });
}

// -----------------------------------------------
// User Ebook Page
// -----------------------------------------------
function initEbookPage() {
  let currentPage = 1;
  let currentSearch = '';
  let currentKategori = '';
  const LIMIT = 12;

  const grid      = document.getElementById('ebookGrid');
  const searchInp = document.getElementById('searchInput');
  const searchClr = document.getElementById('searchClear');
  const katFilter = document.getElementById('kategoriFilter');
  const countEl   = document.getElementById('resultsCount');
  const paginEl   = document.getElementById('paginationWrapper');

  // Initial load
  loadEbooks(1);

  // Events
  searchInp && searchInp.addEventListener('input', debounce(e => {
    currentSearch = e.target.value.trim();
    searchClr && searchClr.classList.toggle('d-none', !currentSearch);
    loadEbooks(1);
  }));

  searchClr && searchClr.addEventListener('click', () => {
    searchInp.value = '';
    currentSearch = '';
    searchClr.classList.add('d-none');
    loadEbooks(1);
  });

  katFilter && katFilter.addEventListener('change', e => {
    currentKategori = e.target.value;
    loadEbooks(1);
  });

  function loadEbooks(page) {
    currentPage = page;
    grid.innerHTML = renderSkeletons(8);

    let url = `api/ebooks?page=${page}&limit=${LIMIT}`;
    if (currentSearch)   url += `&search=${encodeURIComponent(currentSearch)}`;
    if (currentKategori) url += `&kategori=${encodeURIComponent(currentKategori)}`;

    apiGet(url).then(res => {
      if (!res.status) {
        grid.innerHTML = renderEmpty('Gagal memuat data', 'Terjadi kesalahan pada server.');
        return;
      }
      const { ebooks, total, total_pages } = res.data;

      if (countEl) {
        countEl.textContent = `Menampilkan ${ebooks.length} dari ${total} e-book`;
      }

      if (ebooks.length === 0) {
        grid.innerHTML = renderEmpty(
          currentSearch ? `Hasil "${currentSearch}" tidak ditemukan` : 'Belum ada e-book',
          currentSearch ? 'Coba kata kunci lain.' : 'Admin belum mengunggah e-book.'
        );
        if (paginEl) paginEl.innerHTML = '';
        return;
      }

      grid.innerHTML = ebooks.map(renderCard).join('');
      if (paginEl) paginEl.innerHTML = renderPagination(page, total_pages);

      // Animate cards
      grid.querySelectorAll('.ebook-card').forEach((card, i) => {
        card.style.animationDelay = `${i * 0.04}s`;
        card.classList.add('fade-in');
      });
    }).catch(() => {
      grid.innerHTML = renderEmpty('Koneksi gagal', 'Periksa koneksi Anda.');
    });
  }

  function renderCard(e) {
    const cover = e.cover_url
      ? `<img src="${e.cover_url}" alt="${escHtml(e.judul)}" loading="lazy">`
      : `<div class="ebook-cover-placeholder"><i class="fas fa-book-open"></i></div>`;
    return `
      <div class="ebook-card" onclick="viewEbook(${e.id})">
        <div class="ebook-cover">
          ${cover}
          <div class="ebook-overlay"><button class="btn-read"><i class="fas fa-eye me-1"></i>Baca</button></div>
        </div>
        <div class="ebook-info">
          <span class="ebook-kategori">${escHtml(e.kategori)}</span>
          <h4 class="ebook-title">${escHtml(e.judul)}</h4>
          <p class="ebook-author"><i class="fas fa-user-pen me-1"></i>${escHtml(e.penulis)}</p>
        </div>
      </div>`;
  }

  function renderPagination(current, total) {
    if (total <= 1) return '';
    let html = '';
    const prev = current > 1;
    const next = current < total;
    html += `<button class="page-btn" onclick="window.ebookPage.go(${current-1})" ${!prev?'disabled':''}><i class="fas fa-chevron-left"></i></button>`;
    for (let p = Math.max(1, current-2); p <= Math.min(total, current+2); p++) {
      html += `<button class="page-btn ${p===current?'active':''}" onclick="window.ebookPage.go(${p})">${p}</button>`;
    }
    html += `<button class="page-btn" onclick="window.ebookPage.go(${current+1})" ${!next?'disabled':''}><i class="fas fa-chevron-right"></i></button>`;
    return html;
  }

  // Expose pagination go
  window.ebookPage = { go: loadEbooks };
}

// -----------------------------------------------
// Skeleton Loader
// -----------------------------------------------
function renderSkeletons(n) {
  return `<div class="loading-grid">${Array(n).fill(`
    <div class="skeleton-card">
      <div class="skeleton-cover"></div>
      <div class="skeleton-body">
        <div class="skeleton-line w-60"></div>
        <div class="skeleton-line w-80"></div>
        <div class="skeleton-line w-40"></div>
      </div>
    </div>`).join('')}</div>`;
}

// -----------------------------------------------
// Empty State
// -----------------------------------------------
function renderEmpty(title, subtitle) {
  return `<div class="empty-state">
    <i class="fas fa-book-open"></i>
    <h4>${title}</h4>
    <p>${subtitle}</p>
  </div>`;
}

// -----------------------------------------------
// HTML Escape
// -----------------------------------------------
function escHtml(str) {
  if (!str) return '';
  return str.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
