/* Strucon branding — runtime DOM patcher.
   Runs AFTER React mounts and re-runs on every DOM change.
   Rewrites "Núcleo" branding to "Strucon Engenharia" without editing the
   original component files. */

(function () {
  const REWRITES = [
    // Most specific first (avoid partial matches clobbering)
    ["Núcleo · Portal do cliente", "Strucon · Portal do cliente"],
    ["v2.4 · acesso seguro", "Engenharia · acesso seguro"],
    ["NÚCLEO CONSTRUTORA · CNPJ 12.345.678/0001-90",
     "STRUCON ENGENHARIA · CREA-SC 209.510-4"],
    ["NÚCLEO CONSTRUTORA", "STRUCON ENGENHARIA"],
    ["CNPJ 12.345.678/0001-90", "CREA-SC 209.510-4"],
    ["Núcleo", "Strucon"],
  ];

  function patchTextNodes(root) {
    if (!root) return 0;
    const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null);
    const nodes = [];
    let n;
    while ((n = walker.nextNode())) nodes.push(n);
    let count = 0;
    for (const node of nodes) {
      let t = node.nodeValue;
      if (!t || !t.trim()) continue;
      const orig = t;
      for (const [from, to] of REWRITES) {
        if (t.includes(from)) t = t.split(from).join(to);
      }
      if (t !== orig) { node.nodeValue = t; count++; }
    }
    return count;
  }

  function patchBrandMarks(root) {
    root.querySelectorAll(".brand-mark").forEach((el) => {
      // Use the same wordmark logo everywhere (mobile = desktop).
      const wantVariant = "wordmark";
      const curVariant = el.getAttribute("data-strucon");
      if (curVariant === wantVariant) return;

      const txt = el.textContent.trim();
      if (curVariant == null && txt !== "N" && el.childElementCount > 0) return;

      el.setAttribute("data-strucon", wantVariant);
      el.setAttribute("aria-label", "Strucon Engenharia");
      el.textContent = "";
      const img = document.createElement("img");
      img.src = wantVariant === "seal"
        ? "assets/strucon-logo.svg"
        : "assets/strucon-wordmark.svg";
      img.alt = "Strucon Engenharia";
      img.className = wantVariant === "seal"
        ? "strucon-seal-img"
        : "strucon-wordmark-img";
      el.appendChild(img);
    });

    // Also: on mobile header, simplify the status line — drop "canteiro ativo · "
    // prefix because it visually competes with the project title in a cramped header.
    root.querySelectorAll(".m-header-status").forEach((el) => {
      if (el.getAttribute("data-strucon-simplified") === "1") return;
      // walk text nodes, strip "canteiro ativo · " prefix
      const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null);
      let n, touched = false;
      while ((n = walker.nextNode())) {
        if (n.nodeValue && n.nodeValue.includes("canteiro ativo · ")) {
          n.nodeValue = n.nodeValue.replace("canteiro ativo · ", "");
          touched = true;
        }
      }
      if (touched) el.setAttribute("data-strucon-simplified", "1");
    });
  }

  let pending = false;
  function patchAll() {
    const root = document.getElementById("root") || document.body;
    if (!root) return;
    patchTextNodes(root);
    patchBrandMarks(root);
  }
  function schedulePatch() {
    if (pending) return;
    pending = true;
    requestAnimationFrame(() => {
      pending = false;
      patchAll();
    });
  }

  function start() {
    patchAll();
    const target = document.body;
    const obs = new MutationObserver(schedulePatch);
    obs.observe(target, {
      childList: true,
      subtree: true,
      characterData: true,
    });
    // Safety net — run every 1s for the first 10s to catch anything missed
    let ticks = 0;
    const iv = setInterval(() => {
      patchAll();
      if (++ticks > 10) clearInterval(iv);
    }, 1000);
  }

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