/*
 * Madar layers for Illustrator
 *
 * Illustrator opens every SVG with all its layers inside one "Layer 1". This script lifts them out,
 * so each Madar category (Buildings – Residential, Streets, Green space, Title, Legend …) becomes its
 * own top-level layer, in the same order. Empty "Layer 1" is removed.
 *
 * How to use: open the Madar SVG (or PDF) in Illustrator, then File → Scripts → Other Script… and pick
 * this file. You can also copy it into Illustrator's Scripts folder to have it in the File → Scripts menu.
 */
#target illustrator
(function () {
  if (app.documents.length === 0) {
    alert("Open a Madar SVG in Illustrator first, then run this script again.");
    return;
  }
  var doc = app.activeDocument;
  var moved = 0;
  // Go through the current top-level layers (from the bottom up, because the list changes as we move).
  for (var i = doc.layers.length - 1; i >= 0; i--) {
    var host = doc.layers[i];
    if (host.layers.length === 0) continue;
    var wasLocked = host.locked;
    host.locked = false;
    // Move each sublayer out, just above its old parent, keeping the order.
    while (host.layers.length > 0) {
      var sub = host.layers[0];
      sub.move(host, ElementPlacement.PLACEBEFORE);
      moved++;
    }
    if (host.pageItems.length === 0) host.remove(); else host.locked = wasLocked;
  }
  alert(moved > 0 ? moved + " layers are now top-level layers." : "Nothing to change: the layers are already top-level.");
})();
