/**
 * Aura Builder — Templates admin (library, kits, design systems, wizard).
 */
(function () {
  "use strict";
  var CFG = window.AuraBuilderTemplates || {};
  var rest = (CFG.restUrl || "").replace(/\/$/, "");
  var nonce = CFG.nonce || "";
  var state = {
    tab: "kit",
    q: "",
    category: "",
    items: [],
    designSystems: [],
    importId: null,
  };

  var CAT_KIT = {
    business: "business-pro",
    education: "school-classic",
    school: "school-classic",
    blog: "blog-clean",
    news: "news-portal",
    landing: "landing-boost",
    restaurant: "restaurant-bistro",
    portfolio: "portfolio-studio",
    realestate: "real-estate",
  };

  function api(path, opts) {
    opts = opts || {};
    return fetch(rest + path, {
      method: opts.method || "GET",
      credentials: "same-origin",
      headers: {
        "Content-Type": "application/json",
        "X-WP-Nonce": nonce,
      },
      body: opts.body ? JSON.stringify(opts.body) : undefined,
    }).then(function (r) {
      return r.json().then(function (j) {
        if (!r.ok) throw new Error((j && j.message) || r.statusText || "Erro");
        return j;
      });
    });
  }

  function esc(s) {
    return String(s == null ? "" : s)
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;");
  }

  function iconFor(type) {
    if (type === "kit") return "K";
    if (type === "page") return "P";
    if (type === "header") return "H";
    if (type === "footer") return "F";
    if (type === "design") return "D";
    return "S";
  }

  function load() {
    var grid = document.getElementById("ab-tpl-grid");
    if (!grid) return;

    if (state.tab === "design") {
      grid.innerHTML = '<p class="ab-tpl-loading">Carregando design systems…</p>';
      api("/design-systems")
        .then(function (res) {
          state.designSystems = res.designSystems || [];
          renderDesign();
        })
        .catch(function (err) {
          grid.innerHTML =
            '<p class="ab-tpl-error">Falha: ' + esc(err.message) + "</p>";
        });
      return;
    }

    grid.innerHTML = '<p class="ab-tpl-loading">Carregando biblioteca…</p>';
    var qs = [];
    if (state.tab === "user") qs.push("source=user");
    else if (state.tab === "favorites") qs.push("favorites=1");
    else if (state.tab !== "all") qs.push("type=" + encodeURIComponent(state.tab));
    if (state.category) qs.push("category=" + encodeURIComponent(state.category));
    if (state.q) qs.push("q=" + encodeURIComponent(state.q));
    api("/templates" + (qs.length ? "?" + qs.join("&") : ""))
      .then(function (res) {
        state.items = res.templates || [];
        render();
      })
      .catch(function (err) {
        grid.innerHTML =
          '<p class="ab-tpl-error">Falha ao carregar: ' + esc(err.message) + "</p>";
      });
  }

  function renderDesign() {
    var grid = document.getElementById("ab-tpl-grid");
    if (!grid) return;
    var items = state.designSystems;
    if (!items.length) {
      grid.innerHTML = '<p class="ab-tpl-empty">Nenhum design system na pasta library.</p>';
      return;
    }
    grid.innerHTML = items
      .map(function (d) {
        var color = d.preview || "#7c3aed";
        return (
          '<article class="ab-tpl-card">' +
          '<div class="ab-tpl-card__thumb" style="background:' +
          esc(color) +
          ';color:#fff">Aa</div>' +
          '<div class="ab-tpl-card__body">' +
          '<h3 class="ab-tpl-card__name">' +
          esc(d.name || d.id) +
          "</h3>" +
          '<p class="ab-tpl-card__meta"><span class="ab-tpl-badge">Design</span><span>' +
          esc(d.category || "") +
          "</span></p>" +
          '<p class="ab-field-hint" style="margin:0;font-size:12px;color:#64748b">Troca cores/fontes sem apagar páginas.</p>' +
          '<div class="ab-tpl-card__actions">' +
          '<button type="button" class="button button-primary" data-apply-ds="' +
          esc(d.id) +
          '">Aplicar no site</button>' +
          "</div></div></article>"
        );
      })
      .join("");
    grid.querySelectorAll("[data-apply-ds]").forEach(function (btn) {
      btn.addEventListener("click", function () {
        var id = btn.getAttribute("data-apply-ds");
        if (!confirm("Aplicar o design “" + id + "”? O conteúdo das páginas não será apagado.")) return;
        btn.disabled = true;
        api("/design-systems/" + encodeURIComponent(id) + "/apply", { method: "POST", body: {} })
          .then(function (res) {
            alert(res.message || "Design aplicado.");
            btn.disabled = false;
          })
          .catch(function (err) {
            alert(err.message);
            btn.disabled = false;
          });
      });
    });
  }

  function render() {
    var grid = document.getElementById("ab-tpl-grid");
    if (!grid) return;
    var items = state.items.slice();
    if (!items.length) {
      grid.innerHTML =
        '<p class="ab-tpl-empty">Nenhum item nesta aba. Use o assistente ou salve templates pelo editor.</p>';
      return;
    }
    grid.innerHTML = items
      .map(function (t) {
        var type = t.type || "component";
        var src = t.source || "core";
        var isKit = type === "kit";
        var fav = !!t.favorite;
        var actions = "";
        if (isKit) {
          actions =
            '<button type="button" class="button button-primary" data-import-kit="' +
            esc(t.id) +
            '">Importar kit</button>';
        } else if (type === "header") {
          actions =
            '<a class="button button-primary" href="' +
            esc((CFG.admin || "admin.php") + "?page=aura-builder&mode=header") +
            '">Abrir Header</a>';
        } else if (type === "footer") {
          actions =
            '<a class="button button-primary" href="' +
            esc((CFG.admin || "admin.php") + "?page=aura-builder&mode=footer") +
            '">Abrir Footer</a>';
        } else {
          actions =
            '<a class="button button-primary" href="' +
            esc((CFG.admin || "admin.php") + "?page=aura-builder-pages") +
            '">Usar no editor</a>';
        }
        actions +=
          ' <button type="button" class="button" data-fav="' +
          esc(t.id) +
          '" title="Favorito">' +
          (fav ? "★" : "☆") +
          "</button>";
        if (src === "user") {
          actions +=
            ' <button type="button" class="button" data-delete="' +
            esc(t.id) +
            '">Excluir</button>';
        }
        var thumb = t.thumbnail || "";
        var previewKind = t.preview || type || "section";
        var letter = esc((t.name || "?").charAt(0).toUpperCase());
        var thumbHtml = thumb
          ? '<img class="ab-tpl-card__img" src="' +
            esc(thumb) +
            '" alt="' +
            esc(t.name || t.id) +
            '" loading="lazy" onerror="this.style.display=\'none\';var w=this.nextElementSibling;if(w)w.hidden=false;"/>' +
            '<div class="ab-tpl-wire ab-tpl-wire--' +
            esc(previewKind) +
            '" hidden aria-hidden="true"></div>'
          : '<div class="ab-tpl-wire ab-tpl-wire--' +
            esc(previewKind) +
            '" aria-hidden="true"></div>';
        return (
          '<article class="ab-tpl-card" data-id="' +
          esc(t.id) +
          '">' +
          '<div class="ab-tpl-card__thumb' +
          (isKit ? " ab-tpl-card__thumb--kit" : "") +
          (thumb ? " ab-tpl-card__thumb--img" : "") +
          '">' +
          thumbHtml +
          "</div>" +
          '<div class="ab-tpl-card__body">' +
          '<h3 class="ab-tpl-card__name">' +
          esc(t.name || t.id) +
          "</h3>" +
          '<p class="ab-tpl-card__meta">' +
          '<span class="ab-tpl-badge ab-tpl-badge--' +
          esc(src) +
          '">' +
          esc(src === "user" ? "Meu" : "Core") +
          "</span>" +
          "<span>" +
          esc(t.category || "geral") +
          "</span>" +
          (t.version ? "<span>v" + esc(t.version) + "</span>" : "") +
          (fav ? '<span class="ab-tpl-badge">★</span>' : "") +
          "</p>" +
          '<div class="ab-tpl-card__actions">' +
          actions +
          "</div></div></article>"
        );
      })
      .join("");

    grid.querySelectorAll("[data-import-kit]").forEach(function (btn) {
      btn.addEventListener("click", function () {
        openImportModal(btn.getAttribute("data-import-kit"));
      });
    });
    grid.querySelectorAll("[data-delete]").forEach(function (btn) {
      btn.addEventListener("click", function () {
        var id = btn.getAttribute("data-delete");
        if (!confirm("Excluir este template?")) return;
        api("/templates/" + encodeURIComponent(id), { method: "DELETE" })
          .then(function () {
            load();
          })
          .catch(function (err) {
            alert(err.message);
          });
      });
    });
    grid.querySelectorAll("[data-fav]").forEach(function (btn) {
      btn.addEventListener("click", function () {
        var id = btn.getAttribute("data-fav");
        api("/templates/" + encodeURIComponent(id) + "/favorite", {
          method: "POST",
          body: {},
        })
          .then(function () {
            load();
          })
          .catch(function (err) {
            alert(err.message);
          });
      });
    });
  }

  function openImportModal(kitId) {
    state.importId = kitId;
    var modal = document.getElementById("ab-tpl-modal");
    var title = document.getElementById("ab-tpl-modal-title");
    var desc = document.getElementById("ab-tpl-modal-desc");
    var body = document.getElementById("ab-tpl-modal-body");
    var status = document.getElementById("ab-tpl-modal-status");
    if (!modal || !body) return;
    title.textContent = "Importar Site Kit";
    desc.textContent =
      "Escolha o que aplicar. Single dinâmico (posts) é importado se o kit tiver o template.";
    status.hidden = true;
    status.textContent = "";
    body.innerHTML =
      '<label><input type="checkbox" name="globals" checked/> Cores e tipografia (Design System)</label>' +
      '<label><input type="checkbox" name="header" checked/> Header</label>' +
      '<label><input type="checkbox" name="footer" checked/> Footer</label>' +
      '<label><input type="checkbox" name="single" checked/> Single Post dinâmico</label>' +
      '<label><input type="checkbox" name="pages" checked/> Páginas do kit</label>' +
      '<label><input type="checkbox" name="set_home"/> Definir Home do kit como página inicial</label>';
    modal.hidden = false;
  }

  function closeModal() {
    var modal = document.getElementById("ab-tpl-modal");
    if (modal) modal.hidden = true;
    state.importId = null;
  }

  function confirmImport() {
    if (!state.importId) return;
    var body = document.getElementById("ab-tpl-modal-body");
    var status = document.getElementById("ab-tpl-modal-status");
    var confirmBtn = document.getElementById("ab-tpl-modal-confirm");
    var opts = {};
    body.querySelectorAll("input[type=checkbox]").forEach(function (inp) {
      opts[inp.name] = !!inp.checked;
    });
    if (confirmBtn) confirmBtn.disabled = true;
    status.hidden = false;
    status.className = "ab-tpl-modal__status";
    status.textContent = "Importando…";
    api("/kits/" + encodeURIComponent(state.importId) + "/import", {
      method: "POST",
      body: opts,
    })
      .then(function (res) {
        status.className = "ab-tpl-modal__status is-ok";
        var n = (res.pages || []).length;
        status.textContent =
          (res.message || "OK") +
          (n ? " · " + n + " página(s)" : "") +
          (res.header ? " · Header" : "") +
          (res.footer ? " · Footer" : "") +
          (res.single ? " · Single" : "");
        if (confirmBtn) confirmBtn.disabled = false;
      })
      .catch(function (err) {
        status.className = "ab-tpl-modal__status is-err";
        status.textContent = err.message || "Erro na importação";
        if (confirmBtn) confirmBtn.disabled = false;
      });
  }

  function openWizard() {
    var w = document.getElementById("ab-tpl-wizard");
    var st = document.getElementById("ab-tpl-wizard-status");
    if (st) {
      st.hidden = true;
      st.textContent = "";
    }
    if (w) w.hidden = false;
  }

  function closeWizard() {
    var w = document.getElementById("ab-tpl-wizard");
    if (w) w.hidden = true;
  }

  function runWizard() {
    var cat = (document.getElementById("ab-wiz-category") || {}).value || "business";
    var ds = (document.getElementById("ab-wiz-design") || {}).value || "";
    var name = (document.getElementById("ab-wiz-name") || {}).value || "";
    var setHome = !!(document.getElementById("ab-wiz-home") || {}).checked;
    var globals = !!(document.getElementById("ab-wiz-globals") || {}).checked;
    var status = document.getElementById("ab-tpl-wizard-status");
    var runBtn = document.getElementById("ab-tpl-wizard-run");
    var kitId = CAT_KIT[cat] || "business-pro";
    if (status) {
      status.hidden = false;
      status.className = "ab-tpl-modal__status";
      status.textContent = "Criando site com kit “" + kitId + "”…";
    }
    if (runBtn) runBtn.disabled = true;
    api("/site-wizard", {
      method: "POST",
      body: {
        kitId: kitId,
        category: cat,
        designSystem: ds,
        siteName: name,
        set_home: setHome,
        globals: globals,
        header: true,
        footer: true,
        pages: true,
        single: true,
      },
    })
      .then(function (res) {
        if (status) {
          status.className = "ab-tpl-modal__status is-ok";
          var n = (res.pages || []).length;
          status.textContent =
            (res.message || "OK") +
            (n ? " · " + n + " página(s) criadas." : "") +
            " Abra Páginas do Builder para editar.";
        }
        if (runBtn) runBtn.disabled = false;
      })
      .catch(function (err) {
        if (status) {
          status.className = "ab-tpl-modal__status is-err";
          status.textContent = err.message || "Erro no assistente";
        }
        if (runBtn) runBtn.disabled = false;
      });
  }

  function boot() {
    document.querySelectorAll(".ab-tpl-tab").forEach(function (tab) {
      tab.addEventListener("click", function () {
        document.querySelectorAll(".ab-tpl-tab").forEach(function (t) {
          t.classList.remove("is-active");
        });
        tab.classList.add("is-active");
        state.tab = tab.getAttribute("data-tab") || "kit";
        load();
      });
    });
    var search = document.getElementById("ab-tpl-search");
    var cat = document.getElementById("ab-tpl-category");
    var t;
    if (search) {
      search.addEventListener("input", function () {
        clearTimeout(t);
        t = setTimeout(function () {
          state.q = search.value.trim();
          load();
        }, 250);
      });
    }
    if (cat) {
      cat.addEventListener("change", function () {
        state.category = cat.value;
        load();
      });
    }
    var close = document.getElementById("ab-tpl-modal-close");
    var cancel = document.getElementById("ab-tpl-modal-cancel");
    var confirm = document.getElementById("ab-tpl-modal-confirm");
    if (close) close.addEventListener("click", closeModal);
    if (cancel) cancel.addEventListener("click", closeModal);
    if (confirm) confirm.addEventListener("click", confirmImport);

    var openW = document.getElementById("ab-tpl-open-wizard");
    var wClose = document.getElementById("ab-tpl-wizard-close");
    var wCancel = document.getElementById("ab-tpl-wizard-cancel");
    var wRun = document.getElementById("ab-tpl-wizard-run");
    if (openW) openW.addEventListener("click", openWizard);
    if (wClose) wClose.addEventListener("click", closeWizard);
    if (wCancel) wCancel.addEventListener("click", closeWizard);
    if (wRun) wRun.addEventListener("click", runWizard);

    load();
  }

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