/**
 * Ragreen - Pantry logic
 * Requires config.js + jQuery loaded first.
 */

const Pantry = {
  init() {
    this.load();
    $('#pantryAddForm').on('submit', (e) => this.handleAdd(e));
  },

  load() {
    $.get(`${API_BASE}/pantry/list.php`)
      .done((res) => this.render(res.data.items))
      .fail(() => {
        $('#pantryList').html('<div class="empty-state"><h3>Could not load your pantry</h3></div>');
      });
  },

  handleAdd(e) {
    e.preventDefault();
    const $alert = $('#pantryAlert');
    hideAlert($alert);

    const payload = {
      product_name: valTrim('#pn_name'),
      quantity: parseInt($('#pn_quantity').val() || 1, 10),
      expiry_date: $('#pn_expiry').val(),
    };

    if (!payload.product_name) {
      showAlert($alert, 'Please enter a product name.');
      return;
    }

    const $btn = $('#pantryAddBtn');
    setLoading($btn, true, 'Add to pantry', 'Adding…');

    $.ajax({
      url: `${API_BASE}/pantry/add.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify(payload),
    })
      .done(() => {
        $('#pantryAddForm')[0].reset();
        this.load();
      })
      .fail((xhr) => showAlert($alert, xhr.responseJSON?.message || 'Could not add this item.'))
      .always(() => setLoading($btn, false, 'Add to pantry', 'Adding…'));
  },

  render(items) {
    const $list = $('#pantryList');
    if (!items.length) {
      $list.html('<div class="empty-state"><h3>Your pantry is empty</h3><p>Add household items to track expiry dates.</p></div>');
      return;
    }

    const tagLabels = { expired: 'Expired', soon: 'Expiring soon', ok: 'Fresh', none: 'No date' };

    $list.html(items.map(item => `
      <div class="pantry-row" data-id="${item.id}">
        <div>
          <div class="name">${escapeHtml(item.product_name)}</div>
          <div class="qty-label">Qty ${item.quantity}${item.expiry_date ? ' · Expires ' + formatDate(item.expiry_date) : ''}</div>
        </div>
        <span class="expiry-tag expiry-${item.expiry_state}">${tagLabels[item.expiry_state]}</span>
        <div class="qty-stepper">
          <button class="qty-minus">−</button>
          <span>${item.quantity}</span>
          <button class="qty-plus">+</button>
        </div>
        <button class="icon-btn relist-btn" title="List in marketplace">🛒</button>
        <button class="icon-btn danger remove-btn" title="Remove">×</button>
      </div>
    `).join(''));

    $list.find('.relist-btn').on('click', function () {
      window.location.href = `product-form.html?from_pantry=${$(this).closest('.pantry-row').data('id')}`;
    });

    $list.find('.qty-minus').on('click', function () {
      const $row = $(this).closest('.pantry-row');
      const qty = Math.max(1, parseInt($row.find('.qty-stepper span').text(), 10) - 1);
      Pantry.updateQuantity($row.data('id'), qty);
    });
    $list.find('.qty-plus').on('click', function () {
      const $row = $(this).closest('.pantry-row');
      const qty = parseInt($row.find('.qty-stepper span').text(), 10) + 1;
      Pantry.updateQuantity($row.data('id'), qty);
    });
    $list.find('.remove-btn').on('click', function () {
      Pantry.remove($(this).closest('.pantry-row').data('id'));
    });
  },

  updateQuantity(id, quantity) {
    $.ajax({
      url: `${API_BASE}/pantry/update.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify({ id, quantity }),
    }).done(() => this.load());
  },

  remove(id) {
    $.ajax({
      url: `${API_BASE}/pantry/remove.php`, method: 'POST', contentType: 'application/json',
      data: JSON.stringify({ id }),
    }).done(() => this.load());
  },
};
