(function () {
  'use strict';

  function icons() {
    if (typeof lucide !== 'undefined') {
      lucide.createIcons({ attrs: { 'stroke-width': 1.75 } });
    }
  }

  function toast(msg, type) {
    type = type || 'ok';
    var stack = document.getElementById('toastStack');
    if (!stack) {
      stack = document.createElement('div');
      stack.id = 'toastStack';
      stack.className = 'toast-stack';
      document.body.appendChild(stack);
    }
    var el = document.createElement('div');
    el.className = 'toast ' + type;
    el.textContent = msg;
    stack.appendChild(el);
    setTimeout(function () {
      el.classList.add('hide');
      setTimeout(function () { el.remove(); }, 320);
    }, 3800);
  }

  function sidebar() {
    var btn = document.getElementById('menuBtn');
    var sidebar = document.getElementById('sidebar');
    var backdrop = document.getElementById('backdrop');
    if (!btn || !sidebar) return;

    function close() {
      sidebar.classList.remove('open');
      if (backdrop) backdrop.classList.remove('show');
    }

    function toggle() {
      sidebar.classList.toggle('open');
      if (backdrop) backdrop.classList.toggle('show');
    }

    btn.addEventListener('click', toggle);
    if (backdrop) backdrop.addEventListener('click', close);
  }

  function copyButtons() {
    document.querySelectorAll('[data-copy]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        var text = btn.getAttribute('data-copy') || '';
        if (!text) return;
        navigator.clipboard.writeText(text).then(function () {
          toast('Copiado', 'ok');
        }).catch(function () {
          toast('Não foi possível copiar', 'bad');
        });
      });
    });
  }

  function confirmLinks() {
    document.querySelectorAll('[data-confirm]').forEach(function (el) {
      el.addEventListener('click', function (e) {
        var msg = el.getAttribute('data-confirm') || 'Confirmar?';
        if (!confirm(msg)) e.preventDefault();
      });
    });
  }

  function flashFromServer() {
    if (window.__FLASH__ && window.__FLASH__.msg) {
      toast(window.__FLASH__.msg, window.__FLASH__.type || 'ok');
    }
  }

  document.addEventListener('DOMContentLoaded', function () {
    icons();
    sidebar();
    copyButtons();
    confirmLinks();
    flashFromServer();
  });
})();
