(function(){
  function showView(id){
    document.querySelectorAll('.view').forEach(v=>v.style.display='none');
    const el = document.getElementById('view_'+id);
    if (el) el.style.display='block';
  }

  async function route(){
    const raw = location.hash.replace('#','') || '';
    if (!raw){
      const role = (localStorage.getItem('role')||'').toLowerCase();
      if (role==='solardoot' || role==='captain' || role==='statehead') location.hash = '#dashboard';
      else if (role==='admin') { window.location.href='/AdminPanel/'; return; }
      else location.hash = '#dashboard';
      return;
    }
    const [route, qs] = raw.split('?');
    switch(route){
      case 'dashboard': showView('dashboard'); if (window.loadDashboard) window.loadDashboard(); break;
      case 'customers': showView('customers'); if (window.renderCustomers) window.renderCustomers(); break;
      case 'customer': showView('customer'); if (window.showCustomerFromHash) window.showCustomerFromHash(); break;
      case 'tasks': showView('tasks'); if (window.renderTasks) window.renderTasks(); break;
      case 'task': showView('task'); if (window.showTaskFromHash) window.showTaskFromHash(); break;
      case 'followups': showView('followups'); if (window.showFollowupsFromHash) window.showFollowupsFromHash(); break;
      case 'devices': showView('devices'); if (window.renderDevices) window.renderDevices(); break;
      default: break;
    }
  }

  window.addEventListener('hashchange', route);
  document.addEventListener('DOMContentLoaded', async function(){
    if (window.Auth && window.Auth.refreshToken){
      await window.Auth.refreshToken().catch(()=>{});
    }
    route();
  });
})();