function escapeHtml(value) {
  return String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function buildActionButton(label, action, libraryId, extraClass = "", disabled = false) {
  const disabledAttribute = disabled ? ' disabled aria-disabled="true"' : "";
  const className = ["library-btn", extraClass].filter(Boolean).join(" ");
  return `<button type="button" class="${className}" data-action="${action}" data-library-id="${escapeHtml(libraryId)}"${disabledAttribute}>${escapeHtml(label)}</button>`;
}

function getPreviewBins(bins) {
  return bins.filter((bin) => {
    const value = String(bin ?? "").trim();
    return value && value !== "[object Object]";
  });
}

export function getLibraryModalElements(rootDocument = document) {
  return {
    createLibraryBtnQuick: rootDocument.getElementById("createLibraryBtnQuick"),
    manageLibrariesBtn: rootDocument.getElementById("manageLibrariesBtn"),
    libraryManagementModal: rootDocument.getElementById("libraryManagementModal"),
    closeLibraryModal: rootDocument.getElementById("closeLibraryModal"),
    libraryList: rootDocument.getElementById("libraryList"),
    newLibraryName: rootDocument.getElementById("newLibraryName"),
    newLibraryBins: rootDocument.getElementById("newLibraryBins"),
    createLibraryBtn: rootDocument.getElementById("createLibraryBtn"),
    importLibraryFile: rootDocument.getElementById("importLibraryFile"),
    importLibraryBtn: rootDocument.getElementById("importLibraryBtn"),
    libraryEditModal: rootDocument.getElementById("libraryEditModal"),
    editModalTitle: rootDocument.getElementById("editModalTitle"),
    editLibraryName: rootDocument.getElementById("editLibraryName"),
    editLibraryBins: rootDocument.getElementById("editLibraryBins"),
    closeEditModal: rootDocument.getElementById("closeEditModal"),
    cancelEditBtn: rootDocument.getElementById("cancelEditBtn"),
    saveEditBtn: rootDocument.getElementById("saveEditBtn")
  };
}

export function buildLibraryItemMarkup(library) {
  const bins = Array.isArray(library?.bins) ? library.bins : [];
  const previewBins = getPreviewBins(bins);
  const preview = previewBins.slice(0, 3).map(escapeHtml).join(", ");
  const totalCount = Number.isFinite(library?.rawBinCount) && library.rawBinCount > bins.length
    ? library.rawBinCount
    : bins.length;
  const countLabel = `${totalCount.toLocaleString()} BIN${totalCount === 1 ? "" : "s"}`;
  const readOnly = Boolean(library?.isReadOnly);

  const actions = [
    buildActionButton("Load", "load", library.id, "primary"),
    buildActionButton("Copy", "copy", library.id),
    buildActionButton("Export", "export", library.id)
  ];

  if (!readOnly) {
    actions.push(buildActionButton("Edit", "edit", library.id));
    actions.push(buildActionButton("Delete", "delete", library.id, "danger"));
  }

  return [
    `<div class="library-item${readOnly ? " readonly" : ""}">`,
    '  <div class="library-info">',
    `    <div class="library-name">${escapeHtml(library?.name || "Untitled Library")}${readOnly ? ' <span class="library-badge">Read only</span>' : ""}</div>`,
    '    <div class="library-meta">',
    `      <span>${escapeHtml(countLabel)}</span>`,
    `      <span class="library-preview${preview ? "" : " library-preview-empty"}" title="${escapeHtml(preview || "Preview unavailable")}">${preview || "Preview unavailable"}</span>`,
    "    </div>",
    "  </div>",
    `  <div class="library-actions">${actions.join("")}</div>`,
    "</div>"
  ].join("");
}
