/* Game1 entry point built with Webpack Encore */
import './styles/game1.css';

function subscribeToMercure(mercurePublicUrl, topic) {
  try {
    const url = mercurePublicUrl + '?topic=' + encodeURIComponent(topic);
    const es = new EventSource(url);

    es.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        console.log('[Mercure][game1] Update:', data);
      } catch (e) {
        console.log('[Mercure][game1] Raw event:', event.data);
      }
    };

    es.onerror = (err) => {
      console.warn('[Mercure][game1] EventSource error:', err);
    };

    console.log('[Mercure][game1] Subscribed to', url);
  } catch (e) {
    console.error('[Mercure][game1] Failed to subscribe:', e);
  }
}

async function fetchJson(url, options = {}) {
  const opts = { ...options };
  const headers = new Headers(opts.headers || {});
  headers.set('Accept', 'application/json');
  if (opts.body !== undefined && typeof opts.body !== 'string') {
    headers.set('Content-Type', 'application/json');
    opts.body = JSON.stringify(opts.body);
  }
  // Useful convention for server-side checks
  if (!headers.has('X-Requested-With')) {
    headers.set('X-Requested-With', 'XMLHttpRequest');
  }
  opts.headers = headers;
  const res = await fetch(url, opts);
  const text = await res.text();
  let data;
  try { data = text ? JSON.parse(text) : null; } catch (e) { data = text; }
  if (!res.ok) {
    const err = new Error('HTTP ' + res.status + ' ' + res.statusText);
    console.error('[API][game1]', err, data);
    throw err;
  }
  return data;
}

document.addEventListener('DOMContentLoaded', async () => {
  // Simple boot log so you can verify it in the browser console
  // and confirm this specific bundle is loaded on the Game Hub page.
  console.log('Game1 bundle loaded');

  // Example: add a CSS class to <body> so page-specific styles can apply
  document.body.classList.add('game1-page');

  // Look for config injected by Twig in the page
  const cfgEl = document.getElementById('mercure-config');
  if (!cfgEl) {
    console.warn('[Mercure][game1] #mercure-config element not found on page');
    return;
  }

  const mercurePublicUrl = cfgEl.dataset.mercurePublicUrl;
  const topic = cfgEl.dataset.topic;
  const apiPingUrl = cfgEl.dataset.apiPingUrl;
  const apiEchoUrl = cfgEl.dataset.apiEchoUrl;
  const userId = cfgEl.dataset.userId;

  if (mercurePublicUrl && topic) {
    subscribeToMercure(mercurePublicUrl, topic);
  } else {
    console.warn('[Mercure][game1] Missing data attributes on #mercure-config');
  }

  // Demo API calls
  try {
    if (apiPingUrl) {
      const ping = await fetchJson(apiPingUrl);
      console.log('[API][game1] ping →', ping);
    } else {
      console.warn('[API][game1] data-api-ping-url missing');
    }

    if (apiEchoUrl) {
      const echo = await fetchJson(apiEchoUrl, {
        method: 'POST',
        body: { message: 'from game1.js', ts: new Date().toISOString(), user: userId },
      });
      console.log('[API][game1] echo →', echo);
    } else {
      console.warn('[API][game1] data-api-echo-url missing');
    }
  } catch (e) {
    console.error('[API][game1] Request failed:', e);
  }
});
