(function($) {
  'use strict';

  var $subscriptionCardsContainer = null;

  function escapeHtml(str) {
    if (!str) return '';
    return String(str).replace(/[&<>"']/g, function(c) {
      return {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
      } [c];
    });
  }

  function renderBuyButton() {
    var $wrapper = $('#btn-buy-wrapper');
    if (!$wrapper.length) return;
    $wrapper.empty();

    $.post(mindwecoData.ajaxurl, {
      action: 'mindweco_get_buy_url',
      nonce: mindwecoData.nonce
    }).done(function(response) {
      if (response.success && response.data.url) {
        var $link = $('<a></a>')
          .attr('href', response.data.url)
          .attr('target', '_blank')
          .attr('rel', 'noopener noreferrer')
          .addClass('btn btn-success buy_subscription')
          .attr('id', 'buy_subscription')
          .html('<i class="bi bi-bag"></i> <span>Buy Subscription</span>');
        $wrapper.append($link).show();
      }
    }).fail(function() {
      MindwecoToast.error('Failed to load buy URL.');
    });
  }

  async function addTrialWithoutUser() {
    try {
      var response = await $.ajax({
        url: mindwecoData.ajaxurl,
        method: 'POST',
        data: {
          action: 'mindweco_add_trial_without_user',
          nonce: mindwecoData.nonce
        },
        dataType: 'json'
      });
      if (response.success) {
        $subscriptionCardsContainer.html(
          '<div class="success-message-card"><span class="dashicons dashicons-yes-alt"></span>' +
          '<p>Trial subscription added successfully! Loading your subscription...</p></div>'
        );
        setTimeout(function() {
          loadSubscriptionsCards();
        }, 1000);
      } else {
        throw new Error(response.data && response.data.message ? response.data.message : 'Unknown error');
      }
    } catch (error) {
      MindwecoToast.error('Error adding trial: you have already used your trial, buy a new one.');
    }
  }

  async function cancelSubscription(subscriptionId) {
    try {
      const response = await $.post(mindwecoData.ajaxurl, {
        action: 'mindweco_cancel_subscription',
        nonce: mindwecoData.nonce,
        subscription_id: subscriptionId
      });

      if (response.success) {
        MindwecoToast.success('Subscription auto-renew cancelled successfully.');
        const $container = $('#subscription-cards-container');
        $container.html('<div class="loading-card d-flex justify-content-center"><span class="spinner is-active"></span><p>Refreshing subscriptions...</p></div>');
        await loadSubscriptionsCards();
      } else {
        throw new Error(response.data?.message || 'Unknown error');
      }
    } catch (error) {
      MindwecoToast.error('Error cancelling subscription.');
      throw error;
    }
  }

  async function reactivateSubscription(subscriptionId) {
    try {
      const response = await $.post(mindwecoData.ajaxurl, {
        action: 'mindweco_reactivate_subscription',
        nonce: mindwecoData.nonce,
        subscription_id: subscriptionId
      });

      if (response.success) {
        MindwecoToast.success('Subscription reactivated successfully.');
        const $container = $('#subscription-cards-container');
        $container.html('<div class="loading-card d-flex justify-content-center"><span class="spinner is-active"></span><p>Refreshing subscriptions...</p></div>');
        await loadSubscriptionsCards();
      } else {
        throw new Error(response.data?.message || 'Unknown error');
      }
    } catch (error) {
      MindwecoToast.error('Error reactivating subscription.');
      throw error;
    }
  }

  function createSubscriptionCard(item) {
    var subscriptionId = 'subscription-' + escapeHtml(String(item.stripeSubscriptionId || Math.random()));
    var statusBadge = '';
    var actionButton = '';
    var helpers = window.MindwecoHelpers;

    if (item.type == 0) {
      if (item.status == 0) statusBadge = '<span class="badge-status active">ACTIVE</span>';
      else if (item.status == 1) statusBadge = '<span class="badge-status cancelled">CANCELLED</span>';
      else if (item.status == 2) statusBadge = '<span class="badge-status expired">EXPIRED</span>';
    } else if (item.type == 1) {
      if (item.status == 0) {
        statusBadge = '<span class="badge-status active">ACTIVE</span>';
        actionButton = '<button class="btn-cancel-subscription cancel_subscription" data-item-id="' + escapeHtml(String(item.stripeSubscriptionId)) + '"><i class="bi bi-x-circle"></i> Cancel Auto-Renew</button>';
      } else if (item.status == 1) {
        statusBadge = '<span class="badge-status cancelled">CANCELLED</span>';
        var now = new Date();
        var endDate = new Date(item.currentPeriodEnd);
        if (now <= endDate) {
          actionButton = '<button class="btn-activate-subscription activate_subscription" data-item-id="' + escapeHtml(String(item.stripeSubscriptionId)) + '"><i class="bi bi-arrow-repeat"></i> Activate Auto-Renew</button>';
        }
      } else if (item.status == 2) {
        statusBadge = '<span class="badge-status expired">EXPIRED</span>';
      }
    }

    var hasInvoices = item.invoices && item.invoices.length > 0;
    var invoiceCount = hasInvoices ? item.invoices.length : 0;

    var invoicesHtml = '';
    if (hasInvoices) {
      var invoiceItems = item.invoices.map(function(invoice) {
        return '<div class="invoice-item">' +
          '<div class="invoice-icon"><i class="bi bi-file-earmark-text"></i></div>' +
          '<div class="invoice-details">' +
          '<div class="invoice-id">#' + escapeHtml(String(invoice.invoiceNumber || 'N/A')) + '</div>' +
          '<div class="invoice-meta">' +
          escapeHtml(helpers.formatMyDate(invoice.created)) + ' • Package Price ' +
          escapeHtml(invoice.currency || '€') + ' • Tax Fee ' +
          escapeHtml(invoice.currency || '€') + ' • ' +
          escapeHtml(invoice.status || 'paid') +
          '</div>' +
          '</div>' +
          '<button class="btn-download-invoice download-invoice" data-item-id="' + escapeHtml(String(invoice.invoiceNumber || '')) + '"><i class="bi bi-download"></i> Download</button>' +
          '</div>';
      }).join('');

      invoicesHtml = '<div class="invoices-section" id="' + subscriptionId + '" style="display: none;">' + invoiceItems + '</div>';
    }

    var nextPaymentHtml = (item.type === 1 && item.status === 0) ?
      '<div class="next-payment">Next Payment Date: ' + escapeHtml(helpers.formatMyDate(item.currentPeriodEnd)) + '</div>' :
      '';

    return '<div class="subscription-card-wrapper">' +
      '<div class="subscription-main-card" id="subscription-main-card-' + subscriptionId + '">' +
      '<div class="subscription-icon"><i class="bi bi-check-circle"></i></div>' +
      '<div class="subscription-info">' +
      '<div class="subscription-header-row">' +
      '<div class="subscription-type">' + escapeHtml(item.type == 0 ? item.packageName : 'Paid') + '</div>' +
      statusBadge +
      '</div>' +
      '<div class="subscription-dates">' +
      '<div class="date-item"><span class="date-label">Activated At:</span><span class="date-value">' + escapeHtml(helpers.formatMyDate(item.createdAt)) + '</span></div>' +
      '<div class="date-separator">•</div>' +
      '<div class="date-item"><span class="date-label">Current Period Start:</span><span class="date-value">' + escapeHtml(helpers.formatMyDate(item.currentPeriodStart)) + '</span></div>' +
      '<div class="date-separator">•</div>' +
      '<div class="date-item"><span class="date-label">Current Period End:</span><span class="date-value">' + escapeHtml(helpers.formatMyDate(item.currentPeriodEnd)) + '</span></div>' +
      '</div>' +
      nextPaymentHtml +
      '</div>' +
      '<div class="subscription-price">' + (item.price ? '<div class="price-amount">€' + escapeHtml(String(item.price)) + '</div>' : '') + '</div>' +
      '<div class="subscription-actions">' +
      actionButton +
      (hasInvoices ? '<button class="btn-toggle-invoices" data-target="' + subscriptionId + '"><i class="bi bi-chevron-down"></i> Invoices (' + invoiceCount + ')</button>' : '') +
      '</div>' +
      '</div>' +
      invoicesHtml +
      '</div>';
  }

  async function loadSubscriptionsCards() {
    $subscriptionCardsContainer = $('#subscription-cards-container');
    $subscriptionCardsContainer.html(
      '<div class="loading-card d-flex justify-content-center"><span class="spinner is-active"></span><p>Loading subscriptions...</p></div>'
    );

    try {
      var response = await $.post(mindwecoData.ajaxurl, {
        action: 'mindweco_get_all_subscriptions',
        nonce: mindwecoData.nonce,
        status: mindwecoData.trial_status,
        type: mindwecoData.trial_type
      });

      $subscriptionCardsContainer.empty();

      if (response.success && Array.isArray(response.data) && response.data.length > 0) {
        window.MindwecoPagination.init(
          'subscription-cards-container',
          response.data,
          function(item, $container) {
            $container.append(createSubscriptionCard(item));
          }
        );
      } else if (response.success && Array.isArray(response.data) && response.data.length === 0) {
        $subscriptionCardsContainer.append(
          '<div class="empty-state-card">' +
          '<div class="empty-state-icon">' +
          '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" fill="none" viewBox="0 0 24 24">' +
          '<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="1.5" opacity="0.3"/>' +
          '<path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" d="M12 8v4m0 4h.01"/>' +
          '<path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" d="M8.5 15.5c.83-1 2-1.5 3.5-1.5s2.67.5 3.5 1.5"/>' +
          '</svg>' +
          '</div>' +
          '<h3 class="empty-state-title text-secondary">No Active Subscriptions</h3>' +
          '<p class="empty-state-desc">Start your free trial and unlock all features — no credit card required.</p>' +
          '<button id="add-trial-btn" class="btn-add-trial">' +
          '<span class="btn-add-trial-icon">' +
          '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16">' +
          '<path d="M8 4a.5.5 0 0 1 .5.5v3h3a.5.5 0 0 1 0 1h-3v3a.5.5 0 0 1-1 0v-3h-3a.5.5 0 0 1 0-1h3v-3A.5.5 0 0 1 8 4z"/>' +
          '</svg>' +
          '</span>' +
          '<span>Start Free Trial</span>' +
          '</button>' +
          '<p class="empty-state-hint">✦ 7-day trial  ·  Cancel anytime</p>' +
          '</div>'
        );
      }
    } catch (error) {
      $subscriptionCardsContainer.html(
        '<div class="error-card"><i class="bi bi-exclamation-triangle"></i><p>Failed to load subscriptions. Please refresh the page.</p></div>'
      );
    }
  }

  function openSubscriptionModal(action, subscriptionId) {
    if (action === 'cancel') {
      MindwecoModal.confirm(
        'Cancel Auto-Renew',
        'Are you sure you want to cancel auto-renew for this subscription?',
        function() {
          cancelSubscription(subscriptionId);
        },
        'Confirm Cancel',
        'btn-danger'
      );
    } else if (action === 'reactivate') {
      MindwecoModal.confirm(
        'Re-activate',
        'Are you sure you want to re-activate this subscription?',
        function() {
          reactivateSubscription(subscriptionId);
        },
        'Re-activate Subscription',
        'btn-success'
      );
    }
  }

  function init() {
    if (window.MindwecoPagination && window.MindwecoPagination.options) {
      window.MindwecoPagination.options.itemsPerPage = 20;
      window.MindwecoPagination.options.scrollOffset = 150;
    }

    $(document).on('click', '#add-trial-btn', function() {
      var $btn = $(this);
      $btn.prop('disabled', true)
        .html('<span class="spinner is-active mindweco-spinner-inline"></span> Adding Trial...');
      addTrialWithoutUser();
    });

    $(document).on('click', '.cancel_subscription', function() {
      openSubscriptionModal('cancel', $(this).data('item-id'));
    });

    $(document).on('click', '.activate_subscription', function() {
      openSubscriptionModal('reactivate', $(this).data('item-id'));
    });

    $(document).on('click', '.btn-toggle-invoices', function() {
      var $btn = $(this);
      var targetId = $btn.data('target');
      var $invoicesSection = $('#' + targetId);
      var $icon = $btn.find('i');
      if ($invoicesSection.is(':visible')) {
        $invoicesSection.slideUp(300);
        $icon.removeClass('bi-chevron-up').addClass('bi-chevron-down');
      } else {
        $invoicesSection.slideDown(300);
        $icon.removeClass('bi-chevron-down').addClass('bi-chevron-up');
      }
    });

    $(document).on('click', '.download-invoice', function() {
      var invoiceNumber = $(this).data('item-id');
      MindwecoToast.info('Downloading invoice...');
      $.post(mindwecoData.ajaxurl, {
          action: 'mindweco_download_invoice',
          nonce: mindwecoData.nonce,
          invoice_number: invoiceNumber
        })
        .done(function(response) {
          if (response.success && response.data.url) {
            var link = document.createElement('a');
            link.href = response.data.url;
            link.download = 'Invoice-' + invoiceNumber + '.pdf';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            MindwecoToast.success('Invoice download started.');
          } else {
            MindwecoToast.error('Failed to download invoice.');
          }
        })
        .fail(function() {
          MindwecoToast.error('Failed to download invoice. Please try again later.');
        });
    });

    $(document).on('click', '#buy_subscription', function() {
      if (window.MindwecoMain) window.MindwecoMain.state.paymentStarted = true;
    });

    $('#subscription-tab').on('click', function() {
      renderBuyButton();
      loadSubscriptionsCards();
    });
  }

  window.MindwecoSubscriptions = {
    init: init,
    load: loadSubscriptionsCards,
    renderBuyButton: renderBuyButton,
    cancel: cancelSubscription,
    reactivate: reactivateSubscription
  };

})(jQuery);