{{ define "content" }}
<div class="page-head">
  <h1>{{ T "nav.inventory" }}</h1>
  <input type="search" id="stock-search" placeholder="{{ T "inventory.search_placeholder" }}" autocomplete="off">
</div>

<div class="catalog-layout">
  <div class="catalog-list">
    <div class="card">
      <h2>{{ T "inventory.stock_levels" }}</h2>
      <table class="table" id="stock-table">
        <thead><tr><th>{{ T "basket.col.item" }}</th><th>{{ T "catalog.col.sku" }}</th><th>{{ T "inventory.location" }}</th><th>{{ T "basket.col.qty" }}</th><th>{{ T "inventory.reorder_at" }}</th></tr></thead>
        <tbody>
          {{ if .StockLevels }}
            {{ range .StockLevels }}
              <tr class="stock-row" data-item="{{ .ItemID }}" data-name="{{ .Name }}" data-sku="{{ .SKU }}" data-location="{{ .LocationID }}">
                <td class="catalog-name">{{ .Name }}</td>
                <td class="muted">{{ .SKU }}</td>
                <td>{{ .LocationName }}</td>
                <td class="{{ if .Low }}stock-low{{ end }}">{{ .CurrentQty }}</td>
                <td class="muted">{{ if .ReorderLevel }}{{ .ReorderLevel }}{{ else }}—{{ end }}</td>
              </tr>
            {{ end }}
          {{ else }}
            <tr><td colspan="5" class="empty">{{ T "inventory.empty" }}</td></tr>
          {{ end }}
        </tbody>
      </table>
    </div>

    <div class="card" style="margin-top:1rem">
      <h2>{{ T "inventory.low_stock" }} <span id="low-stock-badge" class="tag" style="background:rgba(220,38,38,.12); color:var(--danger)">0</span></h2>
      <div id="low-stock-list" hx-get="/api/inventory/low-stock" hx-trigger="load" hx-swap="innerHTML">
        {{ T "common.loading" }}
      </div>
    </div>
  </div>

  <div class="card catalog-form">
    <h3>{{ T "inventory.receive_adjust" }}</h3>
    <form id="stock-form" hx-post="/api/inventory/receipt" hx-swap="innerHTML" hx-target="#result">
      <label>{{ T "inventory.type" }}
        <select name="type" required>
          <option value="receive">{{ T "inventory.type_receipt" }}</option>
          <option value="adjust">{{ T "inventory.type_adjustment" }}</option>
        </select>
      </label>
      <label>{{ T "basket.col.item" }}
        <input type="text" id="stock-item-search" list="items-list" placeholder="{{ T "inventory.item_placeholder" }}" required>
        <input type="hidden" name="item_id" id="stock-item-id">
      </label>
      <div class="field-pair">
        <label>{{ T "inventory.location" }}
          <select name="location_id" id="stock-location" required>
            {{ range .Locations }}<option value="{{ .ID }}">{{ .Name }}</option>{{ end }}
          </select>
        </label>
        <label>{{ T "inventory.quantity" }} <input type="number" name="quantity" step="0.01" required placeholder="{{ T "inventory.qty_placeholder" }}"></label>
      </div>
      <div class="field-pair">
        <label>{{ T "inventory.cost_optional" }} <input type="number" id="stock-cost" step="0.01" min="0"></label>
        <input type="hidden" name="cost_price" id="stock-cost-minor">
      </div>
      <label>{{ T "inventory.reason" }} <input type="text" name="reason" placeholder="{{ T "inventory.reason_placeholder" }}"></label>
      <button type="submit" class="btn primary" style="width:100%">{{ T "common.submit" }}</button>
      <div id="result" class="muted" style="min-height:1.3rem; margin-top:.4rem"></div>
    </form>

    <details class="catalog-extra">
      <summary>{{ T "inventory.override_title" }}</summary>
      <form id="override-form" hx-post="/api/inventory/override" hx-swap="innerHTML" hx-target="#override-result">
        <label>{{ T "basket.col.item" }}
          <input type="text" list="items-list" class="override-item-search" placeholder="{{ T "inventory.item_placeholder" }}" required>
          <input type="hidden" name="item_id" class="override-item-id">
        </label>
        <div class="field-pair">
          <label>{{ T "inventory.location" }}
            <select name="location_id" required>
              {{ range .Locations }}<option value="{{ .ID }}">{{ .Name }}</option>{{ end }}
            </select>
          </label>
          <label>{{ T "inventory.current_qty" }} <input type="number" name="qty_before" step="0.01" required></label>
        </div>
        <div class="field-pair">
          <label>{{ T "inventory.requested_qty" }} <input type="number" name="qty_requested" step="0.01" required></label>
          <label>{{ T "inventory.manager_pin" }} <input type="password" name="manager_pin" inputmode="numeric" pattern="[0-9]{4,8}" maxlength="8" placeholder="{{ T "inventory.manager_pin_placeholder" }}"></label>
        </div>
        <label>{{ T "inventory.reason" }} <input type="text" name="reason" required placeholder="{{ T "inventory.override_reason_placeholder" }}"></label>
        <button type="submit" class="btn">{{ T "inventory.authorize_override" }}</button>
        <div id="override-result" class="muted" style="min-height:1.3rem; margin-top:.4rem"></div>
      </form>
    </details>

    <details class="catalog-extra">
      <summary>{{ T "inventory.return_title" }}</summary>
      <form id="return-form" hx-post="/api/inventory/return" hx-swap="innerHTML" hx-target="#return-result">
        <label>{{ T "inventory.original_receipt" }} <input type="text" name="receipt_no" required placeholder="000000123"></label>
        <label>{{ T "inventory.reason" }} <input type="text" name="reason" required placeholder="{{ T "inventory.return_reason_placeholder" }}"></label>
        <p class="muted" style="font-size:.8rem">{{ T "inventory.return_note" }}</p>
        <button type="submit" class="btn">{{ T "inventory.process_return" }}</button>
        <div id="return-result" class="muted" style="min-height:1.3rem; margin-top:.4rem"></div>
      </form>
    </details>
  </div>
</div>

<datalist id="items-list"></datalist>
<script id="inventory-items" type="application/json">{{ .ItemsJSON }}</script>
<script>
(function () {
  var items = JSON.parse(document.getElementById('inventory-items').textContent || '[]');
  var byLabel = {};
  var dl = document.getElementById('items-list');
  items.forEach(function (it) {
    var label = it.name + (it.sku ? ' (' + it.sku + ')' : '');
    byLabel[label.toLowerCase()] = it.id;
    var opt = document.createElement('option');
    opt.value = label;
    dl.appendChild(opt);
  });

  function bindPicker(searchEl, hiddenEl) {
    function resolve() {
      var v = (searchEl.value || '').toLowerCase();
      hiddenEl.value = byLabel[v] || '';
      searchEl.setCustomValidity(hiddenEl.value ? '' : 'Pick an item from the list');
    }
    searchEl.addEventListener('input', resolve);
    searchEl.addEventListener('change', resolve);
  }
  bindPicker(document.getElementById('stock-item-search'), document.getElementById('stock-item-id'));
  var os = document.querySelector('.override-item-search');
  if (os) bindPicker(os, document.querySelector('.override-item-id'));

  // Row click fills the receive form.
  document.addEventListener('click', function (ev) {
    var row = ev.target.closest('.stock-row');
    if (!row) return;
    var label = row.dataset.name + (row.dataset.sku ? ' (' + row.dataset.sku + ')' : '');
    var searchEl = document.getElementById('stock-item-search');
    searchEl.value = label;
    document.getElementById('stock-item-id').value = row.dataset.item;
    searchEl.setCustomValidity('');
    var loc = document.getElementById('stock-location');
    if (row.dataset.location) loc.value = row.dataset.location;
  });

  // Cost in pounds → minor units.
  document.getElementById('stock-form').addEventListener('submit', function () {
    var pounds = parseFloat(document.getElementById('stock-cost').value || '');
    document.getElementById('stock-cost-minor').value = isNaN(pounds) ? '' : Math.round(pounds * 100);
  });

  // Search filter over stock rows.
  var search = document.getElementById('stock-search');
  search.addEventListener('input', function () {
    var q = search.value.toLowerCase();
    document.querySelectorAll('.stock-row').forEach(function (row) {
      var hay = (row.dataset.name + ' ' + row.dataset.sku).toLowerCase();
      row.hidden = q !== '' && hay.indexOf(q) === -1;
    });
  });
})();
</script>
{{ end }}
