{% extends "admin/base.html" %}
{% import "macros/ui.html" as ui %}

{% block title %}{{ t(key="set-discount", lang=lang | default(value='sk')) }}{% endblock title %}
{% block crumb %}{{ t(key="admin-discounts", lang=lang | default(value='sk')) }}{% endblock crumb %}

{% block content %}
<div class="flex items-center justify-between gap-3">
  <div>
    <h1 class="text-2xl font-bold text-on-surface-strong dark:text-on-surface-dark-strong">{{ product.name }}</h1>
    <p class="text-sm text-on-surface/70 dark:text-on-surface-dark/70">
      {% if audience == "business" %}{{ t(key="audience-business", lang=lang | default(value='sk')) }}{% else %}{{ t(key="audience-personal", lang=lang | default(value='sk')) }}{% endif %}
    </p>
  </div>
  {{ ui::button(variant="outline-secondary", label=t(key="cancel", lang=lang | default(value='sk')), href="/admin/catalog/products?audience=" ~ audience, size="px-3 py-2 text-sm") }}
</div>

{# One discount row per option (variant). Each row picks a fixed sale price or a   #}
{# percentage off its own regular price; a blank input clears that option's        #}
{# discount. Both the fixed and percent inputs always submit (the server reads the #}
{# active mode); rows are pre-filled from `rows` (DB values, or submitted values   #}
{# when repainting after a validation error) and indexed as v[<variant id>][...].  #}
<script id="discount-data" type="application/json">{{ rows | json_encode() | safe }}</script>

<form method="post" action="/admin/catalog/products/{{ product.id }}/discount?audience={{ audience }}"
  x-data="discountEditor(JSON.parse(document.getElementById('discount-data').textContent))"
  class="mt-6 max-w-2xl space-y-5">
  {{ ui::csrf_field() }}

  {% if error %}
  {{ ui::alert_danger(message=t(key=error, lang=lang | default(value='sk'))) }}
  {% endif %}

  <template x-for="row in rows" :key="row.id">
    <div class="space-y-4 rounded-radius border border-outline bg-surface p-5 dark:border-outline-dark dark:bg-surface-dark-alt">
      <div class="flex items-center justify-between gap-3">
        <span class="font-semibold text-on-surface-strong dark:text-on-surface-dark-strong"
          x-text="row.label || ('#' + row.id)"></span>
        <span class="text-sm tabular-nums text-on-surface/70 dark:text-on-surface-dark/70">
          {{ t(key="price", lang=lang | default(value='sk')) }}:
          <span x-text="row.regular_price"></span> €
        </span>
      </div>

      <input type="hidden" :name="`v[${row.id}][mode]`" :value="row.mode">

      <div class="grid gap-4 sm:grid-cols-2">
        <!-- mode toggle -->
        <div class="grid grid-cols-2 gap-2">
          <label class="flex cursor-pointer items-center justify-center gap-2 rounded-radius border px-3 py-2 text-sm transition"
            :class="row.mode === 'fixed' ? 'border-primary bg-primary/10 text-on-surface-strong dark:border-primary-dark dark:bg-primary-dark/10 dark:text-on-surface-dark-strong' : 'border-outline text-on-surface dark:border-outline-dark dark:text-on-surface-dark'">
            <input type="radio" :name="`mode-ui-${row.id}`" value="fixed" x-model="row.mode" class="sr-only">
            {{ t(key="discount-mode-fixed", lang=lang | default(value='sk')) }}
          </label>
          <label class="flex cursor-pointer items-center justify-center gap-2 rounded-radius border px-3 py-2 text-sm transition"
            :class="row.mode === 'percent' ? 'border-primary bg-primary/10 text-on-surface-strong dark:border-primary-dark dark:bg-primary-dark/10 dark:text-on-surface-dark-strong' : 'border-outline text-on-surface dark:border-outline-dark dark:text-on-surface-dark'">
            <input type="radio" :name="`mode-ui-${row.id}`" value="percent" x-model="row.mode" class="sr-only">
            {{ t(key="discount-mode-percent", lang=lang | default(value='sk')) }}
          </label>
        </div>

        <!-- value input: both fields stay in the DOM and submit; the server reads
             whichever matches the row's mode -->
        <div class="space-y-1.5">
          <div x-show="row.mode === 'fixed'">
            <label class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="sale-price", lang=lang | default(value='sk')) }}</label>
            <input :name="`v[${row.id}][fixed]`" x-model="row.fixed" inputmode="decimal" placeholder="0.00"
              class="w-full rounded-radius border border-outline bg-surface-alt px-4 py-2 text-sm text-on-surface focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark dark:focus-visible:outline-primary-dark">
          </div>
          <div x-show="row.mode === 'percent'">
            <label class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="discount-percent", lang=lang | default(value='sk')) }}</label>
            <input :name="`v[${row.id}][percent]`" x-model="row.percent" inputmode="decimal" min="0" max="100" placeholder="0"
              class="w-full rounded-radius border border-outline bg-surface-alt px-4 py-2 text-sm text-on-surface focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark dark:focus-visible:outline-primary-dark">
          </div>
        </div>
      </div>

      <!-- live preview -->
      <div x-show="afterCents(row) !== null" x-cloak
        class="flex flex-wrap items-center justify-between gap-3 rounded-radius border border-outline bg-surface-alt px-4 py-2.5 text-sm dark:border-outline-dark dark:bg-surface-dark/40">
        <span class="text-on-surface/70 dark:text-on-surface-dark/70">{{ t(key="discount-preview-after", lang=lang | default(value='sk')) }}</span>
        <span class="flex items-center gap-2">
          <span class="tabular-nums text-on-surface/50 line-through dark:text-on-surface-dark/50" x-text="money(row.regular_cents) + ' €'"></span>
          <span class="text-base font-semibold tabular-nums" :class="valid(row) ? 'text-danger' : 'text-on-surface/40 dark:text-on-surface-dark/40'"
            x-text="money(afterCents(row)) + ' €'"></span>
          <span x-show="valid(row)" class="text-xs text-on-surface/60 dark:text-on-surface-dark/60" x-text="'(−' + percentOff(row) + '%)'"></span>
        </span>
      </div>
      <p x-show="afterCents(row) !== null && !valid(row)" class="text-xs text-danger">{{ t(key="discount-below-regular", lang=lang | default(value='sk')) }}</p>
    </div>
  </template>

  <div class="flex flex-wrap gap-3 pt-2">
    {{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit", attrs=`onclick="return confirm('` ~ t(key="discount-apply-confirm", lang=lang | default(value='sk')) ~ `')"`) }}
    {% if has_discount %}
    {{ ui::button(variant="outline-danger", label=t(key="remove-discount", lang=lang | default(value='sk')), type="submit", attrs=`formaction="/admin/catalog/products/` ~ product.id ~ `/discount/remove?audience=` ~ audience ~ `" onclick="return confirm('` ~ t(key="discount-remove-confirm", lang=lang | default(value='sk')) ~ `')"`) }}
    {% endif %}
  </div>
</form>

<script>
  function discountEditor(initial) {
    return {
      rows: (initial || []).map(r => ({
        id: r.id,
        label: r.label || '',
        regular_cents: r.regular_cents,
        regular_price: r.regular_price,
        mode: r.mode || 'fixed',
        fixed: r.fixed || '',
        percent: r.percent || '',
      })),
      num(v) { let n = parseFloat(String(v).replace(',', '.')); return isFinite(n) ? n : null; },
      money(c) { return (c / 100).toFixed(2); },
      afterCents(row) {
        if (row.mode === 'percent') {
          let p = this.num(row.percent); if (p === null) return null;
          return row.regular_cents - Math.round(row.regular_cents * p / 100);
        }
        let f = this.num(row.fixed); if (f === null) return null;
        return Math.round(f * 100);
      },
      valid(row) { let a = this.afterCents(row); return a !== null && a > 0 && a < row.regular_cents; },
      percentOff(row) {
        let a = this.afterCents(row);
        return (a === null || row.regular_cents <= 0) ? null : Math.round((row.regular_cents - a) / row.regular_cents * 100);
      },
    };
  }
</script>
{% endblock content %}
