/*
 * Content Builder — block editor (vanilla JS, no build step).
 *
 * Reads the palette from window.CB_PALETTE (printed by post-edit.php),
 * keeps an in-memory layout array, and serializes it into #cb-layout on
 * every change so a normal form POST carries the JSON.
 *
 * Supports: add, reorder (up/down), edit fields, delete, and one level of
 * nesting for the "columns" block (each column holds its own blocks).
 */
(function () {
  "use strict";

  var PALETTE = window.CB_PALETTE || {};
  var layoutInput = document.getElementById("cb-layout");
  var canvas = document.getElementById("cb-canvas");
  var palette = document.getElementById("cb-palette");
  if (!layoutInput || !canvas || !palette) return;

  var layout;
  try { layout = JSON.parse(layoutInput.value || "[]"); }
  catch (e) { layout = []; }
  if (!Array.isArray(layout)) layout = [];

  function sync() {
    layoutInput.value = JSON.stringify(layout);
    paint();
  }

  function defaults(type) {
    var d = (PALETTE[type] && PALETTE[type].defaults) || {};
    return JSON.parse(JSON.stringify(d));
  }

  function addBlock(type, list) {
    list.push({ type: type, props: defaults(type) });
    sync();
  }

  function move(list, from, to) {
    if (to < 0 || to >= list.length) return;
    var b = list.splice(from, 1)[0];
    list.splice(to, 0, b);
    sync();
  }

  function remove(list, i) { list.splice(i, 1); sync(); }

  // ---- Palette ----
  // Per-block-type icon (inline SVG paths) + short description for the palette.
  var BLOCK_ICONS = {
    heading:   '<path d="M6 4v16M18 4v16M6 12h12"/>',
    paragraph: '<path d="M4 6h16M4 12h16M4 18h10"/>',
    image:     '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="M21 15l-5-5L5 21"/>',
    button:    '<rect x="3" y="8" width="18" height="8" rx="4"/>',
    columns:   '<rect x="3" y="4" width="7" height="16"/><rect x="14" y="4" width="7" height="16"/>',
    html:      '<path d="M8 9l-3 3 3 3M16 9l3 3-3 3M13 6l-2 12"/>',
    "post-list": '<path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>',
    hero:      '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 14h18M8 9h5"/>',
    "icon-grid": '<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/>',
    "image-grid": '<rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/>',
    cta:       '<rect x="3" y="6" width="18" height="12" rx="2"/><path d="M9 12h6"/>',
    testimonial: '<path d="M7 8h6a2 2 0 012 2v3a2 2 0 01-2 2H9l-3 3v-3a2 2 0 01-2-2v-3"/>',
  };

  function buildPalette() {
    var groups = {};
    Object.keys(PALETTE).forEach(function (type) {
      var g = PALETTE[type].group || "Content";
      (groups[g] = groups[g] || []).push(type);
    });
    palette.innerHTML = "";
    Object.keys(groups).forEach(function (g) {
      var wrap = document.createElement("div");
      wrap.className = "cb-palette-group";
      wrap.innerHTML = '<span class="cb-palette-label">' + esc(g) + "</span>";
      var tiles = document.createElement("div");
      tiles.className = "cb-palette-tiles";
      groups[g].forEach(function (type) {
        var icon = BLOCK_ICONS[type] || BLOCK_ICONS.paragraph;
        var btn = document.createElement("button");
        btn.type = "button";
        btn.className = "cb-tile";
        btn.title = "Add " + (PALETTE[type].label || type);
        btn.innerHTML =
          '<span class="cb-tile-icon"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" ' +
          'stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" width="20" height="20">' +
          icon + '</svg></span>' +
          '<span class="cb-tile-label">' + esc(PALETTE[type].label || type) + '</span>';
        btn.addEventListener("click", function () { addBlock(type, layout); });
        tiles.appendChild(btn);
      });
      wrap.appendChild(tiles);
      palette.appendChild(wrap);
    });
  }

  // ---- Canvas ----
  function paint() {
    canvas.innerHTML = "";
    if (!layout.length) {
      canvas.innerHTML = '<div class="cb-canvas-empty">No blocks yet. Add one above.</div>';
      return;
    }
    layout.forEach(function (block, i) {
      canvas.appendChild(renderCard(block, layout, i));
    });
  }

  function renderCard(block, list, i) {
    var def = PALETTE[block.type] || { label: block.type, fields: [] };
    var card = document.createElement("div");
    card.className = "cb-block";

    var head = document.createElement("div");
    head.className = "cb-block-head";
    head.innerHTML =
      '<span class="cb-block-type">' + esc(def.label || block.type) + "</span>";

    var controls = document.createElement("div");
    controls.className = "cb-block-controls";
    controls.appendChild(iconBtn("↑", function () { move(list, i, i - 1); }));
    controls.appendChild(iconBtn("↓", function () { move(list, i, i + 1); }));
    controls.appendChild(iconBtn("✕", function () { remove(list, i); }, "cb-danger"));
    head.appendChild(controls);
    card.appendChild(head);

    var body = document.createElement("div");
    body.className = "cb-block-body";

    if (def.nest) {
      body.appendChild(renderColumns(block));
    } else {
      (def.fields || []).forEach(function (f) {
        body.appendChild(renderField(block, f));
      });
    }
    card.appendChild(body);
    return card;
  }

  function renderColumns(block) {
    if (!block.props) block.props = { cols: [{ blocks: [] }, { blocks: [] }] };
    if (!Array.isArray(block.props.cols)) block.props.cols = [{ blocks: [] }, { blocks: [] }];
    var wrap = document.createElement("div");
    wrap.className = "cb-cols-editor";
    block.props.cols.forEach(function (col, ci) {
      if (!Array.isArray(col.blocks)) col.blocks = [];
      var colEl = document.createElement("div");
      colEl.className = "cb-col-editor";
      colEl.innerHTML = '<div class="cb-col-label">Column ' + (ci + 1) + "</div>";
      col.blocks.forEach(function (b, bi) {
        colEl.appendChild(renderCard(b, col.blocks, bi));
      });
      var add = document.createElement("select");
      add.className = "cb-col-add";
      add.innerHTML = '<option value="">+ add block…</option>' +
        Object.keys(PALETTE)
          .filter(function (t) { return !PALETTE[t].nest; }) // no columns-in-columns
          .map(function (t) { return '<option value="' + t + '">' + esc(PALETTE[t].label) + "</option>"; })
          .join("");
      add.addEventListener("change", function () {
        if (add.value) { addBlock(add.value, col.blocks); }
      });
      colEl.appendChild(add);
      wrap.appendChild(colEl);
    });
    return wrap;
  }

  function renderField(block, f) {
    if (!block.props) block.props = {};

    // Repeater: an editable list of sub-item objects (icon-grid, image-grid).
    if (f.type === "repeater") {
      return renderRepeater(block, f);
    }

    var field = document.createElement("div");
    field.className = "cb-field";
    var id = "f_" + Math.random().toString(36).slice(2);
    field.innerHTML = '<label class="cb-field-label" for="' + id + '">' + esc(f.label || f.key) + "</label>";

    var input;
    if (f.type === "textarea") {
      input = document.createElement("textarea");
      input.rows = 3;
    } else if (f.type === "select") {
      input = document.createElement("select");
      (f.options || []).forEach(function (o) {
        var opt = document.createElement("option");
        opt.value = o.v; opt.textContent = o.l;
        input.appendChild(opt);
      });
    } else {
      input = document.createElement("input");
      input.type = "text";
    }
    input.id = id;
    input.className = "cb-field-input";
    if (f.placeholder) input.placeholder = f.placeholder;
    input.value = block.props[f.key] != null ? block.props[f.key] : "";
    input.addEventListener("input", function () {
      block.props[f.key] = input.value;
      layoutInput.value = JSON.stringify(layout); // live sync, no repaint (keeps focus)
    });
    field.appendChild(input);

    // Image fields get a "Choose from library" button + thumbnail preview,
    // but only if the Media Library plugin exposed its MediaPicker global.
    if (f.type === "image") {
      var hasPicker = (window.CB_HAS_MEDIA === true);
      var preview = document.createElement("div");
      preview.className = "cb-img-preview";
      var refreshPreview = function () {
        var v = input.value || "";
        preview.innerHTML = v ? '<img src="' + esc(v) + '" alt="">' : "";
      };
      refreshPreview();
      input.addEventListener("input", refreshPreview);

      if (hasPicker) {
        var pick = document.createElement("button");
        pick.type = "button";
        pick.className = "cb-icon-btn";
        pick.style.width = "auto";
        pick.style.padding = "0 .6rem";
        pick.textContent = "Choose from library";
        pick.addEventListener("click", function () {
          if (!window.MediaPicker || typeof window.MediaPicker.open !== "function") {
            alert("Media library is still loading — try again in a moment.");
            return;
          }
          window.MediaPicker.open({
            mode: "single",
            onPick: function (path) {
              input.value = path;
              block.props[f.key] = path;
              layoutInput.value = JSON.stringify(layout);
              refreshPreview();
            }
          });
        });
        var row = document.createElement("div");
        row.className = "cb-img-actions";
        row.appendChild(pick);
        field.appendChild(row);
      }
      field.appendChild(preview);
    }
    return field;
  }

  function renderRepeater(block, f) {
    if (!Array.isArray(block.props[f.key])) block.props[f.key] = [];
    var list = block.props[f.key];
    var wrap = document.createElement("div");
    wrap.className = "cb-field";
    wrap.innerHTML = '<label class="cb-field-label">' + esc(f.label || f.key) + "</label>";

    var container = document.createElement("div");
    container.className = "cb-repeater";

    function repaintRepeater() {
      container.innerHTML = "";
      list.forEach(function (item, idx) {
        var card = document.createElement("div");
        card.className = "cb-repeater-item";
        var head = document.createElement("div");
        head.className = "cb-repeater-head";
        head.innerHTML = '<span>#' + (idx + 1) + "</span>";
        var ctr = document.createElement("div");
        ctr.appendChild(iconBtn("↑", function () { if (idx>0){ list.splice(idx-1,0,list.splice(idx,1)[0]); sync(); } }));
        ctr.appendChild(iconBtn("↓", function () { if (idx<list.length-1){ list.splice(idx+1,0,list.splice(idx,1)[0]); sync(); } }));
        ctr.appendChild(iconBtn("✕", function () { list.splice(idx,1); sync(); }, "cb-danger"));
        head.appendChild(ctr);
        card.appendChild(head);
        (f.item || []).forEach(function (sub) {
          card.appendChild(renderField({ props: item }, sub));
        });
        container.appendChild(card);
      });
    }

    repaintRepeater();
    wrap.appendChild(container);

    var add = document.createElement("button");
    add.type = "button";
    add.className = "cb-icon-btn";
    add.style.width = "auto";
    add.style.padding = "0 .6rem";
    add.style.marginTop = ".4rem";
    add.textContent = "+ Add item";
    add.addEventListener("click", function () {
      var blank = {};
      (f.item || []).forEach(function (sub) { blank[sub.key] = ""; });
      list.push(blank);
      sync();
    });
    wrap.appendChild(add);
    return wrap;
  }

  function iconBtn(label, fn, cls) {
    var b = document.createElement("button");
    b.type = "button";
    b.className = "cb-icon-btn" + (cls ? " " + cls : "");
    b.textContent = label;
    b.addEventListener("click", fn);
    return b;
  }

  function esc(s) {
    return String(s).replace(/[&<>"']/g, function (c) {
      return { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c];
    });
  }

  // Auto-fill slug from title if slug is empty.
  var title = document.getElementById("title");
  var slug = document.getElementById("slug");
  if (title && slug) {
    title.addEventListener("blur", function () {
      if (!slug.value.trim() && title.value.trim()) {
        slug.value = title.value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
      }
    });
  }

  buildPalette();
  paint();
})();
