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

  export let data;
  $: lang = $locale;
  $: ({ invoice, lines } = data);

  function lineLabel(line) {
    if (line.affects_inventory === 0) return line.label;
    return localized({ name_en: line.part_name_en, name_tg: line.part_name_tg }, 'name', lang);
  }
</script>

<article class="receipt">
  <header class="head">
    <div>
      <h1>{$t('invoices.saved_title')} #{invoice.id}</h1>
      <p class="muted">{formatTs(invoice.saved_at)}</p>
    </div>
    <a href="/invoices/new" class="print-hide back">← {$t('invoices.new_another')}</a>
  </header>

  <table>
    <thead>
      <tr>
        <th>{$t('invoices.item')}</th>
        <th class="num">{$t('movements.quantity')}</th>
        <th class="num">{$t('movements.unit_price')}</th>
        <th class="num">{$t('invoices.line_total')}</th>
      </tr>
    </thead>
    <tbody>
      {#each lines as line}
        {@const lineTotal = line.quantity * line.unit_price_dirams}
        <tr>
          <td>{lineLabel(line)}</td>
          <td class="num">{line.quantity}</td>
          <td class="num">{formatMoney(line.unit_price_dirams, lang)}</td>
          <td class="num">{formatMoney(lineTotal, lang)}</td>
        </tr>
      {/each}
    </tbody>
    <tfoot>
      <tr>
        <td colspan="3" class="num"><strong>{$t('invoices.saved_total')}</strong></td>
        <td class="num">
          <strong>{formatMoney(invoice.total_dirams, lang)} {$t('common.currency_short')}</strong>
        </td>
      </tr>
    </tfoot>
  </table>

  <section class="pay">
    <p class="muted">{$t('invoices.saved_thanks')}</p>
    <img src="/payment-qr.png" alt={$t('invoices.qr_alt')} class="qr" />
  </section>
</article>

<style>
  .receipt { max-width: 720px; margin: 0 auto; }
  .head {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    gap: 1rem;
    margin-bottom: 1rem;
  }
  .head h1 { margin: 0; }
  .head .muted { margin: 0.25rem 0 0; font-size: 0.9rem; }
  .back {
    text-decoration: none;
    padding: 0.4rem 0.8rem;
    border: 1px solid #c8cfdc;
    border-radius: 4px;
    background: #fff;
    font-size: 0.9rem;
  }
  tfoot td { background: #f5f7fb; }
  .pay {
    margin-top: 1.5rem;
    text-align: center;
  }
  .qr {
    display: block;
    margin: 0.75rem auto 0;
    max-width: 280px;
    width: 100%;
    height: auto;
    border: 1px solid #e5e8ee;
    background: #fff;
    padding: 6px;
  }

  @media print {
    :global(.header), :global(.lang) { display: none !important; }
    .print-hide { display: none !important; }
    :global(body) { background: #fff; }
    :global(.container) { padding: 0; max-width: 100%; }
  }
</style>
