/**
 * Ragreen - Loyalty rewards page logic
 * Requires config.js + jQuery + products.js (escapeHtml) loaded first.
 */

const Loyalty = {
  init() {
    this.loadFormula();
    this.loadHistory();
    this.loadRewards();
    this.loadRedemptions();
  },

  loadFormula() {
    $.get(`${API_BASE}/loyalty/formula.php`).done((res) => {
      $('#formulaDollar').text(`+${res.data.points_per_dollar_spent} pt`);
      $('#formulaListing').text(`+${res.data.points_per_new_listing} pts`);
    });
  },

  loadHistory(page = 1) {
    $.get(`${API_BASE}/loyalty/history.php`, { page })
      .done((res) => this.renderHistory(res.data.points_balance, res.data.transactions, res.data.pagination))
      .fail(() => {
        $('#loyaltyContent').html('<div class="empty-state"><h3>Could not load your rewards</h3></div>');
      });
  },

  renderHistory(balance, transactions, pagination) {
    $('#pointsBalance').text(balance.toLocaleString());
    this.currentBalance = balance;

    const $tx = $('#txList');
    if (!transactions.length) {
      $tx.html('<p style="color:var(--ink-muted); font-size:13px;">No activity yet — buy or list an item to start earning points.</p>');
      renderPaginationControls('#txPagination', null);
      return;
    }
    $tx.html(transactions.map(t => `
      <div class="tx-row">
        <div>
          <div class="reason">${escapeHtml(t.reason)}</div>
          <div class="date">${new Date(t.created_at.replace(' ', 'T')).toLocaleDateString()}</div>
        </div>
        <div class="points ${t.points >= 0 ? 'positive' : 'negative'}">${t.points >= 0 ? '+' : ''}${t.points}</div>
      </div>
    `).join(''));
    renderPaginationControls('#txPagination', pagination, (p) => this.loadHistory(p));
  },

  loadRewards() {
    $.get(`${API_BASE}/rewards/list.php`).done((res) => {
      this.currentBalance = res.data.points_balance;
      this.renderRewards(res.data.rewards, res.data.points_balance);
    });
  },

  renderRewards(rewards, balance) {
    const $catalog = $('#rewardsCatalog');
    if (!rewards.length) {
      $catalog.html('<p style="color:var(--ink-muted); font-size:13px;">No rewards available right now.</p>');
      return;
    }
    $catalog.html(`
      <div class="tier-grid">
        ${rewards.map(r => {
          const affordable = balance >= r.points_cost;
          return `
            <div class="tier-card">
              <div style="font-weight:700; font-size:14px; margin-bottom:4px;">${escapeHtml(r.title)}</div>
              <div class="desc">${escapeHtml(r.description || '')}</div>
              <div class="pts" style="margin:8px 0;">${r.points_cost} pts</div>
              <button class="mini-btn ${affordable ? 'primary' : ''} claim-btn" data-id="${r.id}" ${affordable ? '' : 'disabled'}>
                ${affordable ? 'Claim' : 'Not enough points'}
              </button>
            </div>
          `;
        }).join('')}
      </div>
    `);

    $catalog.find('.claim-btn').on('click', function () {
      Loyalty.claim($(this).data('id'));
    });
  },

  claim(rewardId) {
    if (!confirm('Claim this reward? Points will be deducted immediately.')) return;

    $.ajax({
      url: `${API_BASE}/rewards/claim.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify({ reward_id: rewardId }),
    })
      .done((res) => {
        alert(`Reward claimed! Your code: ${res.data.redemption.code}\n\nShow this to any seller at pickup.`);
        this.loadHistory();
        this.loadRewards();
        this.loadRedemptions();
      })
      .fail((xhr) => alert(xhr.responseJSON?.message || 'Could not claim this reward.'));
  },

  loadRedemptions() {
    $.get(`${API_BASE}/rewards/redemptions.php`).done((res) => {
      const $list = $('#redemptionsList');
      const redemptions = res.data.redemptions;
      if (!redemptions.length) {
        $list.html('<p style="color:var(--ink-muted); font-size:13px;">No rewards claimed yet.</p>');
        return;
      }
      $list.html(redemptions.map(r => `
        <div class="tx-row">
          <div>
            <div class="reason">${escapeHtml(r.title)} — code <strong style="font-family:var(--font-mono);">${escapeHtml(r.redemption_code)}</strong></div>
            <div class="date">${new Date(r.created_at.replace(' ', 'T')).toLocaleDateString()} · ${r.status}</div>
          </div>
          <div class="points negative">-${r.points_spent}</div>
        </div>
      `).join(''));
    });
  },
};
