{include file="_partials/head.tpl"}

<div class="page-head">
  <div>
    <h1>{page.title}</h1>
    <p class="muted"><a href="/admin/shop/products">{lang key="shop.product.back_to_list"}</a></p>
  </div>
</div>

<form method="post" action="{form_action}" class="form form-tabs">
  {csrf}

  <nav class="tabs-nav">
    <button type="button" class="tabs-btn active" data-tab="general">{lang key="shop.product.tab_general"}</button>
    <button type="button" class="tabs-btn" data-tab="images">{lang key="shop.product.tab.images"}</button>
    <button type="button" class="tabs-btn" data-tab="variations">{lang key="shop.product.tab.variations"}</button>
    [if {attributes}]<button type="button" class="tabs-btn" data-tab="attributes">{lang key="shop.product.tab.attributes"}</button>[/if]
    <button type="button" class="tabs-btn" data-tab="seo">{lang key="shop.product.tab.seo"}</button>
    [if {custom_fields}]<button type="button" class="tabs-btn" data-tab="fields">{lang key="shop.product.tab.fields"}</button>[/if]
  </nav>

  <section class="tabs-pane active" data-pane="general">
    <div class="form-row">
      <div class="form-group"><label>{lang key="shop.common.title"}</label><input type="text" name="title" value="{row.title}" required></div>
      <div class="form-group"><label>Slug</label><input type="text" name="slug" value="{row.slug}" placeholder="{lang key="shop.product.slug_auto"}"></div>
    </div>

    <div class="form-row">
      <div class="form-group"><label>{lang key="shop.product.price"}</label><input type="number" name="price" value="{row.price}" step="0.01" min="0" required></div>
      <div class="form-group"><label>{lang key="shop.product.old_price_full"}</label><input type="number" name="old_price" value="{row.old_price}" step="0.01" min="0"></div>
    </div>

    <div class="form-row">
      <div class="form-group"><label>{lang key="shop.product.sku_full"}</label><input type="text" name="sku" value="{row.sku}"></div>
      <div class="form-group"><label>{lang key="shop.product.stock"}</label><input type="number" name="stock" value="{row.stock}" min="0"></div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>{lang key="shop.product.category"}</label>
        <select name="category_id">
          <option value="">{lang key="shop.product.no_category"}</option>
          [foreach var="categories" as="c"]
            <option value="{c.id}" [if {row.category_id}={c.id}]selected[/if]>{c.title}</option>
          [/foreach]
        </select>
      </div>
      <div class="form-group">
        <label>{lang key="shop.product.brand_label"}</label>
        <select name="manufacturer_id">
          <option value="">{lang key="shop.product.no_brand"}</option>
          [foreach var="manufacturers" as="m"]
            <option value="{m.id}" [if {row.manufacturer_id}={m.id}]selected[/if]>{m.title}</option>
          [/foreach]
        </select>
      </div>
      <div class="form-group">
        <label>{lang key="shop.product.barcode"}</label>
        <input type="text" name="barcode" value="{row.barcode}" placeholder="{lang key="shop.product.barcode_placeholder"}">
      </div>
    </div>

    <div class="form-row">
      <div class="form-group">
        <label>{lang key="shop.product.publish_status"}</label>
        <select name="status">
          <option value="active"   [if {row.status}="active"]selected[/if]>{lang key="shop.product.publish_active"}</option>
          <option value="draft"    [if {row.status}="draft"]selected[/if]>{lang key="shop.product.publish_draft"}</option>
          <option value="archived" [if {row.status}="archived"]selected[/if]>{lang key="shop.product.publish_archived"}</option>
        </select>
      </div>
      <div class="form-group">
        <label>{lang key="shop.product.featured_label"}</label>
        <label class="checkbox"><input type="checkbox" name="is_featured" value="1" [if {row.is_featured}]checked[/if]> {lang key="shop.product.featured_help"}</label>
      </div>
    </div>

    <div class="form-group">
      <label>{lang key="shop.product.short"}</label>
      <textarea name="short" rows="3">{row.short}</textarea>
    </div>

    <input type="hidden" name="body_format" value="html">
    <div class="form-group">
      <label>{lang key="shop.product.body"}</label>
      <textarea name="body" rows="12" data-celena-editor>{row.body|raw}</textarea>
    </div>
  </section>

  <section class="tabs-pane" data-pane="images">
    <div class="form-group">
      <label>{lang key="shop.product.images"}</label>
      <small class="help">{lang key="shop.product.images_help_full"}</small>

      <!-- cover пишется на клиенте: всегда первый url из списка ниже -->
      <input type="hidden" name="cover"  id="product-cover"  value="{row.cover}">
      <input type="hidden" name="images" id="product-images" value='{row.images}'>
      <input type="hidden" id="product-images-picker">

      <div id="product-gallery" class="pg-grid"></div>
    </div>
  </section>

  <section class="tabs-pane" data-pane="variations">
    <div class="hint-card hint-card-blue">
      <div class="hint-h">{icon name="box" size="16"} {lang key="shop.product.hint_var_title"}</div>
      <p>{lang key="shop.product.hint_var_p1"}</p>
      <p class="muted">{lang key="shop.product.hint_var_p2"}</p>
      <p class="hint-vs muted">{lang key="shop.product.hint_var_p3"}</p>
    </div>

    <div class="var-options" data-var-options>
      <h3 class="var-section-h">{lang key="shop.product.var_section_options"}</h3>
      <div data-var-options-list></div>
      <button type="button" class="btn btn-secondary" data-var-options-add>{lang key="shop.product.var_add_option"}</button>
    </div>

    <div class="var-matrix" data-var-matrix style="margin-top:24px">
      <h3 class="var-section-h">
        {lang key="shop.product.combinations"}
        <button type="button" class="btn btn-secondary" data-var-regen style="margin-left:auto">{lang key="shop.product.var_regenerate"}</button>
      </h3>
      <p class="muted">{lang key="shop.product.var_combinations_hint"}</p>
      <div class="var-matrix-wrap">
        <table class="table var-matrix-table" data-var-matrix-table>
          <thead data-var-matrix-thead></thead>
          <tbody data-var-matrix-tbody></tbody>
        </table>
      </div>
    </div>

    <input type="hidden" name="options_json" id="product-options-json" value='{row.options}'>
    <input type="hidden" name="variations_json" id="product-variations-json" value='{row.variations}'>
    <input type="hidden" id="var-image-picker">
  </section>

  [if {attributes}]
  <section class="tabs-pane" data-pane="attributes">
    <div class="hint-card hint-card-green">
      <div class="hint-h">{icon name="sliders" size="16"} {lang key="shop.product.hint_attr_title"}</div>
      <p>{lang key="shop.product.hint_attr_p1"}</p>
      <p class="muted">{lang key="shop.product.hint_attr_p2"}</p>
      <p class="hint-vs muted">{lang key="shop.product.hint_attr_p3_html"}</p>
    </div>

    <div class="attr-list">
      [foreach var="attributes" as="a"]
        <div class="attr-row">
          <label class="attr-label">
            <span class="attr-title">{a.title}[if {a.unit}], {a.unit}[/if]</span>
            [if {a.is_filterable}]<span class="attr-flag">{icon name="filter" size="11"} {lang key="shop.product.in_filters_chip"}</span>[/if]
          </label>

          [if {a.type}="text"]
            <input type="text" name="attr[{a.id}]" value="{a.value}">
          [/if]
          [if {a.type}="number"]
            <input type="number" step="any" name="attr[{a.id}]" value="{a.value}">
          [/if]
          [if {a.type}="boolean"]
            <label class="checkbox"><input type="checkbox" name="attr[{a.id}]" value="1" [if {a.checked}]checked[/if]> {lang key="shop.product.bool_yes"}</label>
          [/if]
          [if {a.type}="select"]
            <select name="attr[{a.id}]">
              <option value="">{lang key="shop.product.option_unspecified"}</option>
              [foreach var="a.options_decorated" as="opt"]
                <option value="{opt.value}" [if {opt.selected}]selected[/if]>{opt.value}</option>
              [/foreach]
            </select>
          [/if]
          [if {a.type}="multiselect"]
            <div class="attr-multi">
              [foreach var="a.options_decorated" as="opt"]
                <label class="attr-chip">
                  <input type="checkbox" name="attr[{a.id}][]" value="{opt.value}" [if {opt.selected}]checked[/if]>
                  {opt.value}
                </label>
              [/foreach]
            </div>
          [/if]
          [if {a.type}="color"]
            <select name="attr[{a.id}]">
              <option value="">{lang key="shop.product.option_unspecified"}</option>
              [foreach var="a.options_decorated" as="opt"]
                <option value="{opt.value}" [if {opt.selected}]selected[/if]>{opt.value}</option>
              [/foreach]
            </select>
          [/if]
        </div>
      [/foreach]
    </div>
  </section>
  [/if]

  <section class="tabs-pane" data-pane="seo">
    <div style="margin-bottom:16px">
      <button type="button" class="ai-btn" data-ai-task="generate_meta" data-ai-args-from='{"title":"[name=title]","content":"[name=body]"}'>{lang key="shop.product.fill_seo_ai"}</button>
    </div>
    <div class="form-group"><label>SEO Title</label><input type="text" name="seo_title" value="{row.seo_title}"></div>
    <div class="form-group"><label>SEO Description</label><textarea name="seo_description" rows="2">{row.seo_description}</textarea></div>
  </section>

  [if {custom_fields}]
  <section class="tabs-pane" data-pane="fields">
    {include file="_partials/custom_fields.tpl"}
  </section>
  [/if]

  <div class="form-actions">
    <button class="btn btn-primary" type="submit">{lang key="shop.common.save"}</button>
    <a class="btn btn-secondary" href="/admin/shop/products">{lang key="shop.common.cancel"}</a>
  </div>
</form>

<script>
(function () {
  // Tabs
  var tabs = document.querySelectorAll('.form-tabs .tabs-btn');
  var panes = document.querySelectorAll('.form-tabs .tabs-pane');
  tabs.forEach(function (btn) {
    btn.addEventListener('click', function () {
      var target = btn.getAttribute('data-tab');
      tabs.forEach(function (t) { t.classList.toggle('active', t === btn); });
      panes.forEach(function (p) { p.classList.toggle('active', p.getAttribute('data-pane') === target); });
    });
  });

  // ============================================================
  // Единая галерея товара: первое фото — главное (cover).
  // Поддерживается drag-reorder, удаление, «сделать главным», добавление.
  // ============================================================
  (function () {
    var coverInput = document.getElementById('product-cover');
    var imagesInput = document.getElementById('product-images');
    var picker = document.getElementById('product-images-picker');
    var grid = document.getElementById('product-gallery');
    if (!grid) return;

    function parseList() {
      var raw = (imagesInput.value || '').trim();
      var list = [];
      if (raw && raw !== 'null') {
        try { var arr = JSON.parse(raw); if (Array.isArray(arr)) list = arr.filter(Boolean); }
        catch (e) {}
      }
      // Старые товары: cover хранился отдельно. Если он не входит в images —
      // ставим его первым, чтобы единый список покрывал и обложку, и галерею.
      var cv = (coverInput.value || '').trim();
      if (cv && list.indexOf(cv) === -1) list.unshift(cv);
      return list;
    }

    function save(list) {
      imagesInput.value = JSON.stringify(list);
      coverInput.value  = list.length > 0 ? list[0] : '';
    }

    function tile(url, isMain) {
      var t = document.createElement('div');
      t.className = 'pg-tile' + (isMain ? ' is-main' : '');
      t.setAttribute('data-url', url);
      t.innerHTML =
        '<div class="pg-handle" title="{lang key="shop.attribute.drag_title"}">⋮⋮</div>' +
        (isMain ? '<div class="pg-badge">{lang key="shop.product.image_main_short"}</div>' : '') +
        '<img src="' + url + '" alt="" loading="lazy">' +
        '<div class="pg-actions">' +
          (isMain ? '' : '<button type="button" class="pg-btn" data-make-main title="{lang key="shop.product.image_make_main_title"}">' +
            '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>' +
          '</button>') +
          '<button type="button" class="pg-btn pg-btn-danger" data-del title="{lang key="shop.product.image_delete_title"}">' +
            '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18M6 6l12 12"/></svg>' +
          '</button>' +
        '</div>';
      return t;
    }

    function addBtn() {
      var b = document.createElement('button');
      b.type = 'button';
      b.className = 'pg-tile pg-add';
      b.id = 'pg-add-btn';
      b.setAttribute('data-media-picker', '#product-images-picker');
      b.setAttribute('data-media-multi', '1');
      b.innerHTML =
        '<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14M5 12h14"/></svg>' +
        '<span>{lang key="shop.product.image_add_short"}</span>';
      return b;
    }

    function render() {
      var list = parseList();
      grid.innerHTML = '';
      list.forEach(function (url, i) {
        grid.appendChild(tile(url, i === 0));
      });
      grid.appendChild(addBtn());
    }

    // Делегирование кликов по плиткам.
    grid.addEventListener('click', function (e) {
      var del = e.target.closest('[data-del]');
      var main = e.target.closest('[data-make-main]');
      if (!del && !main) return;
      var t = e.target.closest('.pg-tile');
      if (!t) return;
      var url = t.getAttribute('data-url');
      var list = parseList();
      var idx = list.indexOf(url);
      if (idx === -1) return;

      if (del) {
        list.splice(idx, 1);
      } else if (main) {
        // Поднимаем выбранный url в начало списка.
        list.splice(idx, 1);
        list.unshift(url);
      }
      save(list);
      render();
      bindSortable();
    });

    // Multi-picker → добавляем выбранные URL в конец, не дублируя.
    grid.addEventListener('celena:media-picked', function (e) {
      var urls = e.detail || [];
      if (!urls.length) return;
      var list = parseList();
      urls.forEach(function (u) { if (list.indexOf(u) === -1) list.push(u); });
      save(list);
      render();
      bindSortable();
    });

    // Drag-reorder: первый элемент после перестановки — новое главное фото.
    var sortableBound = false;
    function bindSortable() {
      if (typeof window.celenaSortable !== 'function') {
        setTimeout(bindSortable, 60);
        return;
      }
      // celenaSortable вешается один раз на контейнер — следит за DOM-перестановками.
      if (sortableBound) return;
      sortableBound = true;
      window.celenaSortable(grid, {
        handle: '.pg-handle',
        itemSelector: '.pg-tile:not(.pg-add)',
        onEnd: function () {
          var urls = [];
          grid.querySelectorAll('.pg-tile:not(.pg-add)').forEach(function (t) {
            var u = t.getAttribute('data-url');
            if (u) urls.push(u);
          });
          save(urls);
          render();
        }
      });
    }

    render();
    bindSortable();
  })();

  // ============================================================
  // Variations editor
  // ============================================================
  var optsHidden = document.getElementById('product-options-json');
  var varsHidden = document.getElementById('product-variations-json');
  var optsList = document.querySelector('[data-var-options-list]');
  var btnAddOpt = document.querySelector('[data-var-options-add]');
  var btnRegen = document.querySelector('[data-var-regen]');
  var matrixThead = document.querySelector('[data-var-matrix-thead]');
  var matrixTbody = document.querySelector('[data-var-matrix-tbody]');

  function parseJsonAttr(el) {
    try {
      var raw = (el.value || '').trim();
      if (!raw || raw === 'null') return [];
      var p = JSON.parse(raw);
      return Array.isArray(p) ? p : [];
    } catch (e) { return []; }
  }
  var options = parseJsonAttr(optsHidden);     // [{name, values:[]}]
  var variations = parseJsonAttr(varsHidden);  // [{id, values:[], price, old_price, stock, sku, image}]

  function saveAll() {
    optsHidden.value = JSON.stringify(options);
    varsHidden.value = JSON.stringify(variations);
  }

  // ---------- Опции ----------
  function renderOptions() {
    optsList.innerHTML = '';
    options.forEach(function (opt, i) {
      var card = document.createElement('div');
      card.className = 'var-opt-card';
      card.innerHTML =
        '<div class="var-opt-head">' +
          '<input type="text" class="var-opt-name" placeholder="{lang key="shop.product.var_option_name_placeholder"}" value="' + escapeAttr(opt.name) + '">' +
          '<button type="button" class="var-opt-del" title="{lang key="shop.product.var_delete_option"}">×</button>' +
        '</div>' +
        '<div class="var-opt-values"></div>' +
        '<button type="button" class="btn btn-secondary var-opt-add-val">{lang key="shop.product.var_add_value"}</button>';
      var nameInput = card.querySelector('.var-opt-name');
      nameInput.addEventListener('input', function () { opt.name = nameInput.value; saveAll(); });
      card.querySelector('.var-opt-del').addEventListener('click', function () {
        options.splice(i, 1); saveAll(); renderOptions();
      });
      var valsBox = card.querySelector('.var-opt-values');
      function renderVals() {
        valsBox.innerHTML = '';
        opt.values.forEach(function (v, j) {
          var row = document.createElement('div');
          row.className = 'var-opt-value';
          row.innerHTML = '<input type="text" placeholder="{lang key="shop.product.var_option_value_placeholder"}" value="' + escapeAttr(v) + '">' +
            '<button type="button" title="Удалить">×</button>';
          var inp = row.querySelector('input');
          inp.addEventListener('input', function () { opt.values[j] = inp.value; saveAll(); });
          row.querySelector('button').addEventListener('click', function () {
            opt.values.splice(j, 1); saveAll(); renderVals();
          });
          valsBox.appendChild(row);
        });
      }
      renderVals();
      card.querySelector('.var-opt-add-val').addEventListener('click', function () {
        opt.values.push(''); saveAll(); renderVals();
      });
      optsList.appendChild(card);
    });
  }
  btnAddOpt.addEventListener('click', function () {
    options.push({ name: '', values: [''] }); saveAll(); renderOptions();
  });

  // ---------- Матрица вариаций ----------
  function escapeAttr(s) { return String(s == null ? '' : s).replace(/"/g, '&quot;'); }

  function combinations(opts) {
    // Декартово произведение values каждой опции. Пустые значения — фильтруем.
    var clean = opts.map(function (o) { return (o.values || []).filter(function (v) { return String(v).trim() !== ''; }); });
    if (clean.length === 0 || clean.some(function (v) { return v.length === 0; })) return [];
    var out = [[]];
    clean.forEach(function (vals) {
      var next = [];
      out.forEach(function (prefix) {
        vals.forEach(function (v) { next.push(prefix.concat([v])); });
      });
      out = next;
    });
    return out;
  }

  function regenerate() {
    var combos = combinations(options);
    var byKey = {};
    variations.forEach(function (v) { byKey[(v.values || []).join('||')] = v; });
    var nextId = 1;
    var fresh = combos.map(function (c) {
      var key = c.join('||');
      if (byKey[key]) return byKey[key];
      return { id: nextId++, values: c, price: 0, old_price: 0, stock: 0, sku: '', image: '' };
    });
    // Назначаем уникальные id заново для безопасности
    fresh.forEach(function (v, i) { v.id = i + 1; });
    variations = fresh;
    saveAll();
    renderMatrix();
  }
  btnRegen.addEventListener('click', regenerate);

  function renderMatrix() {
    if (!options.length || !variations.length) {
      matrixThead.innerHTML = '';
      matrixTbody.innerHTML = '<tr><td class="muted" style="padding:14px">{lang key="shop.product.var_first_step"}</td></tr>';
      return;
    }
    var head = '<tr>';
    options.forEach(function (o) { head += '<th>' + escapeAttr(o.name || '{lang key="shop.product.var_option_default"}') + '</th>'; });
    head += '<th>{lang key="shop.product.price"}</th><th>{lang key="shop.product.var_old_price"}</th><th>{lang key="shop.product.stock"}</th><th>{lang key="shop.product.var_sku"}</th><th>{lang key="shop.product.var_photo"}</th>';
    head += '</tr>';
    matrixThead.innerHTML = head;

    matrixTbody.innerHTML = '';
    variations.forEach(function (v, idx) {
      var tr = document.createElement('tr');
      var html = '';
      v.values.forEach(function (val) { html += '<td><span class="cat-chip">' + escapeAttr(val) + '</span></td>'; });
      html += '<td><input type="number" step="0.01" min="0" data-var-field="price" value="' + escapeAttr(v.price) + '"></td>';
      html += '<td><input type="number" step="0.01" min="0" data-var-field="old_price" value="' + escapeAttr(v.old_price) + '"></td>';
      html += '<td><input type="number" step="1" min="0" data-var-field="stock" value="' + escapeAttr(v.stock) + '"></td>';
      html += '<td><input type="text" data-var-field="sku" value="' + escapeAttr(v.sku) + '"></td>';
      html += '<td>' +
        '<div class="var-image-cell">' +
          (v.image ? '<img src="' + escapeAttr(v.image) + '" alt="">' : '<span class="muted">—</span>') +
        '</div>' +
        '<button type="button" class="btn btn-secondary" data-var-pick-image>{lang key="shop.product.var_pick_image"}</button>' +
        (v.image ? '<button type="button" class="btn btn-secondary" data-var-clear-image>×</button>' : '') +
        '</td>';
      tr.innerHTML = html;
      tr.querySelectorAll('input[data-var-field]').forEach(function (inp) {
        var field = inp.getAttribute('data-var-field');
        inp.addEventListener('input', function () {
          v[field] = (field === 'sku') ? inp.value : parseFloat(inp.value || 0) || 0;
          if (field === 'stock') v[field] = parseInt(inp.value || 0, 10) || 0;
          saveAll();
        });
      });
      var pickBtn = tr.querySelector('[data-var-pick-image]');
      var clearBtn = tr.querySelector('[data-var-clear-image]');
      pickBtn.addEventListener('click', function () {
        var picker = document.getElementById('var-image-picker');
        // Слушатель — только для этой строки
        function handler(e) {
          var url = (e.detail || [''])[0];
          if (url) { v.image = url; saveAll(); renderMatrix(); }
          picker.removeEventListener('celena:media-picked', handler);
        }
        // Привязываем к временной кнопке media-picker
        var temp = document.createElement('button');
        temp.style.display = 'none';
        temp.setAttribute('data-media-picker', '#var-image-picker');
        temp.setAttribute('data-media-preview', '');
        document.body.appendChild(temp);
        temp.addEventListener('celena:media-picked', function (e) {
          var url = (e.detail || [picker.value])[0] || picker.value;
          if (url) { v.image = url; saveAll(); renderMatrix(); }
          temp.remove();
        });
        // Прямой запуск media-picker через клик
        temp.click();
        // Также — fallback через input value (если media-picker сетит value)
        var observer = setInterval(function () {
          if (picker.value) {
            v.image = picker.value;
            picker.value = '';
            saveAll();
            renderMatrix();
            clearInterval(observer);
          }
        }, 300);
        setTimeout(function () { clearInterval(observer); }, 30000);
      });
      if (clearBtn) {
        clearBtn.addEventListener('click', function () {
          v.image = ''; saveAll(); renderMatrix();
        });
      }
      matrixTbody.appendChild(tr);
    });
  }

  renderOptions();
  renderMatrix();
})();
</script>

<style>
/* Галерея фото товара: первое фото большое (2×2), остальные — обычные плитки.
   Добавление, drag, «сделать главным», удаление — всё через JS в этом же шаблоне. */
.pg-grid {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  grid-auto-rows: 130px;
  gap: 10px;
  margin: 12px 0;
}
.pg-tile {
  position: relative;
  border: 1px solid var(--border);
  border-radius: 10px;
  overflow: hidden;
  background: var(--surface-2);
  font-family: inherit;
  cursor: default;
}
/* Первый ребёнок (главное фото) занимает 2×2 — большая плитка, как на скриншоте. */
.pg-tile:first-child {
  grid-column: span 2;
  grid-row: span 2;
}
.pg-tile img {
  width: 100%; height: 100%;
  object-fit: cover;
  display: block;
}
.pg-tile.is-main { border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }

.pg-handle {
  position: absolute;
  left: 6px; top: 6px;
  width: 28px; height: 28px;
  display: flex; align-items: center; justify-content: center;
  background: rgba(255,255,255,0.92);
  border-radius: 50%;
  cursor: grab;
  font-size: 14px;
  color: #333;
  user-select: none;
  z-index: 2;
  box-shadow: 0 1px 4px rgba(0,0,0,0.2);
  opacity: 0; transition: opacity .15s;
}
.pg-tile:hover .pg-handle,
.pg-tile.is-dragging .pg-handle { opacity: 1; }
.pg-handle:active { cursor: grabbing; }

.pg-badge {
  position: absolute;
  left: 8px; bottom: 8px;
  background: var(--accent);
  color: #fff;
  font-size: 11px;
  font-weight: 600;
  padding: 3px 8px;
  border-radius: 4px;
  z-index: 2;
}

.pg-actions {
  position: absolute;
  right: 6px; top: 6px;
  display: flex; gap: 4px;
  z-index: 2;
  opacity: 0; transition: opacity .15s;
}
.pg-tile:hover .pg-actions { opacity: 1; }
.pg-btn {
  width: 28px; height: 28px;
  border: 0;
  border-radius: 50%;
  background: rgba(255,255,255,0.92);
  color: #333;
  cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  box-shadow: 0 1px 4px rgba(0,0,0,0.2);
  transition: background .15s, color .15s;
}
.pg-btn:hover { background: var(--accent); color: #fff; }
.pg-btn-danger:hover { background: #dc2626; color: #fff; }

.pg-tile.is-dragging { opacity: 0.5; transform: scale(0.98); }

/* Кнопка «Добавить фото» — пунктирная плитка того же размера, что и обычные. */
.pg-add {
  display: flex; flex-direction: column;
  align-items: center; justify-content: center; gap: 6px;
  border: 2px dashed var(--border);
  background: transparent;
  color: var(--text-muted);
  cursor: pointer;
  font-size: 12px;
  text-align: center;
  padding: 12px;
  transition: border-color .15s, color .15s, background .15s;
}
.pg-add:hover {
  border-color: var(--accent);
  color: var(--accent);
  background: var(--accent-soft);
}

@media (max-width: 800px) {
  .pg-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); grid-auto-rows: 100px; }
}
</style>

{include file="_partials/foot.tpl"}
