// PRE Web GUI — Shared state, utilities, and panel helpers
// Loaded before app.js and panel modules

window.PRE = (() => {
  // ── Shared utilities ──

  function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  function formatTime(isoString) {
    if (!isoString) return '';
    const d = new Date(isoString);
    const now = new Date();
    const diff = now - d;
    if (diff < 60000) return 'just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return d.toLocaleDateString();
  }

  function formatDuration(ms) {
    if (ms < 1000) return `${ms}ms`;
    if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
    if (ms < 3600000) return `${Math.floor(ms / 60000)}m ${Math.floor((ms % 60000) / 1000)}s`;
    return `${Math.floor(ms / 3600000)}h ${Math.floor((ms % 3600000) / 60000)}m`;
  }

  function timeAgo(ts) {
    if (!ts) return '';
    const diff = Date.now() - new Date(ts).getTime();
    if (diff < 60000) return 'just now';
    if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
    if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
    return `${Math.floor(diff / 86400000)}d ago`;
  }

  // ── Right panel helpers ──

  function openPanel(title, renderFn) {
    const panel = document.getElementById('right-panel');
    const titleEl = document.getElementById('panel-title');
    const content = document.getElementById('panel-content');
    titleEl.textContent = title;
    panel.classList.remove('hidden');
    content.innerHTML = '<div class="spinner" style="margin:20px auto"></div>';
    if (renderFn) renderFn(content);
    return content;
  }

  function closePanel() {
    document.getElementById('right-panel').classList.add('hidden');
  }

  // ── Shared state accessors ──
  // These are populated by app.js on boot. Panel modules call these
  // to interact with core app state without reaching into closures.

  const callbacks = {};

  function on(event, fn) {
    callbacks[event] = fn;
  }

  function emit(event, ...args) {
    if (callbacks[event]) return callbacks[event](...args);
  }

  return {
    escapeHtml,
    formatTime,
    formatDuration,
    timeAgo,
    openPanel,
    closePanel,
    // Event bus for cross-module communication
    on,
    emit,
  };
})();
