// QR Code Generator Script
document.addEventListener('DOMContentLoaded', function() {
  let qrCode = null;
  let currentLogo = null;
  let currentBgImage = null;

  // Initialize QR Code
  function initQRCode() {
    const options = getQROptions();
    qrCode = new QRCodeStyling(options);
    qrCode.append(document.getElementById('qrCanvas'));
  }

  // Get current QR options
  function getQROptions() {
    const fgColor = document.getElementById('fgColor').value;
    const bgColor = document.getElementById('bgColor').value;
    const moduleShape = document.querySelector('#moduleShapeGroup .btn.active')?.dataset.shape || 'square';
    const eyeStyle = document.querySelector('#eyeStyleGroup .btn.active')?.dataset.eye || 'square';
    const gradientType = document.querySelector('#gradientGroup .btn.active')?.dataset.gradient || 'off';
    const margin = document.getElementById('addMargin').checked ? 10 : 0;
    const errorCorrectionLevel = document.querySelector('#correctionGroup .btn.active')?.dataset.correction || 'L';

    // Get current type to determine data
    const currentType = document.querySelector('.qr-type-btn.active')?.dataset.type || 'url';
    let qrData = 'https://example.com';
    
    // Get data based on type
    switch(currentType) {
      case 'url':
        qrData = document.getElementById('urlInput')?.value || 'https://example.com';
        break;
      case 'vcard':
        const name = document.getElementById('vcardName')?.value || '';
        const phone = document.getElementById('vcardPhone')?.value || '';
        const email = document.getElementById('vcardEmail')?.value || '';
        const company = document.getElementById('vcardCompany')?.value || '';
        qrData = `BEGIN:VCARD\nVERSION:3.0\nFN:${name}\nTEL:${phone}\nEMAIL:${email}\nORG:${company}\nEND:VCARD`;
        break;
      case 'text':
        qrData = document.getElementById('textInput')?.value || 'Your text here';
        break;
      case 'email':
        const emailAddr = document.getElementById('emailAddress')?.value || '';
        const subject = document.getElementById('emailSubject')?.value || '';
        const message = document.getElementById('emailMessage')?.value || '';
        qrData = `mailto:${emailAddr}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(message)}`;
        break;
      case 'sms':
        const smsPhone = document.getElementById('smsPhone')?.value || '';
        const smsMsg = document.getElementById('smsMessage')?.value || '';
        qrData = `sms:${smsPhone}?body=${encodeURIComponent(smsMsg)}`;
        break;
      case 'wifi':
        const ssid = document.getElementById('wifiSSID')?.value || '';
        const password = document.getElementById('wifiPassword')?.value || '';
        const security = document.getElementById('wifiSecurity')?.value || 'WPA';
        qrData = `WIFI:T:${security};S:${ssid};P:${password};;`;
        break;
      case 'bitcoin':
        const btcAddr = document.getElementById('bitcoinAddress')?.value || '';
        const amount = document.getElementById('bitcoinAmount')?.value || '';
        const label = document.getElementById('bitcoinLabel')?.value || '';
        qrData = `bitcoin:${btcAddr}${amount ? '?amount=' + amount : ''}${label ? '&label=' + encodeURIComponent(label) : ''}`;
        break;
      default:
        qrData = document.getElementById('urlInput')?.value || 
                 document.getElementById('twitterURL')?.value || 
                 document.getElementById('facebookURL')?.value || 
                 document.getElementById('mp3URL')?.value || 
                 document.getElementById('imageURL')?.value || 
                 document.getElementById('pdfURL')?.value || 
                 document.getElementById('barcodeData')?.value || 
                 'https://example.com';
    }

    let dotsOptions = {
      color: fgColor,
      type: moduleShape
    };

    // Apply gradient if enabled
    if (gradientType != 'off') {
      const gradStart = document.getElementById('gradStart').value;
      const gradEnd = document.getElementById('gradEnd').value;
      dotsOptions.gradient = {
        type: gradientType,
        colorStops: [
          { offset: 0, color: gradStart },
          { offset: 1, color: gradEnd }
        ]
      };
    }

    const options = {
      width: 300,
      height: 300,
      data: qrData,
      margin: margin,
      qrOptions: {
        errorCorrectionLevel: errorCorrectionLevel
      },
      dotsOptions: dotsOptions,
      backgroundOptions: {
        color: bgColor
      },
      cornersSquareOptions: {
        type: eyeStyle,
        color: fgColor
      },
      cornersDotOptions: {
        type: eyeStyle,
        color: fgColor
      }
    };

    // Add logo if uploaded
    if (currentLogo) {
      const logoSize = parseInt(document.getElementById('logoSize').value);
      const logoOpacity = parseInt(document.getElementById('logoOpacity').value) / 100;
      options.image = currentLogo;
      options.imageOptions = {
        hideBackgroundDots: true,
        imageSize: logoSize / 100,
        margin: 5,
        crossOrigin: 'anonymous'
      };
    }

    // Add background image if uploaded
    if (currentBgImage) {
      options.backgroundOptions.image = currentBgImage;
    }

    return options;
  }

  // Update QR Code
  function updateQRCode() {
    if (!qrCode) return;
    const options = getQROptions();
    qrCode.update(options);
  }

  // Event Listeners (removed urlInput listener as it's handled dynamically)
  document.getElementById('fgColor').addEventListener('input', updateQRCode);
  document.getElementById('bgColor').addEventListener('input', updateQRCode);
  document.getElementById('gradStart').addEventListener('input', updateQRCode);
  document.getElementById('gradEnd').addEventListener('input', updateQRCode);
  document.getElementById('addMargin').addEventListener('change', updateQRCode);

  // Logo size and opacity
  document.getElementById('logoSize').addEventListener('input', function() {
    document.getElementById('logoSizeValue').textContent = this.value;
    updateQRCode();
  });

  document.getElementById('logoOpacity').addEventListener('input', function() {
    document.getElementById('logoOpacityValue').textContent = this.value;
    updateQRCode();
  });

  // Logo upload
  document.getElementById('logoUpload').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(event) {
        currentLogo = event.target.result;
        updateQRCode();
      };
      reader.readAsDataURL(file);
    }
  });

  // Background image upload
  document.getElementById('bgImageUpload').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(event) {
        currentBgImage = event.target.result;
        updateQRCode();
      };
      reader.readAsDataURL(file);
    }
  });

  // Button groups
  document.querySelectorAll('#moduleShapeGroup .btn').forEach(btn => {
    btn.addEventListener('click', function() {
      document.querySelectorAll('#moduleShapeGroup .btn').forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      updateQRCode();
    });
  });

  document.querySelectorAll('#eyeStyleGroup .btn').forEach(btn => {
    btn.addEventListener('click', function() {
      document.querySelectorAll('#eyeStyleGroup .btn').forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      updateQRCode();
    });
  });

  document.querySelectorAll('#gradientGroup .btn').forEach(btn => {
    btn.addEventListener('click', function() {
      document.querySelectorAll('#gradientGroup .btn').forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      const gradientType = this.dataset.gradient;
      document.getElementById('gradientColors').style.display = gradientType === 'off' ? 'none' : 'flex';
      updateQRCode();
    });
  });

  document.querySelectorAll('#correctionGroup .btn').forEach(btn => {
    btn.addEventListener('click', function() {
      document.querySelectorAll('#correctionGroup .btn').forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      updateQRCode();
    });
  });

  // QR Type buttons
  document.querySelectorAll('.qr-type-btn').forEach(btn => {
    btn.addEventListener('click', function() {
      document.querySelectorAll('.qr-type-btn').forEach(b => b.classList.remove('active'));
      this.classList.add('active');
      const type = this.dataset.type;
      document.getElementById('contentTitle').textContent = 'QR Content — ' + type.toUpperCase();
      updateContentFields(type);
    });
  });

  // Update content fields based on type
  function updateContentFields(type) {
    const container = document.getElementById('content-fields');
    let html = '';

    switch(type) {
      case 'url':
        html = `
          <div class="mb-3">
            <label class="form-label">Enter URL</label>
            <input type="url" class="form-control qr-data-input" id="urlInput" placeholder="https://example.com" value="https://example.com">
          </div>
        `;
        break;
      
      case 'vcard':
        html = `
          <div class="mb-3">
            <label class="form-label">Full Name</label>
            <input type="text" class="form-control qr-data-input" id="vcardName" placeholder="John Doe">
          </div>
          <div class="mb-3">
            <label class="form-label">Phone</label>
            <input type="tel" class="form-control qr-data-input" id="vcardPhone" placeholder="+1234567890">
          </div>
          <div class="mb-3">
            <label class="form-label">Email</label>
            <input type="email" class="form-control qr-data-input" id="vcardEmail" placeholder="email@example.com">
          </div>
          <div class="mb-3">
            <label class="form-label">Company</label>
            <input type="text" class="form-control qr-data-input" id="vcardCompany" placeholder="Company Name">
          </div>
        `;
        break;
      
      case 'text':
        html = `
          <div class="mb-3">
            <label class="form-label">Your Text</label>
            <textarea class="form-control qr-data-input" id="textInput" rows="4" placeholder="Enter your text here..."></textarea>
          </div>
        `;
        break;
      
      case 'email':
        html = `
          <div class="mb-3">
            <label class="form-label">Email Address</label>
            <input type="email" class="form-control qr-data-input" id="emailAddress" placeholder="email@example.com">
          </div>
          <div class="mb-3">
            <label class="form-label">Subject</label>
            <input type="text" class="form-control qr-data-input" id="emailSubject" placeholder="Email subject">
          </div>
          <div class="mb-3">
            <label class="form-label">Message</label>
            <textarea class="form-control qr-data-input" id="emailMessage" rows="3" placeholder="Email message..."></textarea>
          </div>
        `;
        break;
      
      case 'sms':
        html = `
          <div class="mb-3">
            <label class="form-label">Phone Number</label>
            <input type="tel" class="form-control qr-data-input" id="smsPhone" placeholder="+1234567890">
          </div>
          <div class="mb-3">
            <label class="form-label">Message</label>
            <textarea class="form-control qr-data-input" id="smsMessage" rows="3" placeholder="SMS message..."></textarea>
          </div>
        `;
        break;
      
      case 'wifi':
        html = `
          <div class="mb-3">
            <label class="form-label">Network Name (SSID)</label>
            <input type="text" class="form-control qr-data-input" id="wifiSSID" placeholder="MyWiFiNetwork">
          </div>
          <div class="mb-3">
            <label class="form-label">Password</label>
            <input type="text" class="form-control qr-data-input" id="wifiPassword" placeholder="password123">
          </div>
          <div class="mb-3">
            <label class="form-label">Security Type</label>
            <select class="form-select qr-data-input" id="wifiSecurity">
              <option value="WPA">WPA/WPA2</option>
              <option value="WEP">WEP</option>
              <option value="nopass">No Password</option>
            </select>
          </div>
        `;
        break;
      
      case 'bitcoin':
        html = `
          <div class="mb-3">
            <label class="form-label">Bitcoin Address</label>
            <input type="text" class="form-control qr-data-input" id="bitcoinAddress" placeholder="1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa">
          </div>
          <div class="mb-3">
            <label class="form-label">Amount (optional)</label>
            <input type="number" step="0.00000001" class="form-control qr-data-input" id="bitcoinAmount" placeholder="0.001">
          </div>
          <div class="mb-3">
            <label class="form-label">Label (optional)</label>
            <input type="text" class="form-control qr-data-input" id="bitcoinLabel" placeholder="Payment for...">
          </div>
        `;
        break;
      
      case 'twitter':
        html = `
          <div class="mb-3">
            <label class="form-label">Twitter Profile URL</label>
            <input type="url" class="form-control qr-data-input" id="twitterURL" placeholder="https://twitter.com/username">
          </div>
        `;
        break;
      
      case 'facebook':
        html = `
          <div class="mb-3">
            <label class="form-label">Facebook Page URL</label>
            <input type="url" class="form-control qr-data-input" id="facebookURL" placeholder="https://facebook.com/pagename">
          </div>
        `;
        break;
      
      case 'mp3':
        html = `
          <div class="mb-3">
            <label class="form-label">MP3 File URL</label>
            <input type="url" class="form-control qr-data-input" id="mp3URL" placeholder="https://example.com/audio.mp3">
          </div>
        `;
        break;
      
      case 'app':
        html = `
          <div class="mb-3">
            <label class="form-label">App Store URL (iOS)</label>
            <input type="url" class="form-control qr-data-input" id="appIOS" placeholder="https://apps.apple.com/app/...">
          </div>
          <div class="mb-3">
            <label class="form-label">Play Store URL (Android)</label>
            <input type="url" class="form-control qr-data-input" id="appAndroid" placeholder="https://play.google.com/store/apps/...">
          </div>
        `;
        break;
      
      case 'image':
        html = `
          <div class="mb-3">
            <label class="form-label">Image URL</label>
            <input type="url" class="form-control qr-data-input" id="imageURL" placeholder="https://example.com/image.jpg">
          </div>
        `;
        break;
      
      case 'pdf':
        html = `
          <div class="mb-3">
            <label class="form-label">PDF File URL</label>
            <input type="url" class="form-control qr-data-input" id="pdfURL" placeholder="https://example.com/document.pdf">
          </div>
        `;
        break;
      
      case 'barcode':
        html = `
          <div class="mb-3">
            <label class="form-label">Barcode Data</label>
            <input type="text" class="form-control qr-data-input" id="barcodeData" placeholder="123456789012">
          </div>
        `;
        break;
      
      default:
        html = `
          <div class="mb-3">
            <label class="form-label">Enter URL</label>
            <input type="url" class="form-control qr-data-input" id="urlInput" placeholder="https://example.com" value="https://example.com">
          </div>
        `;
    }

    container.innerHTML = html;
    
    // Add event listeners to new inputs
    document.querySelectorAll('.qr-data-input').forEach(input => {
      input.addEventListener('input', function() {
        updateQRDataFromType(type);
      });
    });
    
    // Initial update
    updateQRDataFromType(type);
  }

  // Get QR data based on type
  function updateQRDataFromType(type) {
    let data = '';
    
    switch(type) {
      case 'url':
        data = document.getElementById('urlInput')?.value || 'https://example.com';
        break;
      
      case 'vcard':
        const name = document.getElementById('vcardName')?.value || '';
        const phone = document.getElementById('vcardPhone')?.value || '';
        const email = document.getElementById('vcardEmail')?.value || '';
        const company = document.getElementById('vcardCompany')?.value || '';
        data = `BEGIN:VCARD\nVERSION:3.0\nFN:${name}\nTEL:${phone}\nEMAIL:${email}\nORG:${company}\nEND:VCARD`;
        break;
      
      case 'text':
        data = document.getElementById('textInput')?.value || 'Your text here';
        break;
      
      case 'email':
        const emailAddr = document.getElementById('emailAddress')?.value || '';
        const subject = document.getElementById('emailSubject')?.value || '';
        const message = document.getElementById('emailMessage')?.value || '';
        data = `mailto:${emailAddr}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(message)}`;
        break;
      
      case 'sms':
        const smsPhone = document.getElementById('smsPhone')?.value || '';
        const smsMsg = document.getElementById('smsMessage')?.value || '';
        data = `sms:${smsPhone}?body=${encodeURIComponent(smsMsg)}`;
        break;
      
      case 'wifi':
        const ssid = document.getElementById('wifiSSID')?.value || '';
        const password = document.getElementById('wifiPassword')?.value || '';
        const security = document.getElementById('wifiSecurity')?.value || 'WPA';
        data = `WIFI:T:${security};S:${ssid};P:${password};;`;
        break;
      
      case 'bitcoin':
        const btcAddr = document.getElementById('bitcoinAddress')?.value || '';
        const amount = document.getElementById('bitcoinAmount')?.value || '';
        const label = document.getElementById('bitcoinLabel')?.value || '';
        data = `bitcoin:${btcAddr}${amount ? '?amount=' + amount : ''}${label ? '&label=' + encodeURIComponent(label) : ''}`;
        break;
      
      case 'twitter':
        data = document.getElementById('twitterURL')?.value || 'https://twitter.com';
        break;
      
      case 'facebook':
        data = document.getElementById('facebookURL')?.value || 'https://facebook.com';
        break;
      
      case 'mp3':
        data = document.getElementById('mp3URL')?.value || 'https://example.com/audio.mp3';
        break;
      
      case 'app':
        const ios = document.getElementById('appIOS')?.value || '';
        const android = document.getElementById('appAndroid')?.value || '';
        data = ios || android || 'https://example.com/app';
        break;
      
      case 'image':
        data = document.getElementById('imageURL')?.value || 'https://example.com/image.jpg';
        break;
      
      case 'pdf':
        data = document.getElementById('pdfURL')?.value || 'https://example.com/document.pdf';
        break;
      
      case 'barcode':
        data = document.getElementById('barcodeData')?.value || '123456789';
        break;
      
      default:
        data = 'https://example.com';
    }
    
    // Update QR code with new data
    if (qrCode && data) {
      const options = getQROptions();
      options.data = data;
      qrCode.update(options);
    }
  }

  // Reset button
  document.getElementById('resetStyleBtn')?.addEventListener('click', function() {
    document.getElementById('fgColor').value = '#101828';
    document.getElementById('bgColor').value = '#ffffff';
    document.getElementById('gradStart').value = '#00c4b4';
    document.getElementById('gradEnd').value = '#101828';
    document.getElementById('logoSize').value = '40';
    document.getElementById('logoOpacity').value = '100';
    document.getElementById('logoSizeValue').textContent = '40';
    document.getElementById('logoOpacityValue').textContent = '100';
    document.getElementById('addMargin').checked = true;
    currentLogo = null;
    currentBgImage = null;
    
    document.querySelectorAll('#moduleShapeGroup .btn').forEach((b, i) => {
      b.classList.toggle('active', i === 0);
    });
    document.querySelectorAll('#eyeStyleGroup .btn').forEach((b, i) => {
      b.classList.toggle('active', i === 0);
    });
    document.querySelectorAll('#gradientGroup .btn').forEach((b, i) => {
      b.classList.toggle('active', i === 0);
    });
    document.querySelectorAll('#correctionGroup .btn').forEach((b, i) => {
      b.classList.toggle('active', i === 0);
    });
    
    updateQRCode();
  });

  // Download buttons
  document.getElementById('downloadPNG')?.addEventListener('click', function() {
    if (qrCode) {
      qrCode.download({ name: 'qrcode', extension: 'png' });
    }
  });

  document.getElementById('downloadSVG')?.addEventListener('click', function() {
    if (qrCode) {
      qrCode.download({ name: 'qrcode', extension: 'svg' });
    }
  });

  document.getElementById('downloadPDF')?.addEventListener('click', function() {
    if (qrCode) {
      // Get the canvas from QR code
      const canvas = document.querySelector('#qrCanvas canvas');
      if (canvas) {
        // Create a temporary link to download as image first
        // For PDF we need jsPDF library, adding simple fallback
        canvas.toBlob(function(blob) {
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'qrcode.png';
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
          
          // Show message about PDF
          alert('PDF download requires registration. PNG downloaded instead.');
        });
      }
    }
  });

  // Initialize
  initQRCode();
  document.getElementById('gradientColors').style.display = 'none';
});
