<?php
$title  = h($event['name']);
$cart   = \App\Core\Cart::get();
$totals = \App\Core\Cart::totals();
$preco  = config('app.preco_foto');
$promoC = config('app.promo_compra');
$promoO = config('app.promo_oferta');
?>
<style>
/* Grid */
.g-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:2px;}
@media(min-width:540px){.g-grid{grid-template-columns:repeat(4,1fr);}}
@media(min-width:900px){.g-grid{grid-template-columns:repeat(5,1fr);}}
@media(min-width:1200px){.g-grid{grid-template-columns:repeat(6,1fr);}}

/* Célula */
.g-cell{position:relative;background:#000;}
.g-thumb{aspect-ratio:1;overflow:hidden;display:flex;align-items:center;justify-content:center;cursor:zoom-in;position:relative;}
.g-thumb img{width:100%;height:100%;object-fit:contain;display:block;transition:opacity .15s;}
.g-cell.selected .g-thumb img{opacity:.65;}

/* Hover */
.g-overlay{position:absolute;inset:0;background:rgba(0,0,0,0);display:flex;align-items:center;justify-content:center;transition:background .18s;pointer-events:none;z-index:5;}
.g-thumb:hover .g-overlay{background:rgba(0,0,0,.35);}
.g-overlay span{font-size:11px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:#fff;opacity:0;transition:opacity .18s;}
.g-thumb:hover .g-overlay span{opacity:1;}

/* Número */
.g-num{text-align:center;padding:3px 0;font-size:10px;color:#4b5563;background:#030712;user-select:none;}
.g-cell.selected .g-num{color:#6b7280;}

/* Checkbox */
.g-check{position:absolute;top:6px;right:6px;z-index:20;width:22px;height:22px;border-radius:5px;
  border:2px solid rgba(255,255,255,.6);background:rgba(0,0,0,.3);
  display:flex;align-items:center;justify-content:center;cursor:pointer;
  transition:all .12s;backdrop-filter:blur(3px);}
.g-check:hover{border-color:#fff;background:rgba(0,0,0,.55);}
.g-cell.selected .g-check{background:#6366f1;border-color:#6366f1;}
.g-check svg{opacity:0;transition:opacity .12s;}
.g-cell.selected .g-check svg{opacity:1;}

/* Qty */
.g-qty-ctrl{position:absolute;bottom:22px;left:50%;transform:translateX(-50%);
  display:none;align-items:center;background:rgba(0,0,0,.8);border-radius:999px;backdrop-filter:blur(4px);}
.g-cell.selected:hover .g-qty-ctrl{display:flex;}
.g-qty-ctrl button{width:28px;height:26px;background:none;border:none;color:#fff;font-size:16px;cursor:pointer;}
.g-qty-num{min-width:20px;text-align:center;font-size:12px;font-weight:700;color:#fff;}
.g-qty-badge{position:absolute;bottom:22px;right:5px;background:#6366f1;color:#fff;
  font-size:10px;font-weight:800;padding:1px 5px;border-radius:3px;}
.g-cell.selected:hover .g-qty-badge{display:none;}

/* Barra — mobile first */
.g-bar{position:fixed;bottom:0;left:0;right:0;z-index:50;
  background:rgba(17,24,39,.97);backdrop-filter:blur(16px);
  border-top:1px solid rgba(255,255,255,.08);
  padding:10px 14px;padding-bottom:calc(10px + env(safe-area-inset-bottom));}
.g-bar-in{max-width:1280px;margin:0 auto;display:flex;align-items:center;gap:10px;}
.g-bar-txt{flex:1;min-width:0;overflow:hidden;}
#bar-count{font-weight:700;font-size:14px;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
#bar-detail{font-size:11px;color:#6b7280;margin-top:1px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.g-bar-btn{background:#fff;color:#111827;font-weight:700;font-size:13px;
  padding:9px 16px;border-radius:9px;white-space:nowrap;flex-shrink:0;
  border:none;cursor:pointer;font-family:inherit;}

/* Notificação azul */
#bar-notif{display:none;position:fixed;bottom:calc(64px + env(safe-area-inset-bottom));
  left:50%;transform:translateX(-50%);z-index:51;
  background:#1d4ed8;color:#fff;padding:8px 18px;border-radius:999px;
  font-size:13px;font-weight:600;box-shadow:0 4px 20px rgba(29,78,216,.4);
  white-space:nowrap;pointer-events:none;}

/* Modal */
.g-modal{position:fixed;inset:0;z-index:100;background:rgba(0,0,0,.96);display:none;
           flex-direction:column;overflow:hidden;}
.g-modal.open{display:flex;}

/* Header do modal — responsivo */
.mh{display:flex;flex-direction:column;flex-shrink:0;background:rgba(0,0,0,.85);}
.mh-row1{display:flex;align-items:center;justify-content:space-between;
          padding:10px 14px 8px;gap:8px;}
.mh-row2{display:flex;align-items:center;justify-content:center;
          padding:8px 14px 12px;gap:8px;border-top:1px solid rgba(255,255,255,.08);}
.mh-left{display:flex;align-items:center;gap:8px;flex:1;min-width:0;}

/* Controlo de quantidade — pill simples */
.mh-qty{display:inline-flex;align-items:center;height:38px;
        background:rgba(255,255,255,.12);border-radius:19px;}
.mh-qty button{width:38px;height:38px;background:transparent;border:none;
               color:#fff;font-size:22px;cursor:pointer;font-family:inherit;
               display:flex;align-items:center;justify-content:center;
               border-radius:19px;flex-shrink:0;}
.mh-qty button:active{background:rgba(255,255,255,.15);}
#modal-qty{min-width:28px;text-align:center;font-size:15px;
           font-weight:700;color:#fff;line-height:1;user-select:none;}

/* Botões de acção */
#modal-sel-btn{height:38px;border:none;padding:0 18px;border-radius:9px;cursor:pointer;
               font-weight:700;font-size:14px;font-family:inherit;
               transition:background .2s,color .2s;white-space:nowrap;}
#modal-rem-btn{display:none;height:38px;align-items:center;border:none;
               padding:0 16px;border-radius:9px;cursor:pointer;
               font-weight:700;font-size:14px;font-family:inherit;white-space:nowrap;
               background:#dc2626;color:#fff;}
#modal-cart-link{display:none;height:38px;align-items:center;gap:5px;
                 background:#4f46e5;color:#fff;padding:0 16px;border-radius:9px;
                 font-weight:700;font-size:13px;border:none;cursor:pointer;
                 font-family:inherit;white-space:nowrap;}
</style>

<div style="padding-bottom:calc(70px + env(safe-area-inset-bottom));">

<!-- Header -->
<div style="background:rgba(255,255,255,.02);border-bottom:1px solid rgba(255,255,255,.06);padding:10px 16px;">
  <div style="max-width:1280px;margin:0 auto;display:flex;align-items:center;gap:8px;font-size:13px;">
    <a href="<?= base_url() ?>" style="color:#6b7280;transition:color .15s;"
       onmouseover="this.style.color='#fff'" onmouseout="this.style.color='#6b7280'">← Eventos</a>
    <span style="color:#374151;">/</span>
    <span style="color:#e5e7eb;font-weight:500;"><?= h($event['name']) ?></span>
    <span style="margin-left:auto;color:#4b5563;font-size:12px;"><?= $total ?> fotografias</span>
  </div>
</div>

<!-- Grid -->
<div class="g-grid" id="photo-grid" style="max-width:1280px;margin:0 auto;padding:2px;">
  <?php foreach($photos as $idx => $photo):
    $qty = $cart[$photo['id']] ?? 0;
    $num = ($idx+1) + (($page-1)*60);
  ?>
  <div class="g-cell <?= $qty>0?'selected':'' ?>"
       id="cell-<?= $photo['id'] ?>"
       data-id="<?= $photo['id'] ?>"
       data-prev="<?= imgurl('previews', $photo['event_id'], $photo['filename']) ?>"
       data-thumb="<?= imgurl('thumbnails', $photo['event_id'], $photo['filename']) ?>">

    <div class="g-thumb" data-action="modal" data-id="<?= $photo['id'] ?>">
      <img src="<?= imgurl('thumbnails', $photo['event_id'], $photo['filename']) ?>"
           alt="Foto <?= $num ?>" loading="<?= $idx < 12 ? 'eager' : 'lazy' ?>" decoding="async">
      <div class="g-overlay"><span>Ver foto</span></div>
    </div>

    <div class="g-num"><?= $num ?></div>

    <div class="g-check" data-action="select" data-id="<?= $photo['id'] ?>" title="Selecionar">
      <svg width="13" height="13" fill="none" stroke="#fff" stroke-width="3" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/>
      </svg>
    </div>

    <div class="g-qty-badge" id="qty-badge-<?= $photo['id'] ?>" <?= $qty<=0?'style="display:none"':'' ?>>×<?= $qty ?></div>

    <div class="g-qty-ctrl">
      <button data-action="dec" data-id="<?= $photo['id'] ?>">−</button>
      <span class="g-qty-num" id="qty-num-<?= $photo['id'] ?>"><?= $qty ?></span>
      <button data-action="inc" data-id="<?= $photo['id'] ?>">+</button>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<!-- Paginação -->
<?php if($pages>1): ?>
<div style="display:flex;justify-content:center;gap:5px;padding:28px 16px 0;">
  <?php for($i=1;$i<=$pages;$i++): ?>
  <a href="?p=<?= $i ?>" style="width:32px;height:32px;border-radius:8px;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:500;
     <?= $i===$page?'background:#fff;color:#111827;':'background:rgba(255,255,255,.08);color:#9ca3af;' ?>">
    <?= $i ?>
  </a>
  <?php endfor; ?>
</div>
<?php endif; ?>
</div>

<!-- Notificação azul -->
<div id="bar-notif"></div>

<!-- Barra carrinho -->
<div class="g-bar">
  <div class="g-bar-in">
    <div class="g-bar-txt">
      <div id="bar-count"><?= $totals['items'] ?> foto<?= $totals['items']!=1?'s':'' ?> selecionada<?= $totals['items']!=1?'s':'' ?></div>
      <div id="bar-detail">
        <?php if($totals['items']>0): ?>
          <?= $totals['pay'] ?> × <?= money($preco) ?> = <?= money($totals['subtotal']) ?>
          <?php if($totals['free']>0): ?> · <span style="color:#4ade80;font-weight:600;"><?= $totals['free'] ?> fotografia<?= $totals['free']!=1?'s':'' ?> grátis</span><?php endif; ?>
        <?php else: ?>
          Clica em ✓ para selecionar fotografias
        <?php endif; ?>
      </div>
    </div>
    <button id="modal-cart-btn" data-go-cart="1" type="button" class="g-bar-btn"
       style="<?= $totals['items']>0?'':'display:none' ?>">🛒 Carrinho</button>
  </div>
</div>

<!-- Modal -->
<div class="g-modal" id="modal">
  <div class="mh" data-stop-propagation="1">
    <!-- Linha 1: fechar + nº foto | botão carrinho -->
    <div class="mh-row1">
      <div class="mh-left">
        <button data-modal-action="close"
                style="background:rgba(255,255,255,.1);border:none;color:#fff;padding:7px 14px;
                       border-radius:8px;cursor:pointer;font-size:13px;font-family:inherit;white-space:nowrap;">✕ Fechar</button>
        <span id="modal-num" style="font-size:11px;color:#6b7280;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"></span>
      </div>
      <button id="modal-cart-link" data-go-cart="1" type="button">🛒 Carrinho</button>
    </div>
    <!-- Linha 2: quantidade + selecionar + remover -->
    <div class="mh-row2">
      <div class="mh-qty">
        <button data-modal-action="qty-dec">−</button>
        <span id="modal-qty">0</span>
        <button data-modal-action="qty-inc">+</button>
      </div>
      <button id="modal-sel-btn" data-modal-action="select">+ Selecionar</button>
      <button id="modal-rem-btn" data-modal-action="remove">× Remover</button>
    </div>
  </div>
  <div style="flex:1;overflow:hidden;display:flex;align-items:center;justify-content:center;position:relative;" data-modal-action="close">
    <button data-modal-action="prev"
            style="position:absolute;left:10px;background:rgba(255,255,255,.1);border:none;color:#fff;width:42px;height:42px;border-radius:50%;cursor:pointer;font-size:22px;z-index:10;display:flex;align-items:center;justify-content:center;">‹</button>
    <img id="modal-img" src="" alt=""
         style="max-width:100%;max-height:100%;object-fit:contain;display:block;" draggable="false"
         data-stop-propagation="1"
         onerror="this.src=document.getElementById('modal-fb').value">
    <input type="hidden" id="modal-fb" value="">
    <button data-modal-action="next"
            style="position:absolute;right:10px;background:rgba(255,255,255,.1);border:none;color:#fff;width:42px;height:42px;border-radius:50%;cursor:pointer;font-size:22px;z-index:10;display:flex;align-items:center;justify-content:center;">›</button>
  </div>
</div>

<script nonce="<?= nonce() ?>">
const CSRF = '<?= csrf_token() ?>', BASE = '<?= base_url() ?>', EID = <?= $event['id'] ?>;
const PRECO = <?= (float)$preco ?>, PROMO_C = <?= (int)$promoC ?>, PROMO_O = <?= (int)$promoO ?>;
const PAGE = <?= $page ?>, TOTAL = <?= $total ?>;
const CICLO = PROMO_C + PROMO_O; // 11 (10 pagas + 1 grátis)

// Cart com keys numéricas
const _cr = <?= json_encode(array_map('intval', $cart)) ?>;
let cart = {};
Object.keys(_cr).forEach(k => { cart[parseInt(k, 10)] = _cr[k]; });

const photoList = <?= json_encode(array_map(fn($p) => ['id' => (int)$p['id'], 'file' => $p['filename']], $photos)) ?>;

// ── Acções carrinho ─────────────────────────────────────
function toggleSelect(id) {
  id = parseInt(id, 10);
  if (cart[id]) setQty(id, 0);
  else { setQty(id, 1); showToast('✓ Fotografia adicionada'); }
}
function changeQty(id, delta) {
  id = parseInt(id, 10);
  const cur = cart[id] || 0, nxt = Math.max(0, cur + delta);
  if (nxt > cur && cur === 0) showToast('✓ Fotografia adicionada');
  setQty(id, nxt);
}
// Queue para garantir que o carrinho está sincronizado antes de navegar
let _syncQueue = Promise.resolve();
let _syncPending = 0;

async function setQty(id, qty) {
  const was = cart[id] || 0;
  if (qty === was) return;
  qty <= 0 ? delete cart[id] : (cart[id] = qty);
  renderCell(id); updateBar(); if (modalId === id) renderModalBtn();
  const action = qty <= 0 ? 'remove' : (was === 0 ? 'add' : 'update');
  const fd = new URLSearchParams({ _csrf: CSRF, photo_id: id, qty });
  _syncPending++;
  _syncQueue = _syncQueue.then(async () => {
    try {
      const r = await fetch(BASE + 'carrinho/' + action, {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        keepalive: true,
        body: fd
      });
      const d = await r.json();
      updateCartBadge(d.count);
    } catch(e) {
      // Reverter estado local se falhar
      qty <= 0 ? (cart[id] = was) : (was === 0 ? delete cart[id] : null);
      renderCell(id); updateBar(); if (modalId === id) renderModalBtn();
    } finally {
      _syncPending--;
    }
  });
  await _syncQueue;
}
function renderCell(id) {
  const cell = document.getElementById('cell-' + id);
  const badge = document.getElementById('qty-badge-' + id);
  const num   = document.getElementById('qty-num-' + id);
  const qty   = cart[id] || 0;
  if (!cell) return;
  cell.classList.toggle('selected', qty > 0);
  if (badge) { badge.textContent = '×' + qty; badge.style.display = qty > 0 ? 'block' : 'none'; }
  if (num) num.textContent = qty;
}

// ── Barra ───────────────────────────────────────────────
let promoShown = {};
function updateBar() {
  const total = Object.values(cart).reduce((a, b) => a + b, 0);
  // Promoção: paga PROMO_C (10), recebe PROMO_O (1) extra grátis
  // floor(11/11)=1 grátis; floor(22/11)=2 grátis
  const free = (CICLO > 0 && total > 0) ? Math.floor(total / CICLO) * PROMO_O : 0;
  const pay  = total - free;
  const sub  = pay * PRECO;

  const elC = document.getElementById('bar-count');
  const elD = document.getElementById('bar-detail');
  const elBtn = document.getElementById('modal-cart-btn');

  if (elC) elC.textContent = total + ' foto' + (total !== 1 ? 's' : '') + ' selecionada' + (total !== 1 ? 's' : '');
  if (elD) {
    if (total > 0) {
      let t = pay + ' × ' + PRECO.toFixed(2).replace('.', ',') + '€ = ' + sub.toFixed(2).replace('.', ',') + '€';
      if (free > 0) t += ' · <span style="color:#4ade80;font-weight:600;">' + free + ' fotografia' + (free !== 1 ? 's' : '') + ' grátis</span>';
      elD.innerHTML = t;
    } else {
      elD.textContent = 'Clica em ✓ para selecionar fotografias';
    }
  }
  if (elBtn) elBtn.style.display = total > 0 ? 'inline-flex' : 'none';

  // Botão carrinho dentro do modal
  const modalCart = document.getElementById('modal-cart-link');
  if (modalCart) modalCart.style.display = total > 0 ? 'inline-flex' : 'none';

  // Notificação azul: falta 1 para o próximo limiar (ex: aos 10, 21, 32...)
  if (PROMO_C > 0 && CICLO > 0 && total > 0 && total % CICLO === PROMO_C) {
    const k = 'n' + total;
    if (!promoShown[k]) { promoShown[k] = true; showBlueNotif('📸 Próxima fotografia grátis!'); }
  }
}
function showBlueNotif(msg) {
  const el = document.getElementById('bar-notif');
  if (!el) return;
  el.textContent = msg;
  el.style.display = 'block';
  clearTimeout(el._t);
  el._t = setTimeout(() => { el.style.display = 'none'; }, 4000);
}

// ── Modal ───────────────────────────────────────────────
let modalId = null;
function openModal(id) {
  modalId = parseInt(id, 10);
  const cell = document.getElementById('cell-' + modalId);
  document.getElementById('modal-fb').value  = cell?.dataset.thumb || '';
  document.getElementById('modal-img').src   = cell?.dataset.prev  || cell?.dataset.thumb || '';
  const idx = photoList.findIndex(p => p.id === modalId);
  document.getElementById('modal-num').textContent = 'Foto ' + (idx + 1 + (PAGE - 1) * 60) + ' de ' + TOTAL;
  renderModalBtn();
  document.getElementById('modal').classList.add('open');
  document.body.style.overflow = 'hidden';
}
function closeModal() {
  document.getElementById('modal').classList.remove('open');
  document.body.style.overflow = '';
  modalId = null;
}
function renderModalBtn() {
  const qty    = cart[modalId] || 0;
  const selBtn = document.getElementById('modal-sel-btn');
  const remBtn = document.getElementById('modal-rem-btn');
  const qtyEl  = document.getElementById('modal-qty');

  if (selBtn) {
    if (qty > 0) {
      selBtn.textContent      = '✓ Selecionada';
      selBtn.style.background = '#16a34a';
      selBtn.style.color      = '#fff';
    } else {
      selBtn.textContent      = '+ Selecionar';
      selBtn.style.background = '#fff';
      selBtn.style.color      = '#111827';
    }
  }

  // Mostrar/esconder botão Remover
  if (remBtn) remBtn.style.display = qty > 0 ? 'inline-flex' : 'none';

  if (qtyEl) qtyEl.textContent = qty;
}
function toggleFromModal() {
  if (!modalId) return;
  if (!cart[modalId]) { setQty(modalId, 1); showToast('✓ Fotografia adicionada'); }
}
function modalChangeQty(delta) {
  if (!modalId) return;
  const cur = cart[modalId] || 0, nxt = Math.max(0, cur + delta);
  if (nxt > cur && cur === 0) showToast('✓ Fotografia adicionada');
  setQty(modalId, nxt);
}
function modalNav(dir) {
  const idx  = photoList.findIndex(p => p.id === modalId);
  const next = photoList[(idx + dir + photoList.length) % photoList.length];
  if (next) openModal(next.id);
}

// Event delegation — substitui todos os onclick inline
document.getElementById('photo-grid')?.addEventListener('click', function(e) {
  const el = e.target.closest('[data-action]');
  if (!el) return;
  const action = el.dataset.action;
  const id     = parseInt(el.dataset.id || el.closest('[data-id]')?.dataset.id || '0', 10);
  if (!id) return;
  if (action === 'modal')  { openModal(id); }
  if (action === 'select') { e.stopPropagation(); toggleSelect(id); }
  if (action === 'dec')    { e.stopPropagation(); changeQty(id, -1); }
  if (action === 'inc')    { e.stopPropagation(); changeQty(id, +1); }
});

// Modal buttons via event listeners
document.getElementById('modal')?.querySelectorAll('[data-modal-action]').forEach(btn => {
  btn.addEventListener('click', e => {
    const a = btn.dataset.modalAction;
    if (a === 'close')    closeModal();
    if (a === 'prev')     modalNav(-1);
    if (a === 'next')     modalNav(1);
    if (a === 'select')   { if (!(cart[modalId])) toggleFromModal(); } // só adiciona
    if (a === 'remove')   { if (cart[modalId] > 0) { setQty(modalId, 0); showToast('Fotografia removida'); } }
    if (a === 'qty-dec')  modalChangeQty(-1);
    if (a === 'qty-inc')  modalChangeQty(1);
    e.stopPropagation();
  });
});

// Stop propagation via data attribute
document.querySelectorAll('[data-stop-propagation]').forEach(el => {
  el.addEventListener('click', e => e.stopPropagation());
});

// Delegação do fundo do modal
document.querySelectorAll('[data-modal-action="close"]').forEach(el => {
  el.addEventListener('click', closeModal);
});

// Interceptar botões do carrinho — aguardar sync antes de navegar
// Navegar para o carrinho — SEMPRE aguarda sincronização pendente
const CART_URL = '<?= base_url('carrinho') ?>';

async function goToCart(btn) {
  btn.disabled = true;
  const orig = btn.textContent;
  btn.textContent = '⏳';
  await _syncQueue;
  window.location.href = CART_URL;
}

// Listeners directos nos botões (event delegation não funciona dentro do modal por causa do stopPropagation)
function bindCartButtons() {
  ['modal-cart-btn', 'modal-cart-link'].forEach(id => {
    const el = document.getElementById(id);
    if (el) el.addEventListener('click', function(e) {
      e.preventDefault();
      e.stopPropagation();
      goToCart(this);
    });
  });
}
bindCartButtons();

// Swipe e teclado
let tx = 0;
const modal = document.getElementById('modal');
modal.addEventListener('touchstart', e => tx = e.touches[0].clientX, { passive: true });
modal.addEventListener('touchend',   e => { const dx = e.changedTouches[0].clientX - tx; if (Math.abs(dx) > 50) modalNav(dx < 0 ? 1 : -1); }, { passive: true });
document.addEventListener('keydown', e => {
  if (!modal.classList.contains('open')) return;
  if (e.key === 'Escape')     closeModal();
  if (e.key === 'ArrowLeft')  modalNav(-1);
  if (e.key === 'ArrowRight') modalNav(1);
});
</script>
