// Define types for jQuery and Turn.js
declare global {
  interface Window {
    $: any; // jQuery
    pdfjsLib: any; // PDF.js library
  }
}

// jQuery for Turn.js
declare const $: any;

// Wait for DOM to be fully loaded
document.addEventListener('DOMContentLoaded', () => {
  // References to DOM elements
  const flipBookElement = document.getElementById('flipbook') as HTMLElement;
  const uploadBtn = document.getElementById('upload-btn') as HTMLButtonElement;
  const pdfUpload = document.getElementById('pdf-upload') as HTMLInputElement;
  const fullscreenBtn = document.getElementById('fullscreen-btn') as HTMLButtonElement;
  const prevPageBtn = document.getElementById('prev-page-btn') as HTMLButtonElement;
  const nextPageBtn = document.getElementById('next-page-btn') as HTMLButtonElement;

  // Total number of pages
  let totalPages = 0;
  // Fullscreen mode flag
  let isFullscreen = false;
  // Flag to check if flipbook is initialized
  let isFlipBookInitialized = false;

  // Set the worker source for PDF.js
  const pdfjsLib = window.pdfjsLib;
  pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.worker.min.js';

  /**
   * Initialize the Turn.js flipbook
   */
  const initializeFlipBook = () => {
    if (isFlipBookInitialized) {
      return;
    }

    // Initialize Turn.js flipbook
    $('#flipbook').turn({
      width: flipBookElement.offsetWidth,
      height: flipBookElement.offsetHeight,
      autoCenter: true,
      display: 'double',
      acceleration: true,
      elevation: 50,
      gradients: true,
      when: {
        turning: function(_event: Event, page: number) {
          console.log('Turning to page:', page);
        },
        turned: function(_event: Event, page: number) {
          console.log('Turned to page:', page);
        }
      }
    });

    isFlipBookInitialized = true;

    // Make it responsive
    $(window).resize(function() {
      resizeFlipbook();
    });
  };

  /**
   * Resize the flipbook based on window size
   */
  const resizeFlipbook = () => {
    if (!isFlipBookInitialized) return;

    const width = flipBookElement.parentElement?.offsetWidth || 800;
    const height = flipBookElement.parentElement?.offsetHeight || 600;

    $('#flipbook').turn('size', width, height);
  };

  /**
   * Load a PDF file and render its pages in the flipbook
   */
  const loadPDF = async (pdfUrl: string) => {
    try {
      // Clear the existing pages
      if (isFlipBookInitialized) {
        // Destroy the flipbook if it's already initialized
        try {
          $('#flipbook').turn('destroy');
          isFlipBookInitialized = false;
        } catch (e) {
          console.warn('Could not destroy flipbook:', e);
        }
      }

      flipBookElement.innerHTML = '';

      // Add a loading message
      const loadingMsg = document.createElement('div');
      loadingMsg.className = 'page loading-message';
      loadingMsg.innerHTML = '<p>Loading PDF...</p>';
      flipBookElement.appendChild(loadingMsg);

      // Load the PDF document
      const loadingTask = pdfjsLib.getDocument(pdfUrl);
      const pdf = await loadingTask.promise;
      totalPages = pdf.numPages;

      // Remove the loading message
      flipBookElement.innerHTML = '';

      // Create hard cover pages
      const frontCover = document.createElement('div');
      frontCover.className = 'hard';
      frontCover.innerHTML = '<div class="cover-title">PDF Flipbook</div>';
      flipBookElement.appendChild(frontCover);

      // Create pages for the PDF content
      for (let i = 1; i <= totalPages; i++) {
        const pageDiv = document.createElement('div');
        pageDiv.className = 'page';
        pageDiv.setAttribute('data-page-number', i.toString());
        flipBookElement.appendChild(pageDiv);
      }

      // Create back cover
      const backCover = document.createElement('div');
      backCover.className = 'hard';
      flipBookElement.appendChild(backCover);

      // Initialize the flipbook
      initializeFlipBook();

      // Render each page
      for (let i = 1; i <= totalPages; i++) {
        renderPage(pdf, i);
      }
    } catch (error) {
      console.error('Error loading PDF:', error);
      flipBookElement.innerHTML = '<div class="page error-message"><p>Error loading PDF. Please try again or upload a different file.</p></div>';
    }
  };

  /**
   * Render a specific page from the PDF
   */
  const renderPage = async (pdf: any, pageNumber: number) => {
    try {
      // Get the page
      const page = await pdf.getPage(pageNumber);

      // Get the page element
      const pageDiv = flipBookElement.querySelector(`[data-page-number="${pageNumber}"]`);
      if (!pageDiv) return;

      // Set up the canvas for rendering
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      if (!context) return;

      const viewport = page.getViewport({ scale: 1.5 });

      // Set canvas dimensions to match the viewport
      canvas.width = viewport.width;
      canvas.height = viewport.height;

      // Render the page
      const renderContext = {
        canvasContext: context,
        viewport: viewport
      };

      await page.render(renderContext).promise;

      // Add the canvas to the page div
      pageDiv.innerHTML = '';
      pageDiv.appendChild(canvas);

      // Add page number
      const pageNumberDiv = document.createElement('div');
      pageNumberDiv.className = 'page-number';
      pageNumberDiv.textContent = pageNumber.toString();
      pageDiv.appendChild(pageNumberDiv);
    } catch (error) {
      console.error(`Error rendering page ${pageNumber}:`, error);
    }
  };

  /**
   * Handle file upload
   */
  const handleFileUpload = () => {
    if (pdfUpload.files && pdfUpload.files.length > 0) {
      const file = pdfUpload.files[0];

      // Check if the file is a PDF
      if (file.type !== 'application/pdf') {
        alert('Please upload a PDF file.');
        return;
      }

      // Create a URL for the uploaded file
      const fileURL = URL.createObjectURL(file);

      // Load the PDF
      loadPDF(fileURL);
    } else {
      alert('Please select a PDF file first.');
    }
  };

  /**
   * Toggle fullscreen mode
   */
  const toggleFullscreen = () => {
    isFullscreen = !isFullscreen;

    if (isFullscreen) {
      // Enter fullscreen
      const container = flipBookElement.parentElement;
      if (container) {
        container.classList.add('fullscreen');
        document.body.style.overflow = 'hidden';
      }
    } else {
      // Exit fullscreen
      const container = flipBookElement.parentElement;
      if (container) {
        container.classList.remove('fullscreen');
        document.body.style.overflow = '';
      }
    }

    // Resize the flipbook after toggling fullscreen
    setTimeout(resizeFlipbook, 300);
  };

  /**
   * Go to the previous page
   */
  const goToPrevPage = () => {
    if (isFlipBookInitialized) {
      $('#flipbook').turn('previous');
    }
  };

  /**
   * Go to the next page
   */
  const goToNextPage = () => {
    if (isFlipBookInitialized) {
      $('#flipbook').turn('next');
    }
  };

  // Add event listeners
  uploadBtn.addEventListener('click', handleFileUpload);
  fullscreenBtn.addEventListener('click', toggleFullscreen);
  prevPageBtn.addEventListener('click', goToPrevPage);
  nextPageBtn.addEventListener('click', goToNextPage);

  // Load the sample PDF
  loadPDF('./sample.pdf');
});

export {};
