(function initMyronAppShell(global) {
  "use strict";

  var railStorageKey = "myron.shell.railCollapsed";
  var branchStoragePrefix = "myron.shell.branchCollapsed.";
  var shellAppearanceStorageKey = "myron.shell.appearance";

  function onReady(callback) {
    if (global.document.readyState === "loading") {
      global.document.addEventListener("DOMContentLoaded", callback, { once: true });
      return;
    }

    callback();
  }

  function isMobileViewport() {
    return global.matchMedia("(max-width: 960px)").matches;
  }

  function isShellAppearanceMode(value) {
    return value === "light" || value === "dark";
  }

  function readShellAppearancePreference() {
    try {
      var value = global.localStorage.getItem(shellAppearanceStorageKey) || "";
      return isShellAppearanceMode(value) ? value : "light";
    } catch (error) {
      return "light";
    }
  }

  function writeShellAppearancePreference(mode) {
    if (!isShellAppearanceMode(mode)) {
      return;
    }

    try {
      global.localStorage.setItem(shellAppearanceStorageKey, mode);
    } catch (error) {
      // Ignore storage failures; the shell remains usable without persistence.
    }
  }

  function syncShellAppearanceButtons(mode) {
    var resolved = isShellAppearanceMode(mode) ? mode : "light";
    var buttons = global.document.querySelectorAll("[data-mc-shell-appearance-toggle]");

    buttons.forEach(function syncButton(button) {
      button.setAttribute("data-mc-shell-appearance-state", resolved);
      button.setAttribute("aria-pressed", resolved === "dark" ? "true" : "false");
    });
  }

  function applyShellAppearance(body, mode, persist) {
    var resolved = isShellAppearanceMode(mode) ? mode : "light";
    body.setAttribute("data-mc-shell-appearance", resolved);
    syncShellAppearanceButtons(resolved);

    if (persist) {
      writeShellAppearancePreference(resolved);
    }
  }

  function setupShellAppearance(body) {
    applyShellAppearance(body, readShellAppearancePreference(), false);

    global.document.querySelectorAll("[data-mc-shell-appearance-toggle]").forEach(function bindShellAppearance(button) {
      button.addEventListener("click", function onShellAppearanceClick(event) {
        event.preventDefault();
        var current = body.getAttribute("data-mc-shell-appearance") === "dark" ? "dark" : "light";
        applyShellAppearance(body, current === "dark" ? "light" : "dark", true);
      });
    });
  }

  function readRailPreference() {
    try {
      return global.localStorage.getItem(railStorageKey) === "1";
    } catch (error) {
      return false;
    }
  }

  function writeRailPreference(collapsed) {
    try {
      global.localStorage.setItem(railStorageKey, collapsed ? "1" : "0");
    } catch (error) {
      // Ignore storage failures; the shell still works without persistence.
    }
  }

  function branchStorageKey(branch) {
    return branchStoragePrefix + (branch.getAttribute("data-mc-rail-branch-key") || "branch");
  }

  function readBranchPreference(branch) {
    try {
      return global.localStorage.getItem(branchStorageKey(branch)) === "1";
    } catch (error) {
      return false;
    }
  }

  function writeBranchPreference(branch, collapsed) {
    try {
      global.localStorage.setItem(branchStorageKey(branch), collapsed ? "1" : "0");
    } catch (error) {
      // Ignore storage failures; branch disclosure remains usable.
    }
  }

  function setBranchCollapsed(branch, collapsed, persist) {
    var toggle = branch.querySelector("[data-mc-rail-branch-toggle]");
    var body = branch.querySelector("[data-mc-rail-branch-body]");

    branch.classList.toggle("mc-rail-branch--collapsed", collapsed);

    if (toggle) {
      toggle.setAttribute("aria-expanded", collapsed ? "false" : "true");
    }

    if (body) {
      body.hidden = collapsed;
    }

    if (persist) {
      writeBranchPreference(branch, collapsed);
    }
  }

  function applyDesktopRailPreference(body) {
    if (isMobileViewport()) {
      return;
    }

    body.classList.toggle("mc-shell--rail-collapsed", readRailPreference());
  }

  function syncToggleState(body) {
    var buttons = global.document.querySelectorAll("[data-mc-shell-toggle]");
    var expanded = isMobileViewport()
      ? body.classList.contains("mc-shell--rail-open")
      : !body.classList.contains("mc-shell--rail-collapsed");
    var canDragGroups = !isMobileViewport() && !body.classList.contains("mc-shell--rail-collapsed");

    buttons.forEach(function updateButton(button) {
      button.setAttribute("aria-expanded", expanded ? "true" : "false");
    });

    global.document.querySelectorAll(".mc-rail-group").forEach(function updateGroup(group) {
      group.setAttribute("draggable", canDragGroups ? "true" : "false");
    });
  }

  function toggleRail(body) {
    if (isMobileViewport()) {
      body.classList.toggle("mc-shell--rail-open");
    } else {
      body.classList.toggle("mc-shell--rail-collapsed");
      writeRailPreference(body.classList.contains("mc-shell--rail-collapsed"));
    }

    syncToggleState(body);
  }

  function getDropTarget(container, pointerY) {
    var groups = Array.prototype.slice.call(
      container.querySelectorAll(".mc-rail-group:not(.mc-rail-group--dragging)")
    );

    return groups.reduce(
      function chooseClosest(closest, group) {
        var box = group.getBoundingClientRect();
        var offset = pointerY - box.top - box.height / 2;

        if (offset < 0 && offset > closest.offset) {
          return { offset: offset, element: group };
        }

        return closest;
      },
      { offset: Number.NEGATIVE_INFINITY, element: null }
    ).element;
  }

  function setupRailReorder() {
    var container = global.document.querySelector("[data-mc-rail-groups]");
    if (!container) {
      return;
    }

    var draggedGroup = null;
    var groups = container.querySelectorAll(".mc-rail-group");

    groups.forEach(function bindGroup(group) {
      group.addEventListener("dragstart", function onDragStart(event) {
        draggedGroup = group;
        group.classList.add("mc-rail-group--dragging");
        if (event.dataTransfer) {
          event.dataTransfer.effectAllowed = "move";
          event.dataTransfer.setData("text/plain", group.getAttribute("data-mc-group") || "");
        }
      });

      group.addEventListener("dragend", function onDragEnd() {
        group.classList.remove("mc-rail-group--dragging");
        draggedGroup = null;
      });
    });

    container.addEventListener("dragover", function onDragOver(event) {
      if (!draggedGroup) {
        return;
      }

      event.preventDefault();
      var after = getDropTarget(container, event.clientY);
      if (!after) {
        container.appendChild(draggedGroup);
        return;
      }

      if (after !== draggedGroup) {
        container.insertBefore(draggedGroup, after);
      }
    });
  }

  function setupRailBranches() {
    var branches = global.document.querySelectorAll("[data-mc-rail-branch]");
    if (!branches.length) {
      return;
    }

    branches.forEach(function bindBranch(branch) {
      var toggle = branch.querySelector("[data-mc-rail-branch-toggle]");
      var activeBranch = branch.getAttribute("data-mc-rail-branch-active") === "true";

      setBranchCollapsed(branch, activeBranch ? false : readBranchPreference(branch), false);

      if (!toggle) {
        return;
      }

      toggle.addEventListener("click", function onToggleClick() {
        setBranchCollapsed(branch, !branch.classList.contains("mc-rail-branch--collapsed"), true);
      });
    });
  }

  function setupAvatarMenus() {
    var roots = global.document.querySelectorAll("[data-mc-avatar-menu-root]");
    if (!roots.length) {
      return;
    }

    function closeAllMenus(exceptRoot) {
      roots.forEach(function closeMenu(root) {
        var toggle = root.querySelector("[data-mc-avatar-toggle]");
        var menu = root.querySelector("[data-mc-avatar-menu]");
        if (!toggle || !menu || root === exceptRoot) {
          return;
        }

        toggle.setAttribute("aria-expanded", "false");
        menu.hidden = true;
      });
    }

    roots.forEach(function bindMenu(root) {
      var toggle = root.querySelector("[data-mc-avatar-toggle]");
      var menu = root.querySelector("[data-mc-avatar-menu]");
      if (!toggle || !menu) {
        return;
      }

      toggle.addEventListener("click", function onToggleClick() {
        var isOpen = toggle.getAttribute("aria-expanded") === "true";
        closeAllMenus(isOpen ? null : root);
        toggle.setAttribute("aria-expanded", isOpen ? "false" : "true");
        menu.hidden = isOpen;
      });
    });

    global.document.addEventListener("click", function onDocumentClick(event) {
      var target = event.target;
      roots.forEach(function closeOutside(root) {
        if (root.contains(target)) {
          return;
        }

        var toggle = root.querySelector("[data-mc-avatar-toggle]");
        var menu = root.querySelector("[data-mc-avatar-menu]");
        if (!toggle || !menu) {
          return;
        }

        toggle.setAttribute("aria-expanded", "false");
        menu.hidden = true;
      });
    });

    global.document.addEventListener("keydown", function onDocumentKeydown(event) {
      if (event.key !== "Escape") {
        return;
      }

      closeAllMenus(null);
    });
  }

  function setupNotificationMenus() {
    var roots = global.document.querySelectorAll("[data-mc-notification-menu-root]");
    if (!roots.length) {
      return;
    }

    function closeAllMenus(exceptRoot) {
      roots.forEach(function closeMenu(root) {
        var toggle = root.querySelector("[data-mc-notification-toggle]");
        var menu = root.querySelector("[data-mc-notification-menu]");
        if (!toggle || !menu || root === exceptRoot) {
          return;
        }

        toggle.setAttribute("aria-expanded", "false");
        menu.hidden = true;
      });
    }

    roots.forEach(function bindMenu(root) {
      var toggle = root.querySelector("[data-mc-notification-toggle]");
      var menu = root.querySelector("[data-mc-notification-menu]");
      if (!toggle || !menu) {
        return;
      }

      toggle.addEventListener("click", function onToggleClick() {
        var isOpen = toggle.getAttribute("aria-expanded") === "true";
        closeAllMenus(isOpen ? null : root);
        toggle.setAttribute("aria-expanded", isOpen ? "false" : "true");
        menu.hidden = isOpen;
      });
    });

    global.document.addEventListener("click", function onDocumentClick(event) {
      var target = event.target;
      roots.forEach(function closeOutside(root) {
        if (root.contains(target)) {
          return;
        }

        var toggle = root.querySelector("[data-mc-notification-toggle]");
        var menu = root.querySelector("[data-mc-notification-menu]");
        if (!toggle || !menu) {
          return;
        }

        toggle.setAttribute("aria-expanded", "false");
        menu.hidden = true;
      });
    });

    global.document.addEventListener("keydown", function onDocumentKeydown(event) {
      if (event.key !== "Escape") {
        return;
      }

      closeAllMenus(null);
    });
  }

  function markDashboardMessageRead(trigger) {
    if (!trigger || !global.fetch || !trigger.hasAttribute("data-mc-message-read-url")) {
      return;
    }

    var endpoint = trigger.getAttribute("data-mc-message-read-url") || "";
    var messageId = trigger.getAttribute("data-mc-message-id") || "";
    var csrfToken = trigger.getAttribute("data-mc-message-csrf") || "";
    if (!endpoint || !messageId || !csrfToken || trigger.getAttribute("data-mc-message-read-sent") === "true") {
      return;
    }

    trigger.setAttribute("data-mc-message-read-sent", "true");
    var body = new URLSearchParams();
    body.set("csrf_token", csrfToken);
    body.set("message_id", messageId);

    global.fetch(endpoint, {
      method: "POST",
      credentials: "same-origin",
      headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" },
      body: body.toString()
    }).catch(function ignoreReadFailure() {
      trigger.removeAttribute("data-mc-message-read-sent");
    });
  }

  function setupAdminSidesheets() {
    var sheets = global.document.querySelectorAll("[data-mc-sidesheet]");
    if (!sheets.length) {
      return;
    }

    var activeSheet = null;
    var activeTrigger = null;
    var focusableSelector = [
      "a[href]",
      "button:not([disabled])",
      "input:not([disabled])",
      "select:not([disabled])",
      "textarea:not([disabled])",
      "[tabindex]:not([tabindex='-1'])"
    ].join(",");

    function findSheet(id) {
      if (!id) {
        return null;
      }

      return global.document.getElementById(id);
    }

    function focusTarget(sheet) {
      return sheet.querySelector("[data-mc-sidesheet-initial-focus]")
        || sheet.querySelector(focusableSelector)
        || sheet.querySelector("[data-mc-sidesheet-panel]")
        || sheet;
    }

    function setTriggerExpanded(trigger, expanded) {
      if (trigger) {
        trigger.setAttribute("aria-expanded", expanded ? "true" : "false");
      }
    }

    function closeSheet(sheet, restoreFocus) {
      var targetSheet = sheet || activeSheet;
      if (!targetSheet) {
        return;
      }

      if (targetSheet._myronRichtextToolbar && typeof targetSheet._myronRichtextToolbar.destroy === "function") {
        targetSheet._myronRichtextToolbar.destroy();
        targetSheet._myronRichtextToolbar = null;
      }
      targetSheet.hidden = true;
      targetSheet.setAttribute("aria-hidden", "true");
      global.document.body.classList.remove("mc-shell--sidesheet-open");
      setTriggerExpanded(activeTrigger, false);

      if (restoreFocus && activeTrigger && typeof activeTrigger.focus === "function") {
        activeTrigger.focus();
      }

      if (targetSheet === activeSheet) {
        activeSheet = null;
        activeTrigger = null;
      }
    }

    function openSheet(sheet, trigger) {
      if (!sheet) {
        return;
      }

      if (activeSheet && activeSheet !== sheet) {
        closeSheet(activeSheet, false);
      }

      activeSheet = sheet;
      activeTrigger = trigger || null;
      sheet.hidden = false;
      sheet.setAttribute("aria-hidden", "false");
      global.document.body.classList.add("mc-shell--sidesheet-open");
      setTriggerExpanded(trigger, true);
      markDashboardMessageRead(trigger);
      if (sheet.querySelector("[data-mc-richtext-toolbar]") && typeof global.setupRichtextToolbar === "function") {
        sheet._myronRichtextToolbar = global.setupRichtextToolbar(sheet);
      }

      global.requestAnimationFrame(function focusSheet() {
        focusTarget(sheet).focus();
      });
    }

    global.document.querySelectorAll("[data-mc-sidesheet-open]").forEach(function bindTrigger(trigger) {
      var sheetId = trigger.getAttribute("data-mc-sidesheet-open") || "";
      var sheet = findSheet(sheetId);
      if (!sheet) {
        return;
      }

      trigger.setAttribute("aria-haspopup", "dialog");
      trigger.setAttribute("aria-controls", sheetId);
      trigger.setAttribute("aria-expanded", "false");

      trigger.addEventListener("click", function onTriggerClick(event) {
        event.preventDefault();
        openSheet(sheet, trigger);
      });
    });

    sheets.forEach(function bindSheet(sheet) {
      sheet.querySelectorAll("[data-mc-sidesheet-close]").forEach(function bindClose(closeControl) {
        closeControl.addEventListener("click", function onCloseClick() {
          closeSheet(sheet, true);
        });
      });

      sheet.addEventListener("keydown", function onSheetKeydown(event) {
        if (event.key === "Escape") {
          event.preventDefault();
          closeSheet(sheet, true);
          return;
        }

        if (event.key !== "Tab") {
          return;
        }

        var focusable = Array.prototype.slice.call(sheet.querySelectorAll(focusableSelector))
          .filter(function visible(element) {
            return element.offsetParent !== null || element === global.document.activeElement;
          });

        if (!focusable.length) {
          event.preventDefault();
          focusTarget(sheet).focus();
          return;
        }

        var first = focusable[0];
        var last = focusable[focusable.length - 1];
        if (event.shiftKey && global.document.activeElement === first) {
          event.preventDefault();
          last.focus();
        } else if (!event.shiftKey && global.document.activeElement === last) {
          event.preventDefault();
          first.focus();
        }
      });
    });
  }

  function setupStandaloneRichtextToolbars() {
    if (typeof global.setupRichtextToolbar !== "function") {
      return;
    }

    var controls = Array.prototype.slice.call(global.document.querySelectorAll("[data-mc-richtext]"))
      .filter(function outsideSidesheet(control) {
        return !control.closest("[data-mc-sidesheet]");
      });
    var roots = [];
    controls.forEach(function collectRoot(control) {
      var root = control.closest("form") || control.closest(".sg-section") || control.parentElement;
      if (!root || roots.indexOf(root) !== -1) {
        return;
      }
      roots.push(root);
    });

    roots.forEach(function mountToolbar(root) {
      if (root.querySelector("[data-mc-richtext-toolbar]")) {
        return;
      }
      var slot = global.document.createElement("div");
      slot.className = "mc-sidesheet-overlay__toolbar mc-richtext-toolbar--standalone";
      slot.setAttribute("data-mc-richtext-toolbar", "");
      root.insertBefore(slot, root.firstChild);
      global.setupRichtextToolbar(root);
    });
  }

  function setupLiveInspectionFilters() {
    var roots = global.document.querySelectorAll("[data-mc-live-filter]");
    if (!roots.length) {
      return;
    }

    function selectedValuesForGroup(group) {
      return Array.prototype.slice.call(group.querySelectorAll("[data-mc-filter-value]"))
        .filter(function selected(button) {
          return button.getAttribute("aria-pressed") === "true";
        })
        .map(function value(button) {
          return button.getAttribute("data-mc-filter-value") || "";
        })
        .filter(Boolean);
    }

    function valuesFromUrl(param) {
      var params = new URLSearchParams(global.location.search);
      var values = [];
      params.getAll(param).forEach(function collect(rawValue) {
        String(rawValue || "").split(",").forEach(function splitValue(value) {
          var normalized = value.trim();
          if (normalized && values.indexOf(normalized) === -1) {
            values.push(normalized);
          }
        });
      });
      return values;
    }

    function rowValueMatches(row, param, selectedValues) {
      if (!selectedValues.length) {
        return true;
      }

      var rowValues = rowValuesForParam(row, param);
      return selectedValues.some(function hasValue(value) {
        return rowValues.indexOf(value) !== -1;
      });
    }

    function rowValuesForParam(row, param) {
      var rawValue = row.getAttribute("data-filter-" + param) || "";
      return rawValue.split("||").map(function normalize(value) {
        return value.trim();
      }).filter(Boolean);
    }

    function updateUrl(groups) {
      if (!global.history || typeof global.history.replaceState !== "function") {
        return;
      }

      var url = new URL(global.location.href);
      groups.forEach(function syncParam(group) {
        var param = group.getAttribute("data-mc-filter-param") || "";
        if (!param) {
          return;
        }

        var selectedValues = selectedValuesForGroup(group);
        url.searchParams.delete(param);
        if (selectedValues.length) {
          url.searchParams.set(param, selectedValues.join(","));
        }
      });

      global.history.replaceState({}, "", url.toString());
    }

    function syncGroupPills(group) {
      var selectedValues = selectedValuesForGroup(group);
      var allButton = group.querySelector("[data-mc-filter-all]");

      if (allButton) {
        var allSelected = selectedValues.length === 0;
        allButton.setAttribute("aria-pressed", allSelected ? "true" : "false");
        allButton.classList.toggle("sg-pill--active", allSelected);
      }

      group.querySelectorAll("[data-mc-filter-value]").forEach(function syncButton(button) {
        var selected = button.getAttribute("aria-pressed") === "true";
        button.classList.toggle("sg-pill--active", selected);
      });
    }

    function rowMatchesSelections(row, selections, excludedParam) {
      return selections.every(function matches(selection) {
        if (excludedParam && selection.param === excludedParam) {
          return true;
        }

        return rowValueMatches(row, selection.param, selection.values);
      });
    }

    function syncAdaptiveFilterOptions(container, groups, selections) {
      var rows = Array.prototype.slice.call(container.querySelectorAll("[data-mc-filter-row]"));

      groups.forEach(function syncGroupOptions(group) {
        var param = group.getAttribute("data-mc-filter-param") || "";
        if (!param) {
          return;
        }

        var availableValues = {};
        rows.filter(function candidateRows(row) {
          return rowMatchesSelections(row, selections, param);
        }).forEach(function collectRowValues(row) {
          rowValuesForParam(row, param).forEach(function collectValue(value) {
            availableValues[value] = true;
          });
        });

        group.querySelectorAll("[data-mc-filter-value]").forEach(function syncButton(button) {
          var value = button.getAttribute("data-mc-filter-value") || "";
          var selected = button.getAttribute("aria-pressed") === "true";
          var available = Boolean(availableValues[value]);

          button.hidden = !selected && !available;
          button.disabled = !selected && !available;
          button.setAttribute("aria-hidden", button.hidden ? "true" : "false");
          button.classList.toggle("mc-filter-pill--unavailable", !available);
        });
      });
    }

    function updateCounts(container) {
      container.querySelectorAll("[data-mc-filter-count]").forEach(function updateCount(countNode) {
        var scope = countNode.getAttribute("data-mc-filter-count-scope") || "";
        var label = countNode.getAttribute("data-mc-filter-count-label") || "matching";
        var rows = Array.prototype.slice.call(container.querySelectorAll("[data-mc-filter-row]"))
          .filter(function inScope(row) {
            return !scope || (row.getAttribute("data-mc-filter-scope") || "") === scope;
          })
          .filter(function visible(row) {
            return !row.hidden;
          });

        countNode.textContent = rows.length + " " + label;
      });
    }

    function updateEmptyStates(container) {
      container.querySelectorAll("[data-mc-filter-empty]").forEach(function updateEmpty(emptyNode) {
        var scope = emptyNode.getAttribute("data-mc-filter-empty-scope") || "";
        var visibleRows = Array.prototype.slice.call(container.querySelectorAll("[data-mc-filter-row]"))
          .filter(function inScope(row) {
            return !scope || (row.getAttribute("data-mc-filter-scope") || "") === scope;
          })
          .filter(function visible(row) {
            return !row.hidden;
          });

        emptyNode.hidden = visibleRows.length !== 0;
      });
    }

    function applyFilters(container, groups, syncUrl) {
      var selectedByParam = groups.map(function groupSelection(group) {
        return {
          param: group.getAttribute("data-mc-filter-param") || "",
          values: selectedValuesForGroup(group)
        };
      }).filter(function hasParam(selection) {
        return selection.param !== "";
      });

      container.querySelectorAll("[data-mc-filter-row]").forEach(function updateRow(row) {
        var visible = rowMatchesSelections(row, selectedByParam, "");
        row.hidden = !visible;
      });

      groups.forEach(syncGroupPills);
      syncAdaptiveFilterOptions(container, groups, selectedByParam);
      updateCounts(container);
      updateEmptyStates(container);
      if (syncUrl) {
        updateUrl(groups);
      }
    }

    roots.forEach(function bindRoot(root) {
      var container = root.closest(".sg-main") || global.document;
      var groups = Array.prototype.slice.call(root.querySelectorAll("[data-mc-filter-group]"));
      if (!groups.length) {
        return;
      }

      groups.forEach(function bindGroup(group) {
        var param = group.getAttribute("data-mc-filter-param") || "";
        var urlValues = valuesFromUrl(param);

        if (urlValues.length) {
          group.querySelectorAll("[data-mc-filter-value]").forEach(function restoreButton(button) {
            var value = button.getAttribute("data-mc-filter-value") || "";
            button.setAttribute("aria-pressed", urlValues.indexOf(value) !== -1 ? "true" : "false");
          });
        }

        group.querySelectorAll("[data-mc-filter-all]").forEach(function bindAll(button) {
          button.addEventListener("click", function onAllClick() {
            group.querySelectorAll("[data-mc-filter-value]").forEach(function clearButton(valueButton) {
              valueButton.setAttribute("aria-pressed", "false");
            });
            applyFilters(container, groups, true);
          });
        });

        group.querySelectorAll("[data-mc-filter-value]").forEach(function bindButton(button) {
          button.addEventListener("click", function onFilterClick() {
            var selected = button.getAttribute("aria-pressed") === "true";
            button.setAttribute("aria-pressed", selected ? "false" : "true");
            applyFilters(container, groups, true);
          });
        });

        syncGroupPills(group);
      });

      applyFilters(container, groups, false);
    });
  }

  function setupSortableGrids() {
    var grids = global.document.querySelectorAll("[data-mc-sortable-grid]");
    if (!grids.length) {
      return;
    }

    function valueForRow(row, key, type) {
      var rawValue = row.getAttribute("data-sort-" + key) || "";
      if (type === "number") {
        var numericValue = Number(rawValue);
        return Number.isFinite(numericValue) ? numericValue : 0;
      }

      return rawValue.toLowerCase();
    }

    function compareRows(key, type, direction) {
      return function compare(a, b) {
        var aValue = valueForRow(a, key, type);
        var bValue = valueForRow(b, key, type);
        var result = 0;

        if (aValue < bValue) {
          result = -1;
        } else if (aValue > bValue) {
          result = 1;
        }

        if (result === 0) {
          var aIndex = Number(a.getAttribute("data-sort-original-index") || "0");
          var bIndex = Number(b.getAttribute("data-sort-original-index") || "0");
          result = aIndex - bIndex;
        }

        return direction === "desc" ? result * -1 : result;
      };
    }

    grids.forEach(function bindGrid(grid) {
      var rows = Array.prototype.slice.call(grid.querySelectorAll("[data-mc-filter-row]"));
      rows.forEach(function markOriginalOrder(row, index) {
        if (!row.hasAttribute("data-sort-original-index")) {
          row.setAttribute("data-sort-original-index", String(index));
        }
      });

      grid.querySelectorAll("[data-mc-sort-key]").forEach(function bindSort(header) {
        var button = header.querySelector("button");
        var key = header.getAttribute("data-mc-sort-key") || "";
        var type = header.getAttribute("data-mc-sort-type") || "text";
        if (!button || !key) {
          return;
        }

        header.setAttribute("aria-sort", "none");
        button.addEventListener("click", function onSortClick() {
          var currentDirection = grid.getAttribute("data-mc-sort-direction") || "";
          var currentKey = grid.getAttribute("data-mc-sort-current") || "";
          var nextDirection = currentKey === key && currentDirection === "asc" ? "desc" : "asc";

          grid.setAttribute("data-mc-sort-current", key);
          grid.setAttribute("data-mc-sort-direction", nextDirection);
          grid.querySelectorAll("[data-mc-sort-key]").forEach(function clearSort(otherHeader) {
            otherHeader.setAttribute("aria-sort", otherHeader === header ? (nextDirection === "asc" ? "ascending" : "descending") : "none");
          });

          Array.prototype.slice.call(grid.querySelectorAll("[data-mc-filter-row]"))
            .sort(compareRows(key, type, nextDirection))
            .forEach(function appendSortedRow(row) {
              grid.appendChild(row);
            });
        });
      });
    });
  }

  function setupPageEditorAbandonModal() {
    var form = global.document.querySelector("[data-page-editor-form]");
    if (!form) {
      return;
    }

    var abandonReturn = form.getAttribute("data-page-abandon-return") || "";
    var dialog = global.document.querySelector("[data-page-abandon-dialog]");
    var backdrop = global.document.querySelector("[data-page-abandon-backdrop]");
    var openButtons = global.document.querySelectorAll("[data-page-abandon-open]");
    if (!openButtons.length || !abandonReturn) {
      return;
    }

    function serializedForm() {
      var values = [];
      Array.prototype.slice.call(form.elements).forEach(function serialize(element) {
        if (!element.name || element.disabled) {
          return;
        }

        var type = String(element.type || "").toLowerCase();
        if ((type === "checkbox" || type === "radio") && !element.checked) {
          return;
        }

        values.push(element.name + "=" + String(element.value || ""));
      });

      return values.join("&");
    }

    var initialFormState = serializedForm();

    function formIsDirty() {
      return serializedForm() !== initialFormState;
    }

    function closeDialog() {
      if (dialog) {
        dialog.hidden = true;
        dialog.setAttribute("aria-hidden", "true");
      }
      if (backdrop) {
        backdrop.hidden = true;
        backdrop.setAttribute("aria-hidden", "true");
      }
    }

    function openDialog() {
      if (!dialog || !backdrop) {
        global.location.href = abandonReturn;
        return;
      }

      backdrop.hidden = false;
      backdrop.setAttribute("aria-hidden", "false");
      dialog.hidden = false;
      dialog.setAttribute("aria-hidden", "false");
      dialog.focus();
    }

    openButtons.forEach(function bindOpen(button) {
      button.addEventListener("click", function onAbandonClick(event) {
        event.preventDefault();
        if (!formIsDirty()) {
          global.location.href = abandonReturn;
          return;
        }

        openDialog();
      });
    });

    global.document.querySelectorAll("[data-page-abandon-close]").forEach(function bindClose(button) {
      button.addEventListener("click", function onCloseClick(event) {
        event.preventDefault();
        closeDialog();
      });
    });

    if (backdrop) {
      backdrop.addEventListener("click", closeDialog);
    }

    if (dialog) {
      dialog.addEventListener("keydown", function onDialogKeydown(event) {
        if (event.key === "Escape") {
          event.preventDefault();
          closeDialog();
        }
      });
    }
  }

  function setupPageEditorTemplateWorkflow() {
    var form = global.document.querySelector("[data-page-editor-form]");
    if (!form) {
      return;
    }

    var templateControl = form.elements.namedItem("template_id");
    var parentSelect = form.elements.namedItem("parent_page_id") || global.document.querySelector("[data-page-parent-select]");
    var categoriesPanel = global.document.querySelector("[data-page-blog-categories]");
    var commentsPanel = global.document.querySelector("[data-page-blog-comments]");
    if (!templateControl) {
      return;
    }

    var isExistingPage = form.getAttribute("data-page-editor-existing-page") === "true";
    var parentWasManuallyChanged = isExistingPage;
    var lastAutoParentId = "";

    function selectedTemplateDataset() {
      if (templateControl.tagName && templateControl.tagName.toLowerCase() === "select") {
        return templateControl.options[templateControl.selectedIndex]
          ? templateControl.options[templateControl.selectedIndex].dataset
          : {};
      }

      return templateControl.dataset || {};
    }

    function setCategoryVisibility(isBlogPostTemplate) {
      if (!categoriesPanel) {
        return;
      }

      categoriesPanel.hidden = !isBlogPostTemplate;
      categoriesPanel.querySelectorAll("input[type='checkbox']").forEach(function toggleCategoryInput(input) {
        input.disabled = !isBlogPostTemplate;
      });
    }

    function setCommentVisibility(isBlogPostTemplate) {
      if (!commentsPanel) {
        return;
      }

      commentsPanel.hidden = !isBlogPostTemplate;
      commentsPanel.querySelectorAll("input[type='radio']").forEach(function toggleCommentInput(input) {
        input.disabled = !isBlogPostTemplate;
      });
    }

    function bestBlogIndexParentId(siteType) {
      if (!parentSelect) {
        return "";
      }

      var candidates = Array.prototype.slice.call(parentSelect.options).filter(function filterBlogIndex(option) {
        return option.value !== "" && option.dataset.pageTemplateRole === "blog-index";
      });

      if (!candidates.length) {
        return "";
      }

      candidates.sort(function sortCandidates(first, second) {
        function score(option) {
          var path = option.dataset.pagePath || "";
          var optionSiteType = option.dataset.pageTemplateSiteType || "";
          var value = 0;
          if (siteType && optionSiteType === siteType) {
            value += 30;
          }
          if (path === "/blog") {
            value += 20;
          } else if (path.indexOf("/blog") === 0) {
            value += 10;
          }
          return value;
        }

        return score(second) - score(first);
      });

      return candidates[0].value || "";
    }

    function syncTemplateDrivenFields() {
      var dataset = selectedTemplateDataset();
      var templateRole = dataset.pageTemplateRole || "";
      var isBlogPostTemplate = templateRole === "post-single";
      setCategoryVisibility(isBlogPostTemplate);
      setCommentVisibility(isBlogPostTemplate);

      if (!parentSelect || parentWasManuallyChanged) {
        return;
      }

      if (!isBlogPostTemplate) {
        if (lastAutoParentId !== "" && parentSelect.value === lastAutoParentId) {
          parentSelect.value = "";
          lastAutoParentId = "";
        }
        return;
      }

      var blogIndexParentId = bestBlogIndexParentId(dataset.pageTemplateSiteType || "");
      if (blogIndexParentId !== "") {
        parentSelect.value = blogIndexParentId;
        lastAutoParentId = blogIndexParentId;
      }
    }

    if (parentSelect) {
      parentSelect.addEventListener("change", function onParentChange() {
        parentWasManuallyChanged = true;
      });
    }

    templateControl.addEventListener("change", syncTemplateDrivenFields);
    syncTemplateDrivenFields();
  }

  function setupPageEditorDeleteModal() {
    var dialog = global.document.querySelector("[data-page-delete-dialog]");
    var backdrop = global.document.querySelector("[data-page-delete-backdrop]");
    var openButtons = global.document.querySelectorAll("[data-page-delete-open]");
    var confirmButton = dialog ? dialog.querySelector("[data-page-delete-confirm]") : null;
    if (!openButtons.length) {
      return;
    }

    function closeDialog() {
      if (dialog) {
        dialog.hidden = true;
        dialog.setAttribute("aria-hidden", "true");
      }
      if (backdrop) {
        backdrop.hidden = true;
        backdrop.setAttribute("aria-hidden", "true");
      }
    }

    function openDialog() {
      if (!dialog || !backdrop) {
        return;
      }

      backdrop.hidden = false;
      backdrop.setAttribute("aria-hidden", "false");
      dialog.hidden = false;
      dialog.setAttribute("aria-hidden", "false");
      (confirmButton || dialog).focus();
    }

    openButtons.forEach(function bindOpen(button) {
      button.addEventListener("click", function onDeleteClick(event) {
        event.preventDefault();
        openDialog();
      });
    });

    global.document.querySelectorAll("[data-page-delete-close]").forEach(function bindClose(button) {
      button.addEventListener("click", function onCloseClick(event) {
        event.preventDefault();
        closeDialog();
      });
    });

    if (backdrop) {
      backdrop.addEventListener("click", closeDialog);
    }

    if (dialog) {
      dialog.addEventListener("keydown", function onDialogKeydown(event) {
        if (event.key === "Escape") {
          event.preventDefault();
          closeDialog();
        }
      });
    }
  }

  function setupVisualSectionEditor() {
    var canvas = global.document.querySelector("[data-mc-visual-editor-canvas]");
    var trigger = global.document.querySelector("[data-mc-visual-section-editor-trigger]");
    var panels = Array.prototype.slice.call(global.document.querySelectorAll("[data-mc-visual-section-panel]"));
    var emptyStates = Array.prototype.slice.call(global.document.querySelectorAll("[data-mc-visual-section-empty]"));
    var activeInstanceKey = "";

    if (!canvas || !trigger || !panels.length) {
      return;
    }

    function activatePanel(instanceKey) {
      var matched = false;
      var requestedInstanceKey = instanceKey || "";
      panels.forEach(function togglePanel(panel) {
        var isActive = requestedInstanceKey !== "" && panel.getAttribute("data-section-instance-key") === requestedInstanceKey;
        panel.hidden = !isActive;
        panel.setAttribute("aria-hidden", isActive ? "false" : "true");
        if (isActive) {
          matched = true;
        }
      });

      activeInstanceKey = matched ? requestedInstanceKey : "";
      emptyStates.forEach(function toggleEmptyState(emptyState) {
        emptyState.hidden = matched;
        emptyState.setAttribute("aria-hidden", matched ? "true" : "false");
      });
    }

    activatePanel("");

    canvas.addEventListener("click", function onCanvasClick(event) {
      var target = event.target;
      if (!target || typeof target.closest !== "function") {
        return;
      }

      var section = target.closest("[data-myron-editor-section]");
      if (!section) {
        return;
      }

      event.preventDefault();
      activatePanel(section.getAttribute("data-section-instance-key") || "");
      trigger.click();
    });
  }

  function setupTemplateSectionPicker() {
    var pickers = Array.prototype.slice.call(global.document.querySelectorAll("[data-template-section-picker]"));
    if (!pickers.length) {
      return;
    }

    pickers.forEach(function bindPicker(picker) {
      var search = picker.querySelector("[data-template-section-picker-search]");
      var rows = Array.prototype.slice.call(picker.querySelectorAll("[data-template-section-picker-row]"));
      var groups = Array.prototype.slice.call(picker.querySelectorAll("[data-template-section-picker-group]"));
      if (!search || !rows.length) {
        return;
      }

      function applyFilter() {
        var query = (search.value || "").trim().toLowerCase();
        rows.forEach(function filterRow(row) {
          var haystack = row.getAttribute("data-search-text") || "";
          row.hidden = query !== "" && haystack.indexOf(query) === -1;
        });

        groups.forEach(function filterGroup(group) {
          var visibleRows = Array.prototype.slice.call(group.querySelectorAll("[data-template-section-picker-row]"))
            .filter(function visible(row) {
              return !row.hidden;
            });
          group.hidden = visibleRows.length === 0;
        });
      }

      search.addEventListener("input", applyFilter);
      applyFilter();
    });
  }

  function setupTemplateSectionDragDrop() {
    var lists = Array.prototype.slice.call(global.document.querySelectorAll("[data-template-section-dnd-list]"));
    var form = global.document.querySelector("[data-template-section-reorder-form]");
    if (!lists.length || !form) {
      return;
    }

    function orderForList(list) {
      return Array.prototype.slice.call(list.querySelectorAll("[data-template-section-drag-item]"))
        .map(function itemPosition(item) {
          return item.getAttribute("data-template-section-drag-position") || "";
        })
        .filter(function hasPosition(position) {
          return position !== "";
        });
    }

    function appendOrderInputs(order) {
      Array.prototype.slice.call(form.querySelectorAll("[data-template-section-order-input]")).forEach(function removeInput(input) {
        input.remove();
      });
      order.forEach(function appendPosition(position) {
        var input = global.document.createElement("input");
        input.type = "hidden";
        input.name = "section_order[]";
        input.value = position;
        input.setAttribute("data-template-section-order-input", "true");
        form.appendChild(input);
      });
    }

    function afterDragElement(list, y) {
      var candidates = Array.prototype.slice.call(list.querySelectorAll("[data-template-section-drag-item]:not(.is-dragging)"));
      return candidates.reduce(function closestMatch(closest, child) {
        var box = child.getBoundingClientRect();
        var offset = y - box.top - (box.height / 2);
        if (offset < 0 && offset > closest.offset) {
          return { offset: offset, element: child };
        }
        return closest;
      }, { offset: Number.NEGATIVE_INFINITY, element: null }).element;
    }

    lists.forEach(function bindList(list) {
      var initialOrder = orderForList(list).join(",");
      var dragging = null;

      Array.prototype.slice.call(list.querySelectorAll("[data-template-section-drag-item]")).forEach(function bindItem(item) {
        item.addEventListener("dragstart", function onDragStart(event) {
          if (item.getAttribute("draggable") !== "true") {
            return;
          }
          dragging = item;
          item.classList.add("is-dragging");
          if (event.dataTransfer) {
            event.dataTransfer.effectAllowed = "move";
            event.dataTransfer.setData("text/plain", item.getAttribute("data-template-section-drag-position") || "");
          }
        });

        item.addEventListener("dragend", function onDragEnd() {
          item.classList.remove("is-dragging");
          dragging = null;
        });
      });

      list.addEventListener("dragover", function onDragOver(event) {
        if (!dragging) {
          return;
        }
        event.preventDefault();
        var afterElement = afterDragElement(list, event.clientY);
        if (afterElement === null) {
          list.appendChild(dragging);
          return;
        }
        list.insertBefore(dragging, afterElement);
      });

      list.addEventListener("drop", function onDrop(event) {
        if (!dragging) {
          return;
        }
        event.preventDefault();
        var order = orderForList(list);
        if (order.join(",") === initialOrder) {
          return;
        }
        appendOrderInputs(order);
        if (typeof form.requestSubmit === "function") {
          form.requestSubmit();
          return;
        }
        form.submit();
      });
    });
  }

  function setupDashboardTabs() {
    var roots = global.document.querySelectorAll("[data-mc-dashboard-tabs]");
    if (!roots.length) {
      return;
    }

    roots.forEach(function bindDashboardTabs(root) {
      var tabs = Array.prototype.slice.call(root.querySelectorAll("[data-mc-dashboard-tab]"));
      var panels = Array.prototype.slice.call(root.querySelectorAll("[data-mc-dashboard-panel]"));
      if (!tabs.length || !panels.length) {
        return;
      }

      function activateTab(key) {
        tabs.forEach(function syncTab(tab) {
          var active = (tab.getAttribute("data-mc-dashboard-tab") || "") === key;
          tab.classList.toggle("sg-pill--active", active);
          tab.setAttribute("aria-selected", active ? "true" : "false");
          tab.setAttribute("tabindex", active ? "0" : "-1");
        });

        panels.forEach(function syncPanel(panel) {
          var active = (panel.getAttribute("data-mc-dashboard-panel") || "") === key;
          panel.hidden = !active;
          panel.setAttribute("aria-hidden", active ? "false" : "true");
        });
      }

      try {
        var requested = new URL(global.location.href).searchParams.get("tab") || "";
        if (requested && tabs.some(function hasRequestedTab(tab) {
          return (tab.getAttribute("data-mc-dashboard-tab") || "") === requested;
        })) {
          activateTab(requested);
        }
      } catch (error) {
        // URL parsing is non-critical; server-rendered active state remains authoritative.
      }

      tabs.forEach(function bindTab(tab) {
        tab.addEventListener("click", function onDashboardTabClick(event) {
          event.preventDefault();
          activateTab(tab.getAttribute("data-mc-dashboard-tab") || "");
        });
        tab.addEventListener("keydown", function onDashboardTabKeydown(event) {
          if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") {
            return;
          }
          event.preventDefault();
          var currentIndex = tabs.indexOf(tab);
          var direction = event.key === "ArrowRight" ? 1 : -1;
          var nextIndex = (currentIndex + direction + tabs.length) % tabs.length;
          tabs[nextIndex].focus();
          activateTab(tabs[nextIndex].getAttribute("data-mc-dashboard-tab") || "");
        });
      });
    });
  }

  function setupStudioBreakpointPreview() {
    var canvases = Array.prototype.slice.call(global.document.querySelectorAll("[data-mc-studio-preview-canvas]"));
    var toggleRoots = Array.prototype.slice.call(global.document.querySelectorAll("[data-mc-studio-breakpoint-toggle]"));
    if (!canvases.length || !toggleRoots.length) {
      return;
    }

    var storageKey = "myron-studio-breakpoint";
    var validBreakpoints = ["mobile", "tablet", "desktop"];

    function isValidBreakpoint(value) {
      return validBreakpoints.indexOf(value) !== -1;
    }

    function readBreakpointPreference() {
      try {
        var stored = global.localStorage.getItem(storageKey) || "";
        return isValidBreakpoint(stored) ? stored : "desktop";
      } catch (error) {
        return "desktop";
      }
    }

    function writeBreakpointPreference(value) {
      if (!isValidBreakpoint(value)) {
        return;
      }

      try {
        global.localStorage.setItem(storageKey, value);
      } catch (error) {
        // Storage is a convenience only; the preview still updates in-session.
      }
    }

    function syncButtons(value) {
      toggleRoots.forEach(function syncRoot(root) {
        root.querySelectorAll("[data-mc-studio-breakpoint-button]").forEach(function syncButton(button) {
          var selected = (button.getAttribute("data-mc-studio-breakpoint-button") || "") === value;
          button.setAttribute("aria-pressed", selected ? "true" : "false");
          button.classList.toggle("sg-button--primary", selected);
          button.classList.toggle("sg-button--secondary", !selected);
        });
      });
    }

    function applyMobileScale(canvas, viewport) {
      viewport.style.height = "";
      var availableWidth = canvas.offsetWidth || canvas.clientWidth || 390;
      var scale = Math.min(1, availableWidth / 390);
      viewport.style.transform = "scale(" + scale.toFixed(4) + ")";

      if (scale < 1) {
        var unscaledHeight = viewport.scrollHeight || viewport.getBoundingClientRect().height / scale;
        if (unscaledHeight > 0) {
          viewport.style.height = Math.ceil(unscaledHeight * scale) + "px";
        }
        return;
      }

      viewport.style.height = "";
    }

    function applyBreakpoint(value, persist) {
      var resolved = isValidBreakpoint(value) ? value : "desktop";

      canvases.forEach(function syncCanvas(canvas) {
        var viewport = canvas.querySelector("[data-mc-studio-preview-viewport]");
        canvas.setAttribute("data-breakpoint", resolved);
        if (!viewport) {
          return;
        }

        viewport.setAttribute("data-breakpoint", resolved);
        viewport.style.transform = "";
        viewport.style.height = "";

        if (resolved === "mobile") {
          applyMobileScale(canvas, viewport);
        }
      });

      syncButtons(resolved);
      if (persist) {
        writeBreakpointPreference(resolved);
      }
    }

    toggleRoots.forEach(function bindRoot(root) {
      root.querySelectorAll("[data-mc-studio-breakpoint-button]").forEach(function bindButton(button) {
        button.addEventListener("click", function onBreakpointClick() {
          applyBreakpoint(button.getAttribute("data-mc-studio-breakpoint-button") || "desktop", true);
        });
      });
    });

    global.addEventListener("resize", function onStudioPreviewResize() {
      canvases.forEach(function recompute(canvas) {
        if (canvas.getAttribute("data-breakpoint") === "mobile") {
          var viewport = canvas.querySelector("[data-mc-studio-preview-viewport]");
          if (viewport) {
            applyMobileScale(canvas, viewport);
          }
        }
      });
    });

    applyBreakpoint(readBreakpointPreference(), false);
  }

  function setupRepeatableEditors() {
    global.document.querySelectorAll("[data-mc-repeatable-group]").forEach(function bindGroup(group) {
      if (group.getAttribute("data-mc-repeatable-ready") === "true") {
        return;
      }
      group.setAttribute("data-mc-repeatable-ready", "true");

      var itemsRoot = group.querySelector("[data-mc-repeatable-items]");
      var template = group.querySelector("[data-mc-repeatable-template]");
      var addButton = group.querySelector("[data-mc-repeatable-add]");
      var status = group.querySelector("[data-mc-repeatable-status]");
      var minItems = Math.max(0, parseInt(group.getAttribute("data-mc-repeatable-min") || "0", 10) || 0);
      var maxItems = Math.max(minItems, parseInt(group.getAttribute("data-mc-repeatable-max") || "12", 10) || 12);
      var nextIndex = Math.max(0, parseInt(group.getAttribute("data-mc-repeatable-next-index") || "0", 10) || 0);

      if (!itemsRoot || !template || !addButton) {
        return;
      }

      function activeItems() {
        return Array.prototype.slice.call(itemsRoot.querySelectorAll("[data-mc-repeatable-item]"))
          .filter(function keepActive(item) {
            return item.getAttribute("data-mc-repeatable-removed") !== "true";
          });
      }

      function sync() {
        var items = activeItems();
        items.forEach(function syncItem(item, position) {
          var label = item.querySelector("[data-mc-repeatable-label]");
          var order = item.querySelector("[data-mc-repeatable-order]");
          var up = item.querySelector("[data-mc-repeatable-up]");
          var down = item.querySelector("[data-mc-repeatable-down]");
          var remove = item.querySelector("[data-mc-repeatable-remove]");
          if (label) {
            label.textContent = (label.getAttribute("data-mc-repeatable-base-label") || label.textContent.replace(/\s+\d+$/, "")) + " " + (position + 1);
            label.setAttribute("data-mc-repeatable-base-label", label.textContent.replace(/\s+\d+$/, ""));
          }
          if (order) {
            order.value = String(position);
          }
          if (up) {
            up.disabled = position === 0;
          }
          if (down) {
            down.disabled = position === items.length - 1;
          }
          if (remove) {
            remove.disabled = items.length <= minItems;
          }
        });
        addButton.disabled = items.length >= maxItems;
        if (status) {
          status.textContent = items.length + " of " + maxItems + " items";
        }
      }

      function bindItem(item) {
        if (item.getAttribute("data-mc-repeatable-item-ready") === "true") {
          return;
        }
        item.setAttribute("data-mc-repeatable-item-ready", "true");
        var remove = item.querySelector("[data-mc-repeatable-remove]");
        var up = item.querySelector("[data-mc-repeatable-up]");
        var down = item.querySelector("[data-mc-repeatable-down]");

        if (remove) {
          remove.addEventListener("click", function removeItem() {
            if (activeItems().length <= minItems) {
              return;
            }
            var removeInput = item.querySelector("[data-mc-repeatable-remove-input]");
            if (removeInput) {
              removeInput.value = "1";
            }
            item.setAttribute("data-mc-repeatable-removed", "true");
            item.hidden = true;
            sync();
          });
        }
        if (up) {
          up.addEventListener("click", function moveItemUp() {
            var items = activeItems();
            var position = items.indexOf(item);
            if (position > 0) {
              itemsRoot.insertBefore(item, items[position - 1]);
              sync();
            }
          });
        }
        if (down) {
          down.addEventListener("click", function moveItemDown() {
            var items = activeItems();
            var position = items.indexOf(item);
            if (position >= 0 && position < items.length - 1) {
              itemsRoot.insertBefore(items[position + 1], item);
              sync();
            }
          });
        }
      }

      activeItems().forEach(bindItem);
      addButton.addEventListener("click", function addItem() {
        if (activeItems().length >= maxItems) {
          return;
        }
        var wrapper = global.document.createElement("div");
        wrapper.innerHTML = template.innerHTML.replace(/__INDEX__/g, String(nextIndex));
        nextIndex += 1;
        group.setAttribute("data-mc-repeatable-next-index", String(nextIndex));
        var item = wrapper.querySelector("[data-mc-repeatable-item]");
        if (!item) {
          return;
        }
        itemsRoot.appendChild(item);
        bindItem(item);
        var firstControl = item.querySelector("input:not([type=hidden]), textarea, select");
        if (firstControl) {
          firstControl.focus();
        }
        sync();
      });
      sync();
    });
  }

  function setupShell() {
    var body = global.document.body;
    if (!body) {
      return;
    }

    var toggleButtons = global.document.querySelectorAll("[data-mc-shell-toggle]");
    toggleButtons.forEach(function bindToggle(button) {
      button.addEventListener("click", function onClick() {
        toggleRail(body);
      });
    });

    var links = global.document.querySelectorAll("[data-mc-shell-link]");
    links.forEach(function bindLink(link) {
      link.addEventListener("click", function onClick() {
        if (isMobileViewport()) {
          body.classList.remove("mc-shell--rail-open");
          syncToggleState(body);
        }
      });
    });

    global.addEventListener("resize", function onResize() {
      if (!isMobileViewport()) {
        body.classList.remove("mc-shell--rail-open");
        applyDesktopRailPreference(body);
      }
      syncToggleState(body);
    });

    setupShellAppearance(body);
    applyDesktopRailPreference(body);
    syncToggleState(body);
    setupRailReorder();
    setupRailBranches();
    setupAvatarMenus();
    setupNotificationMenus();
    setupAdminSidesheets();
    setupStandaloneRichtextToolbars();
    setupLiveInspectionFilters();
    setupSortableGrids();
    setupPageEditorTemplateWorkflow();
    setupPageEditorAbandonModal();
    setupPageEditorDeleteModal();
    setupVisualSectionEditor();
    setupRepeatableEditors();
    setupTemplateSectionPicker();
    setupTemplateSectionDragDrop();
    setupDashboardTabs();
    setupStudioBreakpointPreview();
  }

  onReady(setupShell);
})(window);
