// Test Result Page - Display QR scan results for testing
Page({
  /**
   * Page initial data
   */
  data: {
    qr_code: '',
    scan_timestamp: '',
    scan_mode: 'unknown',
    source_page: 'unknown',
    qr_position: null,
    qr_sharpness: 0,
    qr_size: 0,
    raw_query_string: ''
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    console.log('Test result page loaded with options:', options);
    
    // Parse all query parameters
    const timestamp = new Date().toLocaleString();
    const qr_code = options.qr_code || 'No QR code provided';
    
    // Parse additional data if provided
    let qr_position = null;
    let qr_sharpness = 0;
    let qr_size = 0;
    
    try {
      if (options.qr_position) {
        qr_position = JSON.parse(decodeURIComponent(options.qr_position));
      }
      if (options.qr_sharpness) {
        qr_sharpness = parseFloat(options.qr_sharpness);
      }
      if (options.qr_size) {
        qr_size = parseInt(options.qr_size);
      }
    } catch (error) {
      console.warn('Error parsing additional QR data:', error);
    }

    // Generate raw query string for debugging
    const raw_query_string = Object.keys(options)
      .map(key => `${key}=${options[key]}`)
      .join('\n');

    this.setData({
      qr_code: decodeURIComponent(qr_code),
      scan_timestamp: timestamp,
      scan_mode: options.scan_mode || 'unknown',
      source_page: options.source_page || 'unknown',
      qr_position: qr_position,
      qr_sharpness: qr_sharpness,
      qr_size: qr_size,
      raw_query_string: raw_query_string
    });
  },

  /**
   * Scan again - go back to emblemscanner
   */
  scanAgain() {
    wx.redirectTo({
      url: '/pages/emblemscanner/emblemscanner?debug=1',
      fail: (err) => {
        console.error('Failed to navigate to scanner:', err);
        wx.showToast({
          title: 'Navigation failed',
          icon: 'error'
        });
      }
    });
  },

  /**
   * Copy QR code to clipboard
   */
  copyQRCode() {
    wx.setClipboardData({
      data: this.data.qr_code,
      success: () => {
        wx.showToast({
          title: 'QR code copied',
          icon: 'success'
        });
      },
      fail: () => {
        wx.showToast({
          title: 'Copy failed',
          icon: 'error'
        });
      }
    });
  },

  /**
   * Go back to previous page
   */
  goBack() {
    wx.navigateBack({
      fail: () => {
        // If can't go back, go to scanner
        this.scanAgain();
      }
    });
  },

  /**
   * Share this page (for testing)
   */
  onShareAppMessage() {
    return {
      title: 'QR Scan Result',
      path: `/pages/test_result_page/test_result_page?qr_code=${encodeURIComponent(this.data.qr_code)}`
    };
  }
});