/**
 * QR Code Module Initialization
 * Handles QR code generation and download functionality
 * Requires: QRCode library loaded globally (window.QRCode from qrcodejs)
 */

(function() {
  'use strict';

  /**
   * Initialize all QR code containers on the page
   */
  window.initializeQRCodes = function() {
    const containers = document.querySelectorAll('.qr-code-container[data-qr-content]');

    if (!containers.length) return;

    // Check if QRCode library is loaded
    if (typeof window.QRCode === 'undefined') {
      console.error('QRCode library not loaded');
      containers.forEach(container => {
        container.setAttribute('data-qr-error', 'true');
      });
      return;
    }

    containers.forEach(initializeQRCode);
  };

  /**
   * Initialize a single QR code container
   * @param {HTMLElement} container
   */
  function initializeQRCode(container) {
    // Skip if already initialized
    if (container.querySelector('canvas') || container.querySelector('img')) {
      return;
    }

    // Get configuration from data attributes.
    // Empty content = 'current_page' mode (server left it empty so the page stays
    // cacheable) — fall back to the live URL here.
    const content = container.dataset.qrContent || window.location.href;
    const size = parseInt(container.dataset.qrSize) || 200;
    const darkColor = container.dataset.qrDark || '#000000';
    const lightColor = container.dataset.qrLight || '#FFFFFF';
    const showDownload = container.dataset.qrDownload === 'true';
    const format = container.dataset.qrFormat || 'png';

    if (!content) {
      container.setAttribute('data-qr-error', 'true');
      return;
    }

    // Fill the displayed URL text client-side when the server left it blank.
    const moduleEl = container.closest('.qr-code-module');
    if (moduleEl) {
      const urlEl = moduleEl.querySelector('.qr-code-url');
      if (urlEl && !urlEl.textContent.trim()) {
        urlEl.textContent = content.length > 50 ? content.slice(0, 50) + '…' : content;
      }
    }

    // Set loading state
    container.setAttribute('data-qr-loading', 'true');

    try {
      // Generate QR code using qrcodejs library
      const qrcode = new QRCode(container, {
        text: content,
        width: size,
        height: size,
        colorDark: darkColor,
        colorLight: lightColor,
        correctLevel: QRCode.CorrectLevel.M // Medium error correction
      });

      // Remove loading state
      container.removeAttribute('data-qr-loading');

      // Setup download if enabled
      if (showDownload) {
        // Wait a moment for QR code to render
        setTimeout(function() {
          setupDownload(container, format, content);
        }, 100);
      }
    } catch (error) {
      console.error('QR Code generation error:', error);
      container.removeAttribute('data-qr-loading');
      container.setAttribute('data-qr-error', 'true');
    }
  }

  /**
   * Setup download functionality for QR code
   * @param {HTMLElement} container
   * @param {string} format
   * @param {string} content
   */
  function setupDownload(container, format, content) {
    // Find the canvas or image element
    const canvas = container.querySelector('canvas');
    const img = container.querySelector('img');

    if (!canvas && !img) {
      console.error('QR Code canvas/image not found');
      return;
    }

    // Find the download button (sibling of container)
    const module = container.closest('.qr-code-module');
    if (!module) return;

    const downloadBtn = module.querySelector('.qr-download-btn');
    if (!downloadBtn) return;

    downloadBtn.addEventListener('click', function(e) {
      e.preventDefault();
      if (canvas) {
        downloadQRCode(canvas, format, content);
      } else if (img) {
        downloadFromImage(img, format, content);
      }
    });
  }

  /**
   * Download QR code from canvas
   * @param {HTMLCanvasElement} canvas
   * @param {string} format
   * @param {string} content
   */
  function downloadQRCode(canvas, format, content) {
    const filename = 'qrcode-' + Date.now();

    if (format === 'svg') {
      // For SVG, convert canvas to SVG
      downloadAsSVG(canvas, filename);
    } else {
      // PNG download
      canvas.toBlob(function(blob) {
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.download = filename + '.png';
        link.href = url;
        link.click();
        URL.revokeObjectURL(url);
      }, 'image/png');
    }
  }

  /**
   * Download QR code from image element
   * @param {HTMLImageElement} img
   * @param {string} format
   * @param {string} content
   */
  function downloadFromImage(img, format, content) {
    const filename = 'qrcode-' + Date.now();

    // Create a canvas from the image
    const canvas = document.createElement('canvas');
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);

    // Download from canvas
    downloadQRCode(canvas, format, content);
  }

  /**
   * Download canvas as SVG
   * @param {HTMLCanvasElement} canvas
   * @param {string} filename
   */
  function downloadAsSVG(canvas, filename) {
    // Create SVG with embedded canvas data
    const size = canvas.width;
    const dataUrl = canvas.toDataURL('image/png');

    let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">`;
    svg += `<image href="${dataUrl}" width="${size}" height="${size}"/>`;
    svg += '</svg>';

    const blob = new Blob([svg], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.download = filename + '.svg';
    link.href = url;
    link.click();
    URL.revokeObjectURL(url);
  }

  // Auto-initialize when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', window.initializeQRCodes);
  } else {
    window.initializeQRCodes();
  }
})();
