(function () {
  'use strict';

  var doc = document;
  var body = doc.body;
  var wrapper = doc.querySelector('.wrapper');
  var sidebar = doc.querySelector('.sidebar-wrapper');
  var overlay = doc.querySelector('.overlay');
  var mobileToggle = doc.querySelector('.mobile-toggle-menu');
  var sidebarClose = doc.querySelector('.sidebar-close');
  var desktopToggle = doc.querySelector('.toggle-icon');
  var backToTop = doc.querySelector('.back-to-top');

  function isMobileLayout() {
    return window.matchMedia('(max-width: 1024px)').matches;
  }

  function setMenu(open) {
    if (!wrapper) return;
    if (open) {
      wrapper.classList.add('toggled');
      if (isMobileLayout()) body.classList.add('menu-open');
    } else {
      wrapper.classList.remove('toggled');
      body.classList.remove('menu-open');
    }
  }

  if (mobileToggle) {
    mobileToggle.addEventListener('click', function () {
      setMenu(!(wrapper && wrapper.classList.contains('toggled')));
    });
  }
  if (desktopToggle) {
    desktopToggle.addEventListener('click', function () {
      setMenu(!(wrapper && wrapper.classList.contains('toggled')));
    });
  }
  if (sidebarClose) sidebarClose.addEventListener('click', function () { setMenu(false); });
  if (overlay) overlay.addEventListener('click', function () { setMenu(false); });

  window.addEventListener('resize', function () {
    if (!isMobileLayout()) body.classList.remove('menu-open');
  }, { passive: true });

  function normalizePath(path) {
    var clean = String(path || '').split('?')[0].split('#')[0].replace(/\/+$/, '');
    return clean.substring(clean.lastIndexOf('/') + 1) || 'dashboard.php';
  }

  function markActiveNavigation() {
    var current = normalizePath(window.location.pathname);
    var aliases = {
      'revenda_clientes.php': 'users.php',
      'revenda_criar_cliente.php': 'users_create.php',
      'revendas_criar.php': 'revendas.php',
      'user.php': 'users.php'
    };
    current = aliases[current] || current;
    doc.querySelectorAll('#menu a[href]').forEach(function (link) {
      var href = link.getAttribute('href') || '';
      if (!href || href === 'javascript:;' || href.charAt(0) === '#') return;
      var target = aliases[normalizePath(href)] || normalizePath(href);
      if (target === current) {
        link.classList.add('active');
        var parentLi = link.closest('li');
        if (parentLi) parentLi.classList.add('mm-active');
        var parentList = link.closest('ul');
        if (parentList && parentList.id !== 'menu') {
          parentList.classList.add('mm-show');
          var groupLi = parentList.closest('li');
          if (groupLi) groupLi.classList.add('mm-active');
        }
      }
    });
  }

  function initializeMenu() {
    if (window.jQuery && window.jQuery.fn && window.jQuery.fn.metisMenu && doc.getElementById('menu')) {
      try {
        window.jQuery('#menu').metisMenu({ toggle: true });
      } catch (error) {
        console.warn('[panel] Falha ao inicializar menu:', error);
      }
    }
    markActiveNavigation();
  }

  function enhanceForms() {
    doc.querySelectorAll('input, select, textarea').forEach(function (field) {
      var type = String(field.getAttribute('type') || '').toLowerCase();
      if (['hidden', 'checkbox', 'radio', 'range', 'color'].indexOf(type) !== -1) return;
      if (field.tagName === 'SELECT') field.classList.add('form-select');
      else field.classList.add('form-control');
    });

    doc.querySelectorAll('button:not([class])').forEach(function (button) {
      button.classList.add('btn', 'btn-primary');
    });
  }

  function enhanceTables() {
    doc.querySelectorAll('table').forEach(function (table) {
      table.classList.add('table', 'align-middle');
      if (!table.closest('.table-responsive') && !table.closest('.dataTables_wrapper')) {
        var wrap = doc.createElement('div');
        wrap.className = 'table-responsive';
        table.parentNode.insertBefore(wrap, table);
        wrap.appendChild(table);
      }
    });
  }

  function initializeDataTables() {
    if (!window.jQuery || !window.jQuery.fn || !window.jQuery.fn.DataTable) return;
    window.jQuery('table#myTable').each(function () {
      if (window.jQuery.fn.dataTable.isDataTable(this)) return;
      try {
        window.jQuery(this).DataTable({
          order: [[0, 'desc']],
          pageLength: 25,
          autoWidth: false,
          responsive: false,
          language: {
            emptyTable: 'Nenhum registro encontrado',
            info: 'Mostrando _START_ até _END_ de _TOTAL_ registros',
            infoEmpty: 'Nenhum registro disponível',
            infoFiltered: '(filtrado de _MAX_ registros)',
            lengthMenu: 'Mostrar _MENU_ registros',
            loadingRecords: 'Carregando...',
            processing: 'Processando...',
            search: 'Buscar:',
            zeroRecords: 'Nenhum resultado encontrado',
            paginate: { first: 'Primeira', last: 'Última', next: 'Próxima', previous: 'Anterior' }
          }
        });
      } catch (error) {
        console.warn('[panel] Falha ao iniciar tabela:', error);
      }
    });
  }

  function initializeBackToTop() {
    if (!backToTop) return;
    function update() {
      backToTop.classList.toggle('show', window.scrollY > 320);
    }
    window.addEventListener('scroll', update, { passive: true });
    backToTop.addEventListener('click', function () {
      window.scrollTo({ top: 0, behavior: 'smooth' });
    });
    update();
  }

  function closeMenuAfterNavigation() {
    if (!sidebar) return;
    sidebar.addEventListener('click', function (event) {
      var link = event.target.closest('a[href]');
      if (!link || !isMobileLayout()) return;
      var href = link.getAttribute('href') || '';
      if (href && href !== 'javascript:;' && href.charAt(0) !== '#') setMenu(false);
    });
  }

  function protectWideContent() {
    doc.querySelectorAll('pre, .json-box').forEach(function (node) {
      node.style.maxWidth = '100%';
      node.style.overflowX = 'auto';
    });
  }

  function initializeTooltips() {
    if (!window.bootstrap || !window.bootstrap.Tooltip) return;
    doc.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function (element) {
      try { window.bootstrap.Tooltip.getOrCreateInstance(element); } catch (_) {}
    });
  }



  function initializeDeclarativeActions() {
    doc.addEventListener('click', function (event) {
      var copyButton = event.target.closest('[data-copy-target]');
      if (copyButton) {
        var target = doc.getElementById(copyButton.dataset.copyTarget || '');
        var text = target ? String(target.innerText || target.textContent || '').trim() : '';
        if (!text) {
          if (window.Swal) window.Swal.fire('Vazio', 'Nada para copiar.', 'warning');
          return;
        }
        if (!navigator.clipboard || !navigator.clipboard.writeText) {
          var helper = doc.createElement('textarea');
          helper.value = text; doc.body.appendChild(helper); helper.select(); doc.execCommand('copy'); helper.remove();
          if (window.Swal) window.Swal.fire('Copiado', (copyButton.dataset.copyLabel || 'Conteúdo') + ' copiado com sucesso.', 'success');
          return;
        }
        navigator.clipboard.writeText(text).then(function () {
          if (window.Swal) window.Swal.fire('Copiado', (copyButton.dataset.copyLabel || 'Conteúdo') + ' copiado com sucesso.', 'success');
        });
      }

      var modalTrigger = event.target.closest('[data-open-modal]');
      if (modalTrigger) {
        var modalElement = doc.getElementById(modalTrigger.dataset.openModal || '');
        if (modalElement && window.bootstrap && window.bootstrap.Modal) {
          window.bootstrap.Modal.getOrCreateInstance(modalElement).show();
        }
      }

      var confirmation = event.target.closest('[data-confirm]');
      if (confirmation && !window.confirm(confirmation.dataset.confirm || 'Confirmar esta ação?')) {
        event.preventDefault();
        event.stopImmediatePropagation();
      }
    });

    doc.addEventListener('submit', function (event) {
      var form = event.target.closest('[data-confirm-submit]');
      if (form && !window.confirm(form.dataset.confirmSubmit || 'Confirmar esta ação?')) {
        event.preventDefault();
      }
    });

    doc.addEventListener('keydown', function (event) {
      var trigger = event.target.closest('[data-open-modal][role="button"]');
      if (trigger && (event.key === 'Enter' || event.key === ' ')) {
        event.preventDefault(); trigger.click();
      }
    });

    doc.querySelectorAll('img[data-fallback-src], img[data-image-error]').forEach(function (image) {
      function handleError() {
        var fallback = image.dataset.fallbackSrc;
        if (fallback && image.dataset.fallbackApplied !== '1') { image.dataset.fallbackApplied = '1'; image.src = fallback; return; }
        if (image.dataset.imageError === 'show-next') {
          image.style.display = 'none';
          if (image.nextElementSibling) image.nextElementSibling.style.display = 'flex';
        } else if (image.dataset.imageError === 'invisible') {
          image.style.visibility = 'hidden';
        } else if (image.dataset.imageError === 'hide') {
          image.style.display = 'none';
        }
      }
      image.addEventListener('error', handleError);
      if (image.complete && image.naturalWidth === 0) handleError();
    });
  }

  function initialize() {
    initializeDeclarativeActions();
    initializeMenu();
    enhanceForms();
    enhanceTables();
    initializeDataTables();
    initializeBackToTop();
    closeMenuAfterNavigation();
    protectWideContent();
    initializeTooltips();
    body.classList.add('panel-ready');
  }

  if (doc.readyState === 'loading') doc.addEventListener('DOMContentLoaded', initialize);
  else initialize();
})();
