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

{% block title %}{% if product %}{{ t(key="edit-product", lang=lang | default(value='sk')) }}{% else %}{{ t(key="new-product", lang=lang | default(value='sk')) }}{% endif %}{% endblock title %}
{% block crumb %}{{ t(key="admin-products", lang=lang | default(value='sk')) }}{% endblock crumb %}
{% block head %}
<link href="/static/vendor/quill/quill.snow.css" rel="stylesheet" type="text/css">
{% endblock head %}

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

<form method="post" enctype="multipart/form-data"
  action="{% if product %}/admin/catalog/products/{{ product.id }}{% else %}/admin/catalog/products{% endif %}"
  class="mt-6 space-y-5 rounded-radius border border-outline bg-surface p-6 dark:border-outline-dark dark:bg-surface-dark-alt">
  {{ ui::csrf_field() }}

  {% if product %}
    {% set v_name = product.name %}{% set v_desc = product.description | default(value="") %}{% set v_short = product.short_description | default(value="") %}{% set v_pub = product.published %}
  {% else %}
    {% set v_name = "" %}{% set v_desc = "" %}{% set v_short = "" %}{% set v_pub = false %}
  {% endif %}
  {% set inp = "w-full rounded-radius border border-outline bg-surface-alt px-3 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" %}
  {% set sublabel = "text-xs font-medium text-on-surface/70 dark:text-on-surface-dark/70" %}

  <div class="space-y-1.5">
    <label for="name" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="name", lang=lang | default(value='sk')) }}</label>
    {{ ui::input(name="name", id="name", required=true, value=v_name) }}
  </div>

  {# --- Variants / options editor ------------------------------------------- #}
  {# Each product is sold as one or more variants (a free-text label such as     #}
  {# "10cm x 13cm" or "5ml" plus its own price). Price is required. Stock is      #}
  {# optional — leave it blank ("∞") to mark the option simply available (not     #}
  {# inventory-tracked). SKU and business price are optional too. Rows are        #}
  {# managed client-side; names are indexed (variants[i][…]) and read back by     #}
  {# the controller.                                                              #}
  {% set opt = " (" ~ t(key="optional", lang=lang | default(value='sk')) ~ ")" %}
  <script id="variants-data" type="application/json">{{ variants | json_encode() | safe }}</script>
  <div class="space-y-3" x-data="variantEditor(JSON.parse(document.getElementById('variants-data').textContent))">
    <div class="flex items-center justify-between">
      <span class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="variants-options", lang=lang | default(value='sk')) }}</span>
      <button type="button" @click="add()"
        class="rounded-radius border border-outline px-3 py-1.5 text-sm font-medium text-on-surface hover:bg-surface-alt dark:border-outline-dark dark:text-on-surface-dark dark:hover:bg-surface-dark-alt/50">
        + {{ t(key="add-option", lang=lang | default(value='sk')) }}
      </button>
    </div>

    <template x-for="(row, i) in rows" :key="i">
      <div class="flex items-end gap-3 rounded-radius border border-outline bg-surface-alt/40 p-3 dark:border-outline-dark dark:bg-surface-dark-alt/30">
        <input type="hidden" :name="`variants[${i}][id]`" :value="row.id">

        {# items-end bottom-aligns every input regardless of how many lines each
           label takes, so the row stays aligned even with the "(optional)" notes. #}
        <div class="grid flex-1 grid-cols-2 gap-3 sm:grid-cols-12 sm:items-end">
          <div class="space-y-1 col-span-2 sm:col-span-6">
            <label class="{{ sublabel }} block truncate">{{ t(key="option-label", lang=lang | default(value='sk')) }}{{ opt }}</label>
            <input :name="`variants[${i}][label]`" x-model="row.label" class="{{ inp }}" placeholder="napr. 10cm x 13cm">
          </div>
          <div class="space-y-1 sm:col-span-2">
            <label class="{{ sublabel }} block truncate">{{ t(key="sku", lang=lang | default(value='sk')) }}{{ opt }}</label>
            <input :name="`variants[${i}][sku]`" x-model="row.sku" class="{{ inp }}">
          </div>
          <div class="space-y-1 sm:col-span-2">
            <label class="{{ sublabel }} block truncate">{{ t(key="stock", lang=lang | default(value='sk')) }}{{ opt }}</label>
            <input type="number" min="0" :name="`variants[${i}][stock]`" x-model="row.stock" class="{{ inp }}" placeholder="∞" title="{{ t(key='stock-untracked-hint', lang=lang | default(value='sk')) }}">
          </div>
          <div class="space-y-1 sm:col-span-2">
            <label class="{{ sublabel }} block truncate">{{ t(key="price", lang=lang | default(value='sk')) }} (€)</label>
            <input :name="`variants[${i}][price]`" x-model="row.price" inputmode="decimal" required class="{{ inp }}" placeholder="0.00">
          </div>
        </div>

        <button type="button" @click="remove(i)"
          class="mb-1 shrink-0 rounded-radius px-2 py-2 text-sm text-danger hover:bg-danger/10" title="{{ t(key='delete', lang=lang | default(value='sk')) }}">✕</button>
      </div>
    </template>
  </div>

  <script>
    function variantEditor(initial) {
      const blank = () => ({ id: '', label: '', sku: '', stock: '', price: '' });
      return {
        rows: (initial || []).map(r => ({
          id: r.id || '',
          label: r.label || '',
          sku: r.sku || '',
          stock: (r.stock === null || r.stock === undefined) ? '' : r.stock,
          price: r.price || '',
        })),
        init() { if (this.rows.length === 0) this.add(); },
        add() { this.rows.push(blank()); },
        remove(i) { this.rows.splice(i, 1); if (this.rows.length === 0) this.add(); },
      };
    }
  </script>

  <div class="space-y-1.5">
    <label for="category_id" class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="category", lang=lang | default(value='sk')) }}</label>
    <div class="relative">
      <select id="category_id" name="category_id"
        class="w-full appearance-none 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 disabled:cursor-not-allowed disabled:opacity-75 dark:border-outline-dark dark:bg-surface-dark-alt/50 dark:text-on-surface-dark dark:focus-visible:outline-primary-dark">
        <option value="">{{ t(key="no-category", lang=lang | default(value='sk')) }}</option>
        {% for category in categories %}
        <option value="{{ category.id }}" {% if product and product.category_id == category.id %}selected{% endif %}>{{ category.name }}</option>
        {% endfor %}
      </select>
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="pointer-events-none absolute right-3 top-1/2 size-5 -translate-y-1/2 text-on-surface/60 dark:text-on-surface-dark/60"><path fill-rule="evenodd" d="M5.22 8.22a.75.75 0 0 1 1.06 0L10 11.94l3.72-3.72a.75.75 0 1 1 1.06 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L5.22 9.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" /></svg>
    </div>
  </div>

  <div class="space-y-1.5">
    <span class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="short-description", lang=lang | default(value='sk')) }}</span>
    <p class="{{ sublabel }}">{{ t(key="short-description-hint", lang=lang | default(value='sk')) }}</p>
    {{ ui::rich_editor(name="short_description", lang=lang | default(value='sk'), value=v_short, min_height="6rem") }}
  </div>

  <div class="space-y-1.5">
    <span class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="description", lang=lang | default(value='sk')) }}</span>
    {{ ui::rich_editor(name="description", lang=lang | default(value='sk'), value=v_desc, min_height="16rem") }}
  </div>

  {# --- Images gallery ------------------------------------------------------- #}
  {# Unified drag-orderable gallery: existing images (with id) and new uploads       #}
  {# (placeholder blobs) live in a single list. The full order is submitted as        #}
  {# repeated `image_order` fields — an integer id for kept images or `new` for       #}
  {# each uploaded file. The DataTransfer backing the hidden `image` file input       #}
  {# is rebuilt after every reorder / add / remove so the file-part order matches     #}
  {# the relative order of `new` slots in `image_order`.                              #}
  <script id="images-data" type="application/json">{% if product %}{{ product.images | json_encode() | safe }}{% else %}[]{% endif %}</script>
  <div class="space-y-2" x-data="{
        init() {
          const existing = JSON.parse(document.getElementById('images-data').textContent);
          this.items = existing.map(im => ({ type: 'existing', id: im.id, image_id: im.image_id }));
        },
        items: [],
        dt: new DataTransfer(),
        dragIndex: null,

        rebuildDt() {
          this.dt = new DataTransfer();
          for (const it of this.items) {
            if (it.type === 'new') this.dt.items.add(it.file);
          }
          this.$refs.holder.files = this.dt.files;
        },

        onDrop(i) {
          if (this.dragIndex === null || this.dragIndex === i) { this.dragIndex = null; return; }
          this.items.splice(i, 0, this.items.splice(this.dragIndex, 1)[0]);
          this.dragIndex = null;
          this.rebuildDt();
        },

        addFiles(e) {
          for (const f of e.target.files) {
            this.items.push({ type: 'new', file: f, url: URL.createObjectURL(f) });
          }
          this.rebuildDt();
          e.target.value = '';
        },

        remove(i) {
          const it = this.items[i];
          if (it.type === 'new') URL.revokeObjectURL(it.url);
          this.items.splice(i, 1);
          this.rebuildDt();
        },
      }">
    <span class="text-sm font-medium text-on-surface-strong dark:text-on-surface-dark-strong">{{ t(key="images", lang=lang | default(value='sk')) }}</span>
    <p class="{{ sublabel }}">{{ t(key="gallery-hint", lang=lang | default(value='sk')) }}</p>

    <div class="flex flex-wrap gap-3" x-show="items.length">
      <template x-for="(it, i) in items" :key="it.type === 'existing' ? it.id : it.url">
        <div draggable="true"
          @dragstart="dragIndex = i"
          @dragover.prevent
          @drop.prevent="onDrop(i)"
          :class="dragIndex === i ? 'opacity-50' : ''"
          class="group relative size-24 cursor-move overflow-hidden rounded-radius border border-outline dark:border-outline-dark">

          <input type="hidden" name="image_order" :value="it.type === 'existing' ? it.id : 'new'">

          <img :src="it.type === 'existing' ? `/images/${it.image_id}` : it.url" alt="" class="size-full object-cover">

          <span x-show="i === 0"
            class="absolute left-1 top-1 rounded-radius bg-primary px-1.5 py-0.5 text-[10px] font-semibold text-on-primary dark:bg-primary-dark dark:text-on-primary-dark">{{ t(key="main-image", lang=lang | default(value='sk')) }}</span>
          <button type="button" @click="remove(i)"
            class="absolute right-1 top-1 flex size-5 items-center justify-center rounded-full bg-surface/70 text-xs text-danger opacity-0 transition group-hover:opacity-100 dark:bg-surface-dark/70"
            title="{{ t(key='delete', lang=lang | default(value='sk')) }}">✕</button>
        </div>
      </template>
    </div>

    {# Hidden input carries the accumulated files on submit; the visible picker   #}
    {# only feeds addFiles() and is reset after each pick so selections stack.     #}
    <input type="file" name="image" multiple class="hidden" x-ref="holder">
    <input type="file" accept="image/*" multiple class="hidden" x-ref="picker" @change="addFiles($event)">
    <button type="button" @click="$refs.picker.click()"
      class="rounded-radius border border-outline px-3 py-1.5 text-sm font-medium text-on-surface hover:bg-surface-alt dark:border-outline-dark dark:text-on-surface-dark dark:hover:bg-surface-dark-alt/50">
      + {{ t(key="add-images", lang=lang | default(value='sk')) }}
    </button>
  </div>

  {{ ui::checkbox(name="published", id="published", label=t(key="published", lang=lang | default(value='sk')), checked=v_pub) }}

  <div class="flex gap-3 pt-2">
    {{ ui::button(label=t(key="save", lang=lang | default(value='sk')), type="submit") }}
    {{ ui::button(variant="outline-secondary", label=t(key="cancel", lang=lang | default(value='sk')), href="/admin/catalog/products") }}
  </div>
</form>
<script src="/static/vendor/quill/quill.js"></script>
<script src="/static/js/rich-editor.js"></script>
{% endblock content %}
