<script>
  import { goto } from '$app/navigation';
  import { locale, t, localized, formatMoney, hasTranslation } from '$lib/i18n/store.js';

  export let data;
  $: lang = $locale;
  $: ({ parts, categories, q, sort, dir, categoryIds } = data);

  let search = data.q;
  let searchTimer = null;

  $: selectedSet = new Set(categoryIds);

  function navigate({ qNext = search, sortNext = sort, dirNext = dir, catsNext = categoryIds } = {}) {
    const params = new URLSearchParams();
    if (qNext) params.set('q', qNext);
    if (catsNext.length) params.set('category', catsNext.join(','));
    if (sortNext && sortNext !== 'name_en') params.set('sort', sortNext);
    if (dirNext && dirNext !== 'asc') params.set('dir', dirNext);
    const target = '/parts' + (params.toString() ? '?' + params.toString() : '');
    goto(target, { replaceState: true, keepFocus: true, noScroll: true });
  }

  function onSearchInput() {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => navigate({ qNext: search }), 150);
  }

  function clearSearch() {
    clearTimeout(searchTimer);
    search = '';
    navigate({ qNext: '' });
  }

  function toggleCategory(id) {
    const next = selectedSet.has(id)
      ? categoryIds.filter((c) => c !== id)
      : [...categoryIds, id];
    navigate({ catsNext: next });
  }

  function clearCategories() {
    navigate({ catsNext: [] });
  }

  function sortBy(col) {
    let nextDir = 'asc';
    if (sort === col && dir === 'asc') nextDir = 'desc';
    navigate({ sortNext: col, dirNext: nextDir });
  }

  // Reactive so the header indicators refresh when `sort` / `dir` change.
  // A plain function declaration wouldn't — Svelte tracks reactive deps via
  // static analysis and doesn't look inside function bodies.
  $: arrow = (col) => (sort === col ? (dir === 'asc' ? '▲' : '▼') : '');
</script>

<div class="page-head">
  <h1>{$t('parts.title')}</h1>
  <a class="add-btn" href="/parts/new">+ {$t('nav.new_part')}</a>
</div>

<div class="search">
  <input type="search"
         bind:value={search}
         on:input={onSearchInput}
         placeholder={$t('parts.search_placeholder')} />
  {#if search}
    <button type="button" class="secondary" on:click={clearSearch}>
      {$t('common.clear')}
    </button>
  {/if}
</div>

{#if categories.length > 0}
  <div class="filters" role="group" aria-label={$t('parts.category')}>
    <button type="button"
            class="chip"
            class:active={categoryIds.length === 0}
            aria-pressed={categoryIds.length === 0}
            on:click={clearCategories}>
      {$t('parts.all')}
    </button>
    {#each categories as c}
      <button type="button"
              class="chip"
              class:active={selectedSet.has(c.id)}
              aria-pressed={selectedSet.has(c.id)}
              on:click={() => toggleCategory(c.id)}>
        {localized(c, 'name', lang)}
      </button>
    {/each}
  </div>
{/if}

{#if parts.length === 0}
  <p class="muted card">{$t('parts.no_results')}</p>
{:else}
  <table>
    <thead>
      <tr>
        <th><button class="th-btn" on:click={() => sortBy(lang === 'tg' ? 'name_tg' : 'name_en')}>{$t('parts.name')} {arrow(lang === 'tg' ? 'name_tg' : 'name_en')}</button></th>
        <th>{$t('parts.category')}</th>
        <th class="num"><button class="th-btn" on:click={() => sortBy('quantity_on_hand')}>{$t('parts.quantity_on_hand')} {arrow('quantity_on_hand')}</button></th>
        <th class="num"><button class="th-btn" on:click={() => sortBy('reorder_level')}>{$t('parts.reorder_level')} {arrow('reorder_level')}</button></th>
        <th class="num"><button class="th-btn" on:click={() => sortBy('sale_price')}>{$t('parts.sale_price')} {arrow('sale_price')}</button></th>
      </tr>
    </thead>
    <tbody>
      {#each parts as p}
        <tr>
          <td>
            <a href="/parts/{p.id}">{localized(p, 'name', lang)}</a>
            {#if !hasTranslation(p, 'name', lang)}
              <em class="missing">{$t('common.missing_translation')}</em>
            {/if}
          </td>
          <td>{localized({name_en: p.category_name_en, name_tg: p.category_name_tg}, 'name', lang) || $t('common.none')}</td>
          <td class="num">
            {#if p.quantity_on_hand <= p.reorder_level}
              <span class="pill low">{p.quantity_on_hand}</span>
            {:else}
              {p.quantity_on_hand}
            {/if}
          </td>
          <td class="num">{p.reorder_level}</td>
          <td class="num">{formatMoney(p.sale_price, lang)}</td>
        </tr>
      {/each}
    </tbody>
  </table>
{/if}

<style>
  .page-head { display: flex; align-items: center; justify-content: space-between; }
  .add-btn {
    background: #006a4e;
    color: #fff;
    padding: 0.5rem 0.9rem;
    border-radius: 4px;
    text-decoration: none;
  }
  .add-btn:hover { background: #00553e; color: #fff; }
  .search {
    display: flex;
    gap: 0.5rem;
    margin: 0.5rem 0 0.75rem;
  }
  .search input { flex: 1; }
  .filters {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    margin: 0 0 1rem;
  }
  .chip {
    background: #fff;
    color: #1d2330;
    border: 1px solid #c8cfdc;
    padding: 0.3rem 0.75rem;
    border-radius: 999px;
    font-size: 0.85rem;
    font-weight: 500;
    line-height: 1.2;
    cursor: pointer;
    transition: background 0.1s, border-color 0.1s, color 0.1s;
  }
  .chip:hover { background: #f0f2f6; }
  .chip.active {
    background: #006a4e;
    color: #fff;
    border-color: #006a4e;
  }
  .chip.active:hover { background: #00553e; border-color: #00553e; }
  .th-btn {
    background: transparent;
    color: inherit;
    border: none;
    padding: 0;
    font: inherit;
    font-weight: 600;
    cursor: pointer;
  }
  .th-btn:hover { color: #006a4e; background: transparent; }
  .missing {
    color: #8a6f1b;
    font-size: 0.8em;
    margin-left: 0.35rem;
    font-style: italic;
  }
</style>
