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

// 2026-04-29: 5칸까지 노출 + '더보기' (사용자 요청)
const QNA_PAGE = 5;
let _qnaAll = [];
let _qnaShown = 0;

function qnaItemHTML(q) {
  const imgs = Array.isArray(q.images) && q.images.length ? `
    <div class="qna-images" style="display:flex;gap:8px;flex-wrap:wrap;margin-top:14px;">
      ${q.images.map(u => `<img src="${escapeHtml(u)}" alt="" loading="lazy" style="max-width:100%;width:calc(50% - 4px);height:auto;border-radius:6px;border:1px solid var(--border-subtle);">`).join('')}
    </div>
  ` : '';
  return `
    <details class="qna-item">
      <summary>${escapeHtml(q.question)}</summary>
      <div class="answer">${escapeHtml(q.answer)}${imgs}${q.external_url ? `
        <div style="margin-top:16px;">
          <a class="external-cta" href="${escapeHtml(q.external_url)}" target="_blank" rel="noopener">${escapeHtml(q.external_label || '바로가기')}</a>
        </div>` : ''}</div>
    </details>
  `;
}

function renderQnaMore() {
  const wrap = document.getElementById('qna-more-wrap');
  if (!wrap) return;
  const remaining = _qnaAll.length - _qnaShown;
  if (remaining <= 0) { wrap.innerHTML = ''; return; }
  wrap.innerHTML = `
    <button class="qna-more" type="button" style="margin-top:18px;padding:10px 24px;background:transparent;border:1px solid var(--neon-amber);color:var(--neon-amber);font-family:var(--font-display);font-weight:700;letter-spacing:2px;text-transform:uppercase;cursor:pointer;">
      더보기 (+${Math.min(remaining, QNA_PAGE)} / 남은 ${remaining}건)
    </button>
  `;
  wrap.querySelector('.qna-more').addEventListener('click', () => appendQna());
}

function appendQna() {
  const root = document.getElementById('qna-list');
  if (!root) return;
  const slice = _qnaAll.slice(_qnaShown, _qnaShown + QNA_PAGE);
  _qnaShown += slice.length;
  root.insertAdjacentHTML('beforeend', slice.map(qnaItemHTML).join(''));
  renderQnaMore();
}

export function renderQnA(qna) {
  _qnaAll = qna;
  _qnaShown = 0;
  const root = document.getElementById('qna-list');
  if (!root) return;
  if (!qna.length) {
    root.innerHTML = `<div style="text-align:center;color:var(--text-muted);padding:40px;">등록된 QnA가 없습니다.</div>`;
    const wrap = document.getElementById('qna-more-wrap');
    if (wrap) wrap.innerHTML = '';
    return;
  }
  root.innerHTML = '';
  appendQna();
}
