'use strict';

appReady.then(async () => {
  const loading = document.getElementById('pricesLoading');
  const empty = document.getElementById('pricesEmpty');
  const wrap = document.getElementById('pricesTableWrap');
  const body = document.getElementById('pricesBody');
  const date = document.getElementById('priceDate');
  const count = document.getElementById('priceCount');
  const search = document.getElementById('priceSearch');
  let prices = [];

  function render() {
    const query = search.value.trim().toLowerCase();
    const filtered = prices.filter((item) => item.product_name.toLowerCase().includes(query));
    body.innerHTML = filtered.map((item) => `
      <article class="price-card">
        <div>
          <div class="price-name">${VegApi.escapeHtml(item.product_name)}</div>
          <div class="price-label">سعر البيع المعتمد</div>
        </div>
        <div class="price-box">
          <div class="price-value money">${VegApi.formatNumber(item.sale_price, 2)}</div>
          <div class="price-currency">ريال</div>
        </div>
      </article>`).join('');

    count.textContent = filtered.length === prices.length
      ? `${prices.length} صنف بسعر معتمد`
      : `${filtered.length} نتيجة من أصل ${prices.length}`;

    if (!filtered.length && prices.length) {
      body.innerHTML = '<div class="empty-state price-empty-result">لا توجد نتيجة مطابقة.</div>';
    }
  }

  try {
    const result = await VegApi.request('/api/prices/latest');
    loading.hidden = true;
    if (!result.custody) {
      empty.hidden = false;
      return;
    }
    prices = result.prices;
    date.textContent = `${result.custody.custody_name || 'آخر عهدة محفوظة'} · ${VegApi.formatDate(result.custody.custody_date)}`;
    wrap.hidden = false;
    render();
    search.addEventListener('input', render);
  } catch (error) {
    loading.textContent = error.message;
  }
});
