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

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

function noticeItemHTML(n) {
  return `
    <li class="notice-item ${n.pinned ? 'is-pinned' : ''}" data-id="${n.id}">
      <span class="title">${escapeHtml(n.title)}</span>
      <span class="date">${formatDate(n.created_at)}</span>
    </li>
  `;
}

function renderNoticeMore() {
  const wrap = document.getElementById('notice-more-wrap');
  if (!wrap) return;
  const remaining = _noticesAll.length - _noticesShown;
  if (remaining <= 0) { wrap.innerHTML = ''; return; }
  wrap.innerHTML = `
    <button class="notice-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, NOTICE_PAGE)} / 남은 ${remaining}건)
    </button>
  `;
  wrap.querySelector('.notice-more').addEventListener('click', () => appendNotices());
}

function appendNotices() {
  const root = document.getElementById('notice-list');
  if (!root) return;
  const slice = _noticesAll.slice(_noticesShown, _noticesShown + NOTICE_PAGE);
  _noticesShown += slice.length;
  root.insertAdjacentHTML('beforeend', slice.map(noticeItemHTML).join(''));
  renderNoticeMore();
}

export function renderNotices(notices) {
  _noticesAll = notices;
  _noticesShown = 0;
  const root = document.getElementById('notice-list');
  if (!root) return;
  if (!notices.length) {
    root.innerHTML = `<li class="notice-item"><span class="title">등록된 공지가 없습니다.</span></li>`;
    const wrap = document.getElementById('notice-more-wrap');
    if (wrap) wrap.innerHTML = '';
    return;
  }
  root.innerHTML = '';
  appendNotices();

  if (!root.dataset.boundClick) {
    root.dataset.boundClick = '1';
    root.addEventListener('click', (e) => {
      const item = e.target.closest('.notice-item');
      if (!item) return;
      const id = Number(item.dataset.id);
      const n = _noticesAll.find(x => x.id === id);
      if (!n) return;
      openNotice(n);
    });
  }
}

function openNotice(n) {
  const ext = n.external_url ? `
    <a class="external-cta" href="${escapeHtml(n.external_url)}" target="_blank" rel="noopener" style="display:inline-block;margin-top:20px;padding:10px 18px;background:transparent;border:1px solid var(--neon-cyan);color:var(--neon-cyan);font-family:var(--font-display);font-weight:700;font-size:13px;letter-spacing:2px;text-transform:uppercase;">외부 링크 열기 ↗</a>
  ` : '';
  const imgs = Array.isArray(n.images) && n.images.length ? `
    <div class="notice-images" style="display:flex;gap:8px;flex-wrap:wrap;margin-top:16px;">
      ${n.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>
  ` : '';
  openModal(`
    <button class="close" data-modal-close>×</button>
    <h3>${escapeHtml(n.title)}</h3>
    <div class="body">${escapeHtml(n.body)}</div>
    ${imgs}
    ${ext}
    <div class="meta">
      <span>${n.pinned ? 'PINNED' : 'NOTICE'}</span>
      <span>${formatDate(n.created_at)}</span>
    </div>
  `);
}

function formatDate(iso) {
  if (!iso) return '';
  const d = new Date(iso);
  return `${d.getFullYear()}.${String(d.getMonth()+1).padStart(2,'0')}.${String(d.getDate()).padStart(2,'0')}`;
}
