/* Langfuse Lens — Common Utilities */

// Re-export i18n functions for convenience
export { t, getLocale, setLocale, applyTranslations } from './i18n.js';
import { t } from './i18n.js';

// --- Toast ---
export function toast(message, type = "info", duration = 3500) {
  const container = document.getElementById("toast-container");
  if (!container) return;
  const el = document.createElement("div");
  el.className = `toast toast-${type}`;
  el.textContent = message;
  container.appendChild(el);
  setTimeout(() => {
    el.style.opacity = "0";
    el.style.transform = "translateX(40px)";
    el.style.transition = "all 0.3s ease";
    setTimeout(() => el.remove(), 300);
  }, duration);
}

// --- Date formatting ---
export function formatDate(iso) {
  if (!iso) return "-";
  const d = new Date(iso);
  const pad = (n) => String(n).padStart(2, "0");
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}

export function timeAgo(iso) {
  if (!iso) return "-";
  const diff = Date.now() - new Date(iso).getTime();
  const s = Math.floor(diff / 1000);
  if (s < 60) return t('common.timeAgo.seconds', { n: s });
  const m = Math.floor(s / 60);
  if (m < 60) return t('common.timeAgo.minutes', { n: m });
  const h = Math.floor(m / 60);
  if (h < 24) return t('common.timeAgo.hours', { n: h });
  const d = Math.floor(h / 24);
  return t('common.timeAgo.days', { n: d });
}

// --- Status badges ---
export function statusBadge(status) {
  const map = {
    running: "badge-info",
    completed: "badge-success",
    cancelled: "badge-warning",
    failed: "badge-danger",
    pending: "badge-default",
    active: "badge-success",
    suspended: "badge-danger",
    set: "badge-success",
    missing: "badge-danger",
    healthy: "badge-success",
    degraded: "badge-warning",
    low: "badge-default",
    normal: "badge-info",
    high: "badge-warning",
  };
  const cls = map[status] || "badge-default";
  return `<span class="badge ${cls}">${escapeHtml(status)}</span>`;
}

// --- Escape HTML ---
export function escapeHtml(str) {
  if (str === null || str === undefined) return "";
  const s = String(str);
  const div = document.createElement("div");
  div.textContent = s;
  return div.innerHTML;
}

// --- Modal ---
export function openModal(title, bodyHtml) {
  const overlay = document.getElementById("modal-overlay");
  const titleEl = document.getElementById("modal-title");
  const bodyEl = document.getElementById("modal-body");
  if (!overlay || !titleEl || !bodyEl) return;
  titleEl.textContent = title;
  bodyEl.innerHTML = bodyHtml;
  overlay.hidden = false;
}

export function closeModal() {
  const overlay = document.getElementById("modal-overlay");
  if (overlay) overlay.hidden = true;
}

// --- Pagination HTML ---
export function paginationHtml(page, size, total) {
  const totalPages = Math.max(1, Math.ceil(total / size));
  return `
    <div class="pagination">
      <span class="pagination-info">${t('common.pageOf', { page, totalPages, total })}</span>
      <div class="pagination-buttons">
        <button class="btn-ghost btn-sm" data-page="${page - 1}" ${page <= 1 ? "disabled" : ""}>&laquo; ${t('common.prev')}</button>
        <button class="btn-ghost btn-sm" data-page="${page + 1}" ${page >= totalPages ? "disabled" : ""}>${t('common.next')} &raquo;</button>
      </div>
    </div>
  `;
}

// --- Truncate ---
export function truncate(str, maxLen = 60) {
  if (!str) return "";
  return str.length > maxLen ? str.slice(0, maxLen) + "..." : str;
}

// --- Simple markdown to HTML (basic) ---
export function mdToHtml(md) {
  if (!md) return "";
  let html = escapeHtml(md);
  html = html.replace(/^### (.+)$/gm, "<h4>$1</h4>");
  html = html.replace(/^## (.+)$/gm, "<h3>$1</h3>");
  html = html.replace(/^# (.+)$/gm, "<h2>$1</h2>");
  html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
  html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
  html = html.replace(/\n/g, "<br>");
  return html;
}

// --- Init sidebar toggle ---
export function initSidebar() {
  const sidebar = document.getElementById("sidebar");
  const toggle = document.getElementById("sidebar-toggle");
  if (!sidebar || !toggle) return;

  const saved = localStorage.getItem("sidebar_collapsed");
  if (saved === "true") sidebar.classList.add("collapsed");

  toggle.addEventListener("click", () => {
    sidebar.classList.toggle("collapsed");
    localStorage.setItem("sidebar_collapsed", sidebar.classList.contains("collapsed"));
  });
}

// --- Init modal close ---
export function initModal() {
  const overlay = document.getElementById("modal-overlay");
  const closeBtn = document.getElementById("modal-close");
  if (closeBtn) closeBtn.addEventListener("click", closeModal);
  if (overlay) {
    overlay.addEventListener("click", (e) => {
      if (e.target === overlay) closeModal();
    });
  }
  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") closeModal();
  });
}

// --- Tabs ---
export function initTabs(container) {
  const tabs = container.querySelectorAll(".tab");
  const panels = container.querySelectorAll(".tab-panel");
  tabs.forEach((tab) => {
    tab.addEventListener("click", () => {
      tabs.forEach((t) => t.classList.remove("active"));
      panels.forEach((p) => p.classList.remove("active"));
      tab.classList.add("active");
      const target = document.getElementById(tab.dataset.tab);
      if (target) target.classList.add("active");
    });
  });
}

// --- Loading helpers ---
export function showLoading(el) {
  el.innerHTML = '<div class="loading-center"><div class="spinner spinner-lg"></div></div>';
}

export function showEmpty(el, message) {
  const msg = message || t('common.noData');
  el.innerHTML = `<div class="empty-state"><p>${escapeHtml(msg)}</p></div>`;
}

// --- Init common ---
document.addEventListener("DOMContentLoaded", () => {
  initSidebar();
  initModal();
});
