import { render } from "preact";
import { TableApp } from "./components/TableApp";
import { templateClass } from "./lib/config";
import { ensureStyles } from "./lib/styles";
export { closePopup, openPopup } from "./popup/controller";
import "./table.css";
import "./styles/parts.css";
import "./styles/specs.css";
import "./styles/classic.css";
import "./styles/overlay.css";

/**
 * Storefront table app. WordPress loads this module only where a table is
 * shown (compare page, table block) or when the popup first opens.
 */

/**
 * Renders the table into an element. Returns a function that unmounts it.
 *
 * @param {HTMLElement} el
 * @param {{ ids?: number[], fields?: string[], context?: string,
 *   layout?: string, onlyDiffToggle?: boolean }} options
 */
export function mount(el, options = {}) {
  const props = {
    ids: [],
    fields: [],
    context: "page",
    layout: "auto",
    onlyDiffToggle: true,
    ...options,
  };

  ensureStyles();
  // Drop the server-printed placeholder; Preact owns the element from here.
  el.textContent = "";
  el.classList.add(templateClass());
  render(<TableApp {...props} />, el);
  el.dataset.pcfwMounted = "1";

  return () => {
    render(null, el);
    delete el.dataset.pcfwMounted;
  };
}

/** Reads a mount point's options from its data attributes. */
function optionsFrom(el) {
  const list = (value) => (value || "").split(",").filter(Boolean);
  const { dataset } = el;

  return {
    ids: list(dataset.ids)
      .map(Number)
      .filter((id) => id > 0),
    fields: list(dataset.fields),
    context: dataset.context || "page",
    layout: dataset.layout || "auto",
    onlyDiffToggle: dataset.onlyDiffToggle !== "0",
    shared: dataset.shared === "1",
    title: dataset.title,
    pinned: Number(dataset.pinned) || 0,
    onlyDiff: dataset.onlyDiff === undefined ? null : dataset.onlyDiff === "1",
  };
}

/** Mounts every server-printed `[data-pcfw-table]` not mounted yet. */
export function mountAll(root = document) {
  root
    .querySelectorAll("[data-pcfw-table]:not([data-pcfw-mounted])")
    .forEach((el) => mount(el, optionsFrom(el)));
}

if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", () => mountAll());
} else {
  mountAll();
}
