document.addEventListener('DOMContentLoaded', function () {
  const downloadBtn = document.getElementById('downloadCartPdfBtn');
  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;
      }

      const cart = typeof getCart === 'function' ? getCart() : [];
      if (cart.length === 0) {
        alert('Your cart is empty.');
        return;
      }

      const tableBody = document.getElementById('pdf-table-body');
      const tableFooter = document.getElementById('pdf-table-footer');
      
      // Clear previous content
      tableBody.innerHTML = '';
      tableFooter.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';
      }

      let grandTotal = 0;

      cart.forEach((item, index) => {
        const sno = (index + 1).toString();
        const itemTotal = item.price * item.quantity;
        grandTotal += itemTotal;
        
        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;">${item.name}</td>
          <td style="padding: 10px; border: 1px solid #ddd; text-align: center;">₹${item.price}</td>
          <td style="padding: 10px; border: 1px solid #ddd; text-align: center;">${item.quantity}</td>
          <td style="padding: 10px; border: 1px solid #ddd; text-align: right;">₹${itemTotal}</td>
        `;
        tableBody.appendChild(tr);
      });

      // Add Grand Total row
      const footTr = document.createElement('tr');
      footTr.style.backgroundColor = '#f8f9fa';
      footTr.style.fontWeight = 'bold';
      footTr.innerHTML = `
        <td colspan="4" style="padding: 10px; border: 1px solid #ddd; text-align: right;">Grand Total:</td>
        <td style="padding: 10px; border: 1px solid #ddd; text-align: right; color: #d32f2f; font-size: 16px;">₹${grandTotal}</td>
      `;
      tableFooter.appendChild(footTr);

      // 2) Generate PDF from the hidden container
      const element = document.getElementById('pdf-content');
      
      const opt = {
        margin:       [10, 20, 20, 20], // top, left, bottom, right
        filename:     'GP-Crackers-Cart-Summary.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();
    });
  }
});
