// Yellow Stone Traders & General Supplies — pulls admin-managed content
// (projects, insights, press, events) from the API into the matching grids
// on projects.html / insights.html / index.html. Fails silently if the API
// is unreachable so pages still work as static files.
(function () {
  function escapeHtml(str) {
    return String(str ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
  }

  const GENERIC_ICON = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 21h18M6 21V10l6-4 6 4v11M10 21v-5h4v5"/></svg>`;

  function storyCardHTML(item, badgeText) {
    const tone = item.tone || 'tone-gold';
    return `<article class="story-card reveal in">
      <div class="story-media">
        <div class="photo-tile ${escapeHtml(tone)}">${GENERIC_ICON}</div>
        <span class="story-badge">${escapeHtml(badgeText)}</span>
      </div>
      <div class="story-body">
        <h3>${escapeHtml(item.title)}</h3>
        <p>${escapeHtml(item.excerpt)}</p>
        <a href="${item.link ? escapeHtml(item.link) : '#'}" class="story-link">Read more \u2192</a>
      </div>
    </article>`;
  }

  function append(selector, html) {
    const target = document.querySelector(selector);
    if (target) target.insertAdjacentHTML('beforeend', html);
  }

  function clearEmptyNote(selector) {
    const target = document.querySelector(selector);
    if (target) {
      const note = target.parentElement.querySelector('.empty-note');
      if (note) note.style.display = 'none';
    }
  }

  async function fetchJSON(url) {
    try {
      const resp = await fetch(url);
      if (!resp.ok) return [];
      return await resp.json();
    } catch (e) {
      return [];
    }
  }

  // ---- Projects page (backed by the "stories" table) ----
  async function loadProjects() {
    if (!document.querySelector('#panel-all')) return;
    const rows = await fetchJSON('/api/stories');
    rows.forEach((item) => {
      const badge = item.category ? item.category.charAt(0).toUpperCase() + item.category.slice(1) : 'Project';
      const html = storyCardHTML(item, badge);
      append('#panel-all .story-grid', html);
      clearEmptyNote('#panel-all .story-grid');
      const catSelector = `#panel-${item.category} .story-grid`;
      if (document.querySelector(catSelector)) {
        append(catSelector, html);
        clearEmptyNote(catSelector);
      }
    });
  }

  // ---- Insights page ----
  async function loadInsights() {
    if (!document.querySelector('#panel-publications')) return;
    const rows = await fetchJSON('/api/insights');
    rows.forEach((item) => {
      const html = storyCardHTML(item, item.badge || 'Update');
      const selector = `#panel-${item.tab} .story-grid`;
      if (document.querySelector(selector)) {
        append(selector, html);
        clearEmptyNote(selector);
      }
    });
  }

  // ---- Insights page: press ----
  async function loadPress() {
    if (!document.querySelector('#panel-press')) return;
    const rows = await fetchJSON('/api/press');
    rows.forEach((item) => {
      append('#panel-press .story-grid', storyCardHTML(item, item.badge || 'Press Release'));
      clearEmptyNote('#panel-press .story-grid');
    });
  }

  // ---- Home / Media: photo gallery ----
  function galleryTileHTML(item) {
    const inner = item.url
      ? (item.media_type === 'video'
          ? `<video src="${escapeHtml(item.url)}" muted loop playsinline preload="metadata"></video>`
          : `<img src="${escapeHtml(item.url)}" alt="${escapeHtml(item.title || '')}" loading="lazy">`)
      : `<div class="photo-tile tone-gold">${GENERIC_ICON}</div>`;
    return `<div class="story-media gallery-tile" style="border-radius:var(--radius); aspect-ratio:4/3;" title="${escapeHtml(item.caption || item.title || '')}">${inner}</div>`;
  }

  async function loadGallery() {
    const panel = document.querySelector('[data-gallery]');
    if (!panel) return;
    const rows = await fetchJSON('/api/media?category=gallery');
    const galleryRows = rows.filter((m) => (m.category || 'gallery') === 'gallery' && m.url);
    if (!galleryRows.length) return; // keep static placeholder tiles if nothing uploaded yet
    panel.innerHTML = galleryRows.map(galleryTileHTML).join('');
  }

  // ---- Upcoming site visits / tenders / events ----
  async function loadEvents() {
    const panel = document.querySelector('[data-events]');
    if (!panel) return;
    const rows = await fetchJSON('/api/events');
    if (!rows.length) return;
    const emptyNote = panel.querySelector('.empty-note');
    if (emptyNote) emptyNote.style.display = 'none';
    rows.forEach((ev) => {
      const d = new Date(ev.event_date);
      const month = isNaN(d) ? '' : d.toLocaleDateString(undefined, { month: 'short' }).toUpperCase();
      const day = isNaN(d) ? '' : d.getDate();
      panel.insertAdjacentHTML('beforeend', `
        <div class="pillar" style="display:flex; gap:18px; align-items:flex-start;">
          <span class="num" style="font-family:var(--font-display); font-size:22px; color:var(--gold); min-width:44px;">${month}<br>${day}</span>
          <div><h4 style="margin:0;">${escapeHtml(ev.title)}</h4><p style="margin-top:6px;">${escapeHtml(ev.description)}</p></div>
        </div>`);
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    loadProjects();
    loadInsights();
    loadPress();
    loadGallery();
    loadEvents();
  });
})();
