import { openModal, escapeHtml } from './modal.js';

// 다중 이미지(images jsonb) 우선, 레거시 단일 image_url fallback
function pickImages(p) {
  const arr = Array.isArray(p.images) ? p.images.filter(Boolean) : [];
  if (arr.length) return arr;
  if (p.image_url) return [p.image_url];
  return [];
}

export function renderProducts(products) {
  const root = document.getElementById('product-grid');
  if (!root) return;
  if (!products.length) {
    root.innerHTML = `<div style="grid-column:1/-1;text-align:center;color:var(--text-muted);padding:40px;">등록된 제품이 없습니다.</div>`;
    return;
  }

  root.innerHTML = products.map(p => {
    const imgs = pickImages(p);
    const main = imgs[0] || '';
    return `
    <div class="product-card" data-id="${p.id}">
      <div class="image" data-has-image="${main ? 1 : 0}" data-label="${escapeHtml(extractLabel(p.name))}" style="${main ? `background-image:url('${escapeHtml(main)}')` : ''}"></div>
      <div class="body">
        <div class="name">${escapeHtml(p.name)}</div>
        ${p.description ? `<div class="desc">${escapeHtml(p.description)}</div>` : ''}
        <div class="price">${formatPrice(p.price)}</div>
      </div>
    </div>`;
  }).join('');

  root.addEventListener('click', (e) => {
    const card = e.target.closest('.product-card');
    if (!card) return;
    const id = Number(card.dataset.id);
    const p = products.find(x => x.id === id);
    if (!p) return;
    openProduct(p);
  });
}

function openProduct(p) {
  const imgs = pickImages(p);
  const main = imgs[0] || '';
  const galleryHtml = imgs.length > 1
    ? `<div class="product-gallery" style="display:flex;gap:6px;overflow-x:auto;margin:0 0 16px;padding-bottom:4px;">${imgs.map((u, i) => `<button type="button" data-idx="${i}" class="thumb" style="flex:0 0 auto;width:64px;height:64px;border-radius:6px;border:1px solid rgba(255,255,255,.15);background:url('${escapeHtml(u)}') center/cover no-repeat;cursor:pointer;padding:0;outline:none;${i===0 ? 'box-shadow:0 0 0 2px var(--neon-cyan);' : ''}"></button>`).join('')}</div>`
    : '';
  openModal(`
    <button class="close" data-modal-close>×</button>
    <div class="product-hero" style="${main ? `background-image:url('${escapeHtml(main)}');` : 'background:linear-gradient(135deg, #1a1a24, #0a0a14);'} background-size:cover;background-position:center;aspect-ratio:4/3;border-radius:8px;margin-bottom:12px;"></div>
    ${galleryHtml}
    <h3>${escapeHtml(p.name)}</h3>
    <div class="body">${escapeHtml(p.description || '')}</div>
    <div class="meta">
      <span style="font-family:var(--font-display);font-weight:900;font-size:24px;color:var(--neon-red);text-shadow:0 0 6px rgba(255,42,42,0.5);">${formatPrice(p.price)} ₩</span>
    </div>
  `);
  // 갤러리 썸네일 클릭 → hero 이미지 교체
  if (imgs.length > 1) {
    document.querySelectorAll('.product-gallery .thumb').forEach(btn => {
      btn.addEventListener('click', () => {
        const idx = Number(btn.dataset.idx);
        const hero = document.querySelector('.product-hero');
        if (hero) hero.style.backgroundImage = `url('${imgs[idx]}')`;
        document.querySelectorAll('.product-gallery .thumb').forEach(b => b.style.boxShadow = '');
        btn.style.boxShadow = '0 0 0 2px var(--neon-cyan)';
      });
    });
  }
}

function formatPrice(n) {
  return Number(n || 0).toLocaleString('ko-KR');
}

function extractLabel(name) {
  // "TKTX 40%" → "40%", "TKTX 9개 박스" → "BOX", "만통롤라" → "ROLLA"
  const m = name.match(/(\d+%)/);
  if (m) return m[1];
  if (/박스|box/i.test(name)) return 'BOX';
  if (/롤라|rolla/i.test(name)) return 'ROLLA';
  return name.slice(0, 6).toUpperCase();
}
