document.addEventListener('DOMContentLoaded', function () {
  const downloadBtn = document.getElementById('downloadPdfBtn');
  if (downloadBtn) {
    downloadBtn.addEventListener('click', function () {
      
      // Check if html2pdf is available
      if (typeof html2pdf === 'undefined') {
        alert('PDF generator library (html2pdf) is not loaded. Please try again later.');
        return;
      }

      // 1) Dynamically extract products from the DOM
      const productItems = document.querySelectorAll('.product-item');
      const tableBody = document.getElementById('pdf-table-body');
      
      // Clear previous dynamically created elements
      tableBody.innerHTML = '';
      
      // Inject logo if available
      const logoEl = document.getElementById('pdf-logo');
      if (logoEl && typeof LOGO_BASE64 !== 'undefined' && LOGO_BASE64) {
        logoEl.src = LOGO_BASE64;
        logoEl.style.display = 'block';
        console.log('PDF Logo injected successfully');
      } else {
        console.warn('PDF Logo injection failed: image element or LOGO_BASE64 missing');
      }

      productItems.forEach((item, index) => {
        const sno = (index + 1).toString();
        const productNameEl = item.querySelector('.product-name');
        const categoryEl = item.querySelector('.product-category');
        const priceEl = item.querySelector('.product-price');
        
        const name = productNameEl ? productNameEl.innerText.trim() : '';
        const category = categoryEl ? categoryEl.innerText.trim() : '';
        const price = priceEl ? priceEl.innerText.trim() : '';
        
        // Append row to HTML table body
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td style="padding: 10px; border: 1px solid #ddd;">${sno}</td>
          <td style="padding: 10px; border: 1px solid #ddd; text-align: left;">${name}</td>
          <td style="padding: 10px; border: 1px solid #ddd;">${category}</td>
          <td style="padding: 10px; border: 1px solid #ddd;">${price}</td>
        `;
        tableBody.appendChild(tr);
      });

      // 2) Generate PDF from the hidden container
      const element = document.getElementById('pdf-content');
      
      const opt = {
        margin:       [10, 20, 40, 20], // top, left, bottom, right
        filename:     'GP-Crackers-Letterhead.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { scale: 2 },
        jsPDF:        { unit: 'pt', format: 'a4', orientation: 'portrait' }
      };

      // Generate and save the PDF
      html2pdf().set(opt).from(element).save();
    });
  }
});
