(function () {
  'use strict';

  function initTemplateEditor(root) {
    if (!root) return;

    var buttons = Array.prototype.slice.call(root.querySelectorAll('[data-template-network]'));
    var panels = Array.prototype.slice.call(root.querySelectorAll('[data-template-panel]'));
    var tokenButtons = Array.prototype.slice.call(root.querySelectorAll('[data-template-token]'));
    var notice = root.querySelector('[data-template-editor-notice]');
    var activeNetwork = buttons.length ? buttons[0].getAttribute('data-template-network') : '';

    function activePanel() {
      for (var i = 0; i < panels.length; i++) {
        if (panels[i].getAttribute('data-template-panel') === activeNetwork) return panels[i];
      }
      return null;
    }

    function activeTextarea() {
      var panel = activePanel();
      return panel ? panel.querySelector('[data-template-textarea]') : null;
    }

    function setNotice(message) {
      if (!notice) return;
      notice.textContent = message || '';
      if (message) {
        window.setTimeout(function () {
          if (notice.textContent === message) notice.textContent = '';
        }, 3500);
      }
    }

    function updatePanel(panel) {
      if (!panel) return;
      var textarea = panel.querySelector('[data-template-textarea]');
      var count = panel.querySelector('[data-template-count]');
      var state = panel.querySelector('[data-template-state]');
      if (!textarea) return;

      var value = textarea.value || '';
      var defaultValue = panel.getAttribute('data-default-template') || '';
      if (count) count.textContent = String(value.length) + ' / 4000';
      if (state) {
        var isDefault = value.trim() === defaultValue.trim();
        state.textContent = isDefault ? (root.getAttribute('data-default-label') || 'Default') : (root.getAttribute('data-custom-label') || 'Customized');
        state.classList.toggle('is-default', isDefault);
        state.classList.toggle('is-custom', !isDefault);
      }
    }

    function activate(network) {
      activeNetwork = network;
      buttons.forEach(function (button) {
        var selected = button.getAttribute('data-template-network') === network;
        button.classList.toggle('is-active', selected);
        button.setAttribute('aria-selected', selected ? 'true' : 'false');
      });
      panels.forEach(function (panel) {
        var selected = panel.getAttribute('data-template-panel') === network;
        panel.hidden = !selected;
        panel.classList.toggle('is-active', selected);
      });
      var textarea = activeTextarea();
      if (textarea) window.setTimeout(function () { textarea.focus({ preventScroll: true }); }, 0);
    }

    buttons.forEach(function (button) {
      button.addEventListener('click', function () {
        activate(button.getAttribute('data-template-network') || '');
      });
    });

    tokenButtons.forEach(function (button) {
      button.addEventListener('click', function () {
        var textarea = activeTextarea();
        var token = button.getAttribute('data-template-token') || '';
        if (!textarea || !token) return;

        var start = typeof textarea.selectionStart === 'number' ? textarea.selectionStart : textarea.value.length;
        var end = typeof textarea.selectionEnd === 'number' ? textarea.selectionEnd : start;
        var before = textarea.value.slice(0, start);
        var after = textarea.value.slice(end);
        textarea.value = before + token + after;
        var cursor = start + token.length;
        textarea.focus();
        textarea.setSelectionRange(cursor, cursor);
        textarea.dispatchEvent(new Event('input', { bubbles: true }));
      });
    });

    panels.forEach(function (panel) {
      var textarea = panel.querySelector('[data-template-textarea]');
      var reset = panel.querySelector('[data-template-reset]');
      var copyAll = panel.querySelector('[data-template-copy-all]');

      if (textarea) {
        textarea.addEventListener('input', function () { updatePanel(panel); });
        updatePanel(panel);
      }

      if (reset) {
        reset.addEventListener('click', function () {
          if (!textarea) return;
          textarea.value = panel.getAttribute('data-default-template') || '';
          textarea.dispatchEvent(new Event('input', { bubbles: true }));
          textarea.focus();
          setNotice(root.getAttribute('data-reset-message') || '');
        });
      }

      if (copyAll) {
        copyAll.addEventListener('click', function () {
          if (!textarea) return;
          var confirmMessage = root.getAttribute('data-copy-confirm') || '';
          if (confirmMessage && !window.confirm(confirmMessage)) return;
          panels.forEach(function (otherPanel) {
            var otherTextarea = otherPanel.querySelector('[data-template-textarea]');
            if (!otherTextarea) return;
            otherTextarea.value = textarea.value;
            otherTextarea.dispatchEvent(new Event('input', { bubbles: true }));
          });
          setNotice(root.getAttribute('data-copy-message') || '');
        });
      }
    });
  }

  function boot() {
    Array.prototype.forEach.call(document.querySelectorAll('[data-calliope-template-editor]'), initTemplateEditor);
  }

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