// Frontend script for DiscountLift
jQuery(document).ready(function ($) {
  console.log('Smart Discount Frontend Initialized');
  // Add confetti script
  const confettiScript = document.createElement('script');
  confettiScript.src = 'https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js';
  document.body.appendChild(confettiScript);

  // Store previous states for each rule
  let previousStates = {};

  // Function to trigger confetti
  function triggerConfetti(celebrationType = 'basic') {
    if (typeof confetti === 'undefined') return;

    const defaults = {
      origin: { y: 0.7 },
      spread: 90,
      startVelocity: 30,
      zIndex: 300
    };

    switch (celebrationType.toLowerCase()) {
      case 'rainbow':
        // Rainbow wave effect
        const colors = ['#ff0000', '#ff9900', '#ffff00', '#33cc33', '#3399ff', '#9933ff'];
        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            confetti({
              ...defaults,
              particleCount: 40,
              spread: 80,
              origin: { x: 0.2 + (i * 0.3), y: 0.7 },
              colors: colors,
              ticks: 300,
              startVelocity: 35,
              shapes: ['circle'],
              scalar: 1.2
            });
          }, i * 200);
        }
        break;

      case 'stars':
        // Shooting stars effect
        const starDefaults = {
          ...defaults,
          shapes: ['star'],
          colors: ['#FFD700', '#FFF8DC', '#FFE4B5'],
          gravity: 0.4,
          scalar: 1.4,
          drift: 1
        };

        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            confetti({
              ...starDefaults,
              particleCount: 15,
              spread: 40,
              startVelocity: 35 + (i * 10),
              origin: { x: 0.2 + (i * 0.3), y: 0.7 }
            });
          }, i * 300);
        }
        break;

      case 'hearts':
        // Love hearts shower
        const heartColors = ['#ff69b4', '#ff1493', '#ff0000', '#ff69b4'];
        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            confetti({
              ...defaults,
              particleCount: 25,
              spread: 60,
              shapes: ['heart'],
              colors: heartColors,
              scalar: 2,
              drift: 0.5,
              ticks: 300,
              origin: { x: 0.2 + (i * 0.3), y: 0.7 }
            });
          }, i * 200);
        }
        break;

      case 'glitter':
        // Golden glitter burst
        const glitterDefaults = {
          ...defaults,
          colors: ['#FFD700', '#DAA520', '#FDB813', '#F4C430'],
          gravity: 0.6,
          scalar: 0.7,
          drift: 0.2,
          ticks: 150
        };

        for (let i = 0; i < 5; i++) {
          setTimeout(() => {
            confetti({
              ...glitterDefaults,
              particleCount: 30,
              spread: 50,
              startVelocity: 25 + (i * 5),
              origin: { x: 0.2 + (Math.random() * 0.6), y: 0.7 }
            });
          }, i * 150);
        }
        break;

      case 'explosion':
        // Color explosion
        const explosionColors = [
          '#FF1461', '#18FF92', '#1A8FE3', '#FFE700', '#FF7C00',
          '#FF005D', '#45FFA0', '#00B1E9', '#FFD300', '#FF8E00'
        ];

        for (let i = 0; i < 3; i++) {
          setTimeout(() => {
            confetti({
              ...defaults,
              particleCount: 80,
              spread: 100 + (i * 30),
              origin: { x: 0.5, y: 0.7 },
              colors: explosionColors,
              ticks: 200,
              gravity: 1,
              scalar: 1.2 - (i * 0.2),
              shapes: ['circle', 'square'],
              startVelocity: 40 + (i * 10)
            });
          }, i * 150);
        }
        break;

      case 'snow':
        // Gentle snow effect
        const snowColors = ['#ffffff', '#f0f0f0', '#e0e0e0'];
        for (let i = 0; i < 5; i++) {
          setTimeout(() => {
            confetti({
              ...defaults,
              particleCount: 30,
              spread: 70,
              origin: { x: 0.2 + (Math.random() * 0.6), y: 0.7 },
              colors: snowColors,
              ticks: 400,
              gravity: 0.3,
              scalar: 0.8,
              drift: 2,
              shapes: ['circle']
            });
          }, i * 200);
        }
        break;

      case 'bubbles':
        // Rising bubbles effect
        const bubbleColors = ['#8FDBFF', '#4FC3F7', '#29B6F6', '#03A9F4'];
        for (let i = 0; i < 4; i++) {
          setTimeout(() => {
            confetti({
              ...defaults,
              particleCount: 20,
              spread: 60,
              origin: { x: 0.2 + (Math.random() * 0.6), y: 0.7 },
              colors: bubbleColors,
              ticks: 300,
              gravity: -0.2,
              scalar: 1.5,
              drift: 0.5,
              shapes: ['circle']
            });
          }, i * 150);
        }
        break;

      case 'fireworks':
        confetti({
          ...defaults,
          spread: 360,
          ticks: 200,
          gravity: 0.5,
          decay: 0.94,
          startVelocity: 30,
          particleCount: 100,
          scalar: 1.2,
          shapes: ['star'],
          colors: ['#ff0000', '#00ff00', '#0000ff', '#ffff00', '#ff00ff']
        });
        break;

      case 'sparkles':
        confetti({
          ...defaults,
          spread: 100,
          particleCount: 40,
          ticks: 200,
          origin: { x: 0.4, y: 0.7 },
          colors: ['#FFD700', '#FFA500', '#FF6347']
        });
        confetti({
          ...defaults,
          spread: 100,
          particleCount: 40,
          ticks: 200,
          origin: { x: 0.6, y: 0.7 },
          colors: ['#FFD700', '#FFA500', '#FF6347']
        });
        break;

      case 'party':
        confetti({
          ...defaults,
          spread: 100,
          particleCount: 100,
          origin: { y: 0.8 },
          colors: ['#FF1461', '#18FF92', '#1A8FE3', '#FFE700', '#FF7C00'],
          ticks: 200,
          gravity: 1.2,
          scalar: 1.2,
          drift: 0
        });
        break;

      case 'basic':
      default:
        confetti({
          ...defaults,
          particleCount: 100,
          spread: 70,
          ticks: 200,
          colors: ['#FFD700', '#FFA500', '#FF6347', '#87CEEB', '#98FB98']
        });
        break;
    }
  }

  function updateMessages() {
    console.log('updateMessages function called');
    // Update each message container separately
    $('.dlift-message').each(function () {
      const container = $(this);
      const ruleId = container.data('rule-id');
      console.log('Updating message for rule:', ruleId);

      $.ajax({
        url: dliftSettings.ajaxUrl,
        type: 'POST',
        data: {
          action: 'dlift_get_messages',
          nonce: dliftSettings.nonce,
          'data-rule-id': ruleId
        },
        success: function (response) {
          console.log('AJAX response:', response);
          if (response.success) {
            if (response.data.is_empty) {
              console.log('Empty response, hiding container');
              container.fadeOut(200);
            } else {
              console.log('Updating container with new message');
              // Apply styles and message in sequence
              container.css('display', 'none');
              container.attr('style', response.data.style);
              container.html(response.data.message);
              container.fadeIn(200);

              // Check if discount threshold was just reached
              const currentState = response.data.debug.meets_condition;
              const previousState = previousStates[ruleId] || false;
              const celebrationType = response.data.celebration_type;

              console.log('State change:', {
                previous: previousState,
                current: currentState,
                celebration: celebrationType
              });

              if (currentState && !previousState && celebrationType && celebrationType !== 'none') {
                triggerConfetti(celebrationType);
              }

              // Update previous state
              previousStates[ruleId] = currentState;
            }
          } else {
            console.error('AJAX request failed:', response);
          }
        },
        error: function (xhr, status, error) {
          console.error('AJAX error:', {
            status: status,
            error: error,
            xhr: xhr
          });
        }
      });
    });
  }

  // Convert shortcodes to containers
  $('body :contains("[dlift_discount_message")').each(function () {
    const element = $(this);
    const html = element.html();
    if (typeof html === 'string') {
      const regex = /\[dlift_discount_message id="(\d+)"\]/g;
      const newHtml = html.replace(regex, function (match, ruleId) {
        return '<div class="dlift-message" data-rule-id="' + ruleId + '" style="display: none;"></div>';
      });
      element.html(newHtml);
    }
  });

  // Initial update
  console.log('Running initial message update');
  updateMessages();

  // Listen for all possible cart update events
  $(document.body).on('updated_cart_totals added_to_cart removed_from_cart', function (e) {
    console.log('Cart update event triggered:', e.type);
    updateMessages();
  });

  $(document.body).on('wc_fragments_loaded wc_fragments_refreshed', function (e) {
    console.log('WC fragments event triggered:', e.type);
    updateMessages();
  });

  // Listen for quantity input changes
  $(document.body).on('change', '.qty', function (e) {
    console.log('Quantity changed:', e.target.value);
    setTimeout(updateMessages, 100);
  });

  // Listen for quantity buttons
  $(document.body).on('click', '.quantity .plus, .quantity .minus', function (e) {
    console.log('Quantity button clicked:', e.target.className);
    setTimeout(updateMessages, 100);
  });

  // Listen for Store API requests (for blocks checkout)
  const originalFetch = window.fetch;
  window.fetch = function (url, options) {
    if (url && url.toString().includes('/wc/store/v1/')) {
      console.log('Store API request intercepted:', url);
      return originalFetch(url, options).then(response => {
        console.log('Store API response received');
        setTimeout(updateMessages, 1000);
        return response;
      });
    }
    return originalFetch(url, options);
  };
});
