(function () {
  function initBrandingFieldset(fieldset) {
    initLogoPreview(fieldset);
    fieldset.querySelectorAll("[data-branding-color-row]").forEach(initColorRow);
    initLivePreview(fieldset);
    initNamePreview(fieldset);
  }

  function initLogoPreview(fieldset) {
    var fileInput = fieldset.querySelector("[data-branding-logo-file]");
    var previewImg = fieldset.querySelector("[data-branding-logo-img]");
    var placeholder = fieldset.querySelector("[data-branding-logo-placeholder]");
    if (!fileInput || !previewImg) return;

    fileInput.addEventListener("change", function () {
      var file = fileInput.files && fileInput.files[0];
      if (!file) return;

      var reader = new FileReader();
      reader.onload = function (e) {
        previewImg.src = e.target.result;
        previewImg.hidden = false;
        if (placeholder) placeholder.hidden = true;
        fieldset.dispatchEvent(new CustomEvent("branding:logochange", { bubbles: true }));
      };
      reader.readAsDataURL(file);
    });

    var urlInput = fieldset.querySelector(".branding-url-input");
    if (urlInput) {
      urlInput.addEventListener("change", function () {
        var url = urlInput.value.trim();
        if (!url) return;
        previewImg.src = url;
        previewImg.hidden = false;
        if (placeholder) placeholder.hidden = true;
        fieldset.dispatchEvent(new CustomEvent("branding:logochange", { bubbles: true }));
      });
    }
  }

  function initColorRow(row) {
    var picker = row.querySelector("[data-color-picker]");
    var hexInput = row.querySelector("[data-color-hex]");
    var swatch = row.querySelector("[data-color-swatch]");
    if (!picker || !hexInput) return;

    function applyColor(hex) {
      var normalized = normalizeHex(hex);
      if (!normalized) return;
      picker.value = normalized;
      hexInput.value = normalized;
      if (swatch) swatch.style.background = normalized;
      row.dispatchEvent(new CustomEvent("branding:colorchange", { bubbles: true }));
    }

    picker.addEventListener("input", function () {
      applyColor(picker.value);
    });

    hexInput.addEventListener("input", function () {
      var v = hexInput.value.trim();
      if (/^#[0-9A-Fa-f]{6}$/.test(v)) applyColor(v);
      else if (/^[0-9A-Fa-f]{6}$/.test(v)) applyColor("#" + v);
    });

    hexInput.addEventListener("blur", function () {
      applyColor(hexInput.value || picker.value);
    });

    row.querySelectorAll("[data-color-preset]").forEach(function (btn) {
      btn.addEventListener("click", function () {
        applyColor(btn.getAttribute("data-color-preset"));
      });
    });

    applyColor(picker.value || hexInput.value);
  }

  function initLivePreview(fieldset) {
    var card = fieldset.querySelector("[data-branding-live-preview]");
    if (!card) return;

    function refresh() {
      var primary = fieldset.querySelector('[data-branding-color-row="primary"] [data-color-picker]');
      var secondary = fieldset.querySelector('[data-branding-color-row="secondary"] [data-color-picker]');
      var logoImg = fieldset.querySelector("[data-branding-logo-img]");
      var header = card.querySelector("[data-preview-header]");
      var logoSlot = card.querySelector("[data-preview-logo]");

      if (header && primary && secondary) {
        header.style.setProperty("--preview-primary", primary.value);
        header.style.setProperty("--preview-secondary", secondary.value);
      }
      if (logoSlot && logoImg && !logoImg.hidden && logoImg.src && logoImg.src.indexOf("data:image/gif") === -1) {
        logoSlot.innerHTML =
          '<img src="' + logoImg.src + '" width="40" height="40" alt="" style="border-radius:8px;object-fit:contain">';
      }
    }

    fieldset.addEventListener("branding:colorchange", refresh);
    fieldset.addEventListener("branding:logochange", refresh);
    refresh();
  }

  function initNamePreview(fieldset) {
    var card = fieldset.querySelector("[data-branding-live-preview]");
    if (!card) return;
    var nameEl = card.querySelector(".branding-live-preview__name");
    var form = fieldset.closest("form");
    if (!nameEl || !form) return;

    var nameInput = form.querySelector("[name='club[name]'], [name='team[name]']");
    if (!nameInput) return;

    nameInput.addEventListener("input", function () {
      nameEl.textContent = nameInput.value.trim() || nameEl.textContent;
    });
  }

  function normalizeHex(value) {
    var v = (value || "").trim();
    if (/^[0-9A-Fa-f]{6}$/.test(v)) v = "#" + v;
    if (!/^#[0-9A-Fa-f]{6}$/.test(v)) return null;
    return v.toLowerCase();
  }

  document.querySelectorAll(".branding-fields").forEach(initBrandingFieldset);
})();
