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

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

  $: errors = form?.errors ?? {};
  $: values = form?.values ?? {};
</script>

<h1>{$t('parts.new')}</h1>

{#if errors.name}
  <div class="error">{$t(errors.name)}</div>
{/if}

<form class="stack" method="POST">
  <label>
    {$t('parts.sku')} *
    <input name="sku" required value={values.sku ?? ''} />
    {#if errors.sku}<span class="field-error">{$t(errors.sku)}</span>{/if}
  </label>

  <div class="row">
    <label>
      {$t('parts.name_en')}
      <input name="name_en" value={values.name_en ?? ''} />
    </label>
    <label>
      {$t('parts.name_tg')}
      <input name="name_tg" value={values.name_tg ?? ''} />
    </label>
  </div>

  <label>
    {$t('parts.category')}
    <select name="category_id">
      <option value="">—</option>
      {#each categories as c}
        <option value={c.id} selected={String(values.category_id) === String(c.id)}>
          {localized(c, 'name', lang)}
        </option>
      {/each}
    </select>
  </label>

  <div class="row">
    <label>
      {$t('parts.cost_price')} ({$t('common.currency_short')})
      <input name="cost_price" type="number" step="0.01" min="0" value={values.cost_price ?? ''} />
    </label>
    <label>
      {$t('parts.sale_price')} ({$t('common.currency_short')})
      <input name="sale_price" type="number" step="0.01" min="0" value={values.sale_price ?? ''} />
    </label>
  </div>

  <div class="row">
    <label>
      {$t('parts.unit')}
      <input name="unit" value={values.unit ?? 'pcs'} />
    </label>
    <label>
      {$t('parts.reorder_level')}
      <input name="reorder_level" type="number" min="0" step="1" value={values.reorder_level ?? 0} />
    </label>
  </div>

  <div class="row">
    <label>
      {$t('parts.initial_quantity')}
      <input name="quantity_on_hand" type="number" min="0" step="1" value={values.quantity_on_hand ?? 0} />
    </label>
    <label>
      {$t('parts.location')}
      <input name="location" value={values.location ?? ''} />
    </label>
  </div>

  <label>
    {$t('parts.barcode')}
    <input name="barcode" value={values.barcode ?? ''} />
  </label>

  <div class="row">
    <label>
      {$t('parts.description_en')}
      <textarea name="description_en">{values.description_en ?? ''}</textarea>
    </label>
    <label>
      {$t('parts.description_tg')}
      <textarea name="description_tg">{values.description_tg ?? ''}</textarea>
    </label>
  </div>

  <div class="actions">
    <button type="submit">{$t('common.save')}</button>
    <a href="/parts" class="cancel">{$t('common.cancel')}</a>
  </div>
</form>

<style>
  .actions { display: flex; gap: 1rem; align-items: center; }
  .cancel  { color: #6b7388; text-decoration: none; }
  .field-error { color: #8a1f1b; font-size: 0.8rem; }
</style>
