(function () {
  "use strict";

  var BRAND = "EduLovable";
  var ready = false;

  function bodyEl() {
    return document.getElementById("sp-body");
  }

  function hasRealUi() {
    return !!(
      document.getElementById("sp-license-input") ||
      document.getElementById("sp-msg") ||
      document.querySelector(".sp-profile-card")
    );
  }

  function licenseFallback(message) {
    var body = bodyEl();
    if (!body || hasRealUi()) return;

    body.innerHTML =
      '<div class="sp-license-gate lc-boot-fallback">' +
        '<img class="sp-login-logo" src="images/logo_vertical_white.png" alt="' + BRAND + '">' +
        '<p class="sp-gate-title">Bem-vindo &agrave; <span data-ts-brand="name">' + BRAND + '</span></p>' +
        '<p class="sp-gate-desc">Insira sua chave de licen&ccedil;a para desbloquear.</p>' +
        '<input class="sp-input" id="sp-license-input" placeholder="TS-XXXXXXXXXXXXXXXXXXXX" spellcheck="false">' +
        '<button class="sp-btn-primary" id="sp-validate-btn">Validar Licença</button>' +
        '<div class="sp-log sp-log-error" id="sp-license-log">' + (message || "") + '</div>' +
      '</div>';

    var btn = document.getElementById("sp-validate-btn");
    if (btn) {
      btn.addEventListener("click", function () {
        if (typeof window.LC_VALIDATE_LICENSE === "function") {
          window.LC_VALIDATE_LICENSE();
        } else {
          var log = document.getElementById("sp-license-log");
          if (log) log.textContent = "O painel ainda está carregando. Recarregue a extensão e tente novamente.";
        }
      });
    }
  }

  function markReady() {
    ready = true;
  }

  function recover(reason) {
    if (ready || hasRealUi()) return;
    var message = reason ? "Erro ao carregar painel: " + String(reason).slice(0, 180) : "";
    licenseFallback(message);
  }

  window.LC_SIDE_PANEL_BOOT = {
    markReady: markReady,
    recover: recover
  };

  window.addEventListener("error", function (event) {
    setTimeout(function () {
      recover(event && (event.message || event.error));
    }, 0);
  });

  window.addEventListener("unhandledrejection", function (event) {
    setTimeout(function () {
      recover(event && event.reason);
    }, 0);
  });

  document.addEventListener("DOMContentLoaded", function () {
    setTimeout(function () { recover(); }, 900);
    setTimeout(function () { recover(); }, 2500);
  });
})();

