
// pwa_event_controller.js - global event handlers and route-to-module hook loader
(function(){
  document.addEventListener('DOMContentLoaded', function(){
    // lazy-load module scripts when route activated
    window.addEventListener('hashchange', onRouteChange);
    function onRouteChange(){
      const r = location.hash.replace('#','').split('?')[0]||'dashboard';
      // map route to module file names
      const map = {
        'customers':'/pwa/pwa_customers.js',
        'customer':'/pwa/pwa_customer_view.js',
        'tasks':'/pwa/pwa_tasks.js',
        'task':'/pwa/pwa_tasks.js',
        'followups':'/pwa/pwa_followups.js',
        'dashboard':'/pwa/pwa_dashboard.js',
        'devices':'/pwa/modules/devices.js'
      };
      const src = map[r];
      if(!src) return;
      // if already loaded, call route handlers directly
      if(window[r==='customer'?'showCustomerFromHash': 'render'+r.charAt(0).toUpperCase()+r.slice(1)]) {
        // call direct function if available
        try { if(r==='customer') window.showCustomerFromHash(); else if(r==='followups') window.showFollowupsFromHash(); else if(r==='tasks') window.renderTasks(); else if(r==='customers') window.renderCustomers(); else if(r==='dashboard') window.loadDashboard(); } catch(e){}
        return;
      }
      // dynamically inject script
      var s = document.createElement('script'); s.src = src; s.onload = function(){
        try { if(r==='customer') window.showCustomerFromHash(); else if(r==='followups') window.showFollowupsFromHash(); else if(r==='tasks') window.renderTasks(); else if(r==='customers') window.renderCustomers(); else if(r==='dashboard') window.loadDashboard(); }catch(e){ console.warn(e); }
      }; s.onerror = function(){ console.warn('Module load failed', src); };
      document.body.appendChild(s);
    }
    // initial route trigger
    onRouteChange();
  });
})();