(function() {
  var ROLE_NAMES = { owner: 'Владелец', engineer: 'Инженер', technician: 'Техник' };
  var EMOJIS = { owner: '👑', engineer: '🔧', technician: '🛠️' };

  function closeDropdown() {
    var dd = document.querySelector('.role-dropdown');
    if (dd) dd.classList.remove('open');
  }

  function switchRole(role) {
    closeDropdown();
    fetch('/service/api/role/switch', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ role: role })
    }).then(function(r) { return r.json() }).then(function(d) {
      if (d.ok) { window.location.reload(); }
    });
  }

  function resetRole() {
    closeDropdown();
    fetch('/service/api/role/reset', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' }
    }).then(function(r) { return r.json() }).then(function(d) {
      if (d.ok) { window.location.reload(); }
    });
  }

  // Close dropdown on outside click
  document.addEventListener('click', function(e) {
    var sw = document.querySelector('.role-switcher');
    if (sw && !sw.contains(e.target)) closeDropdown();
  });

  window.roleSwitcher = { switchRole: switchRole, resetRole: resetRole, ROLE_NAMES: ROLE_NAMES, EMOJIS: EMOJIS };
})();
