<script>
  import { enhance } from '$app/forms';
  import { locale, t, localized } from '$lib/i18n/store.js';

  export let data;
  export let form;
  $: lang = $locale;
  $: ({ categories } = data);

  $: createErrors = form?.action === 'create' ? (form.errors ?? {}) : {};
  $: createValues = form?.action === 'create' ? (form.values ?? {}) : {};

  function rowErrors(id) {
    return form?.action === 'update' && form.id === id ? (form.errors ?? {}) : {};
  }

  function confirmDelete(cat) {
    const name = localized(cat, 'name', lang) || cat.name_en || cat.name_tg;
    const template = cat.part_count > 0
      ? $t('categories.delete_confirm_with_parts')
      : $t('categories.delete_confirm');
    const msg = template.replace('{name}', name).replace('{count}', cat.part_count);
    return (e) => { if (!confirm(msg)) e.preventDefault(); };
  }
</script>

<h2>{$t('categories.title')}</h2>

<p class="muted">{$t('categories.intro')}</p>

<!--
  The update and delete forms live outside the table because a <form> is not
  permitted as a child of <tr>. Inputs inside the rows associate via the
  HTML `form` attribute.
-->
{#each categories as c (c.id)}
  <form method="POST" action="?/update" use:enhance id={`row-${c.id}`} hidden>
    <input type="hidden" name="id" value={c.id} />
  </form>
  <form method="POST" action="?/delete" use:enhance id={`del-${c.id}`}
        on:submit={confirmDelete(c)} hidden>
    <input type="hidden" name="id" value={c.id} />
  </form>
{/each}

<table>
  <thead>
    <tr>
      <th class="num">{$t('categories.sort')}</th>
      <th>{$t('parts.name_en')}</th>
      <th>{$t('parts.name_tg')}</th>
      <th class="num">{$t('categories.part_count')}</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    {#each categories as c (c.id)}
      {@const errs = rowErrors(c.id)}
      <tr>
        <td class="num">
          <input form={`row-${c.id}`} name="sort_order" type="number" step="1"
                 value={c.sort_order} class="sort-input" />
        </td>
        <td>
          <input form={`row-${c.id}`} name="name_en" value={c.name_en ?? ''} />
        </td>
        <td>
          <input form={`row-${c.id}`} name="name_tg" value={c.name_tg ?? ''} />
        </td>
        <td class="num">{c.part_count}</td>
        <td class="actions">
          <button form={`row-${c.id}`} type="submit">{$t('common.save')}</button>
          <button form={`del-${c.id}`} type="submit" class="danger">{$t('common.delete')}</button>
          {#if errs.name}<div class="field-error">{$t(errs.name)}</div>{/if}
          {#if errs.sort_order}<div class="field-error">{$t(errs.sort_order)}</div>{/if}
        </td>
      </tr>
    {/each}
  </tbody>
</table>

<h2>{$t('categories.add')}</h2>
<form class="stack" method="POST" action="?/create" use:enhance>
  <div class="row">
    <label>
      {$t('parts.name_en')}
      <input name="name_en" value={createValues.name_en ?? ''} />
    </label>
    <label>
      {$t('parts.name_tg')}
      <input name="name_tg" value={createValues.name_tg ?? ''} />
    </label>
  </div>
  <label>
    {$t('categories.sort_order')}
    <input name="sort_order" type="number" step="1" value={createValues.sort_order ?? '0'} />
  </label>
  {#if createErrors.name}<span class="field-error">{$t(createErrors.name)}</span>{/if}
  {#if createErrors.sort_order}<span class="field-error">{$t(createErrors.sort_order)}</span>{/if}
  <div>
    <button type="submit">{$t('categories.add_button')}</button>
  </div>
</form>

<style>
  .actions { display: flex; gap: 0.4rem; align-items: center; flex-wrap: wrap; }
  .sort-input { width: 4.5rem; text-align: right; }
  .field-error { color: #8a1f1b; font-size: 0.8rem; width: 100%; }
  td input { width: 100%; }
  td.num input { width: auto; }
</style>
