
function applyTheme(cfg) {
  const root = document.documentElement;
  if (cfg.color_primario) {
    root.style.setProperty('--hi-vis',      cfg.color_primario);
    root.style.setProperty('--hi-vis-deep', darkenHex(cfg.color_primario, 24));
  }
  if (cfg.color_acento) {
    root.style.setProperty('--signal',      cfg.color_acento);
    root.style.setProperty('--signal-deep', darkenHex(cfg.color_acento, 20));
  }
  if (cfg.color_sidebar) {
    root.style.setProperty('--sidebar-bg', cfg.color_sidebar);
  }
}

function darkenHex(hex, amount) {
  const n = parseInt((hex || '').replace('#', ''), 16);
  if (isNaN(n)) return hex;
  const r = Math.max(0, (n >> 16) - amount);
  const g = Math.max(0, ((n >> 8) & 0xff) - amount);
  const b = Math.max(0, (n & 0xff) - amount);
  return '#' + [r, g, b].map(v => v.toString(16).padStart(2, '0')).join('');
}
window.darkenHex = darkenHex;

function App() {
  const [screen, setScreen] = React.useState('login');
  const [modal, setModal] = React.useState(null);
  const [installState, setInstallState] = React.useState('checking'); // checking | needsSetup | ready

  const [, setPermsV] = React.useState(0);

  React.useEffect(() => {
    fetch('/api/config/apariencia')
      .then(r => r.ok ? r.json() : {})
      .then(cfg => { applyTheme(cfg); window._appConfig = cfg; })
      .catch(() => {});

    // Refrescar permisos del rol al cargar — los cambios hechos en el panel
    // de Roles y permisos se reflejan en la próxima recarga. El bump de
    // estado re-renderiza sidebar/botones con el mapa fresco.
    if (window.DesasfAPI && DesasfAPI.isLoggedIn()) {
      DesasfAPI.refreshPermisos()
        .then(() => setPermsV(v => v + 1))
        .catch(() => {});
    }

    fetch('/api/install/status')
      .then(r => r.ok ? r.json() : { needsSetup: false })
      .then(s => setInstallState(s.needsSetup ? 'needsSetup' : 'ready'))
      .catch(() => setInstallState('ready'));
  }, []);

  React.useEffect(() => {
    if (window.DesasfAPI && DesasfAPI.isLoggedIn() && screen === 'login') {
      const user = DesasfAPI.getCurrentUser();
      if (user?.rol === 'cliente')             setScreen('cliente-final');
      else if (user?.rol === 'conductor')      setScreen('logistica-conductor');
      else                                      setScreen('dashboard');
    }
    window._desasfNavigate = (id, data) => {
      if (data) {
        if (data.solicitudId) window._desasfCurrentSolicitud = data.solicitudId;
        if (data.pagoId)      window._desasfCurrentPago      = data.pagoId;
        if (data.clienteId)   window._desasfCurrentCliente   = data.clienteId;
        if (data.productoId)  window._desasfCurrentProducto  = data.productoId;
      }
      setScreen(id);
      setModal(null);
    };
    window._desasfOpenModal = (id, data) => {
      if (data) {
        if (data.pagoId)       window._desasfCurrentPago       = data.pagoId;
        if (data.solicitudId)  window._desasfCurrentSolicitud  = data.solicitudId;
        if (data.productoId)   window._desasfCurrentProducto   = data.productoId;
      }
      setModal(id);
    };
    window._desasfCloseModal = () => setModal(null);
    window._desasfLogout = () => {
      if (!confirm('¿Cerrar sesión?')) return;
      DesasfAPI.clearTokens();
      delete window._appConfig;
      setScreen('login');
      setModal(null);
    };
    return () => {
      delete window._desasfNavigate;
      delete window._desasfOpenModal;
      delete window._desasfCloseModal;
      delete window._desasfLogout;
    };
  }, []);

  const screens = {
    login:               Login,
    dashboard:           Dashboard,
    solicitudes:         ListaSolicitudes,
    'solicitud-detalle': DetalleSolicitud,
    clientes:            GestionClientes,
    'clientes-detalle':  DetalleCliente,
    'gestion-clientes':  GestionClientes,
    pagos:               Pagos,
    catalogo:            Catalogo,
    reportes:            Reportes,
    fuerza:              FuerzaVentas,
    ayuda:               CentroAyuda,
    auditoria:           Auditoria,
    config:              Configuracion,
    revisor:             VistaRevisor,
    catalogador:         VistaCatalogador,
    logistica:           VistaLogistica,
    'logistica-conductor': VistaConductor,
    'logistica-cliente':   VistaClienteDespacho,
    'cliente-final':       ClienteFinal,
    'mi-vendedor':         MiVendedor,
    'mis-documentos':      MisDocumentos,
    'mi-cuenta':           MiCuenta,
  };

  const modals = {
    'nueva-solicitud':   ModalNuevaSolicitud,
    'validar-voucher':   ModalValidarVoucher,
    'subir-voucher':     ModalSubirVoucher,
    'producto-detalle':  ModalProductoDetalle,
  };

  if (installState === 'checking') {
    return React.createElement('div', {
      style: { display: 'grid', placeItems: 'center', height: '100vh', color: 'var(--ink-5)', fontSize: 13 }
    }, 'Cargando…');
  }
  if (installState === 'needsSetup') {
    return React.createElement(window.WelcomeWizard);
  }

  const Screen = screens[screen] || Dashboard;
  const Modal = modal ? modals[modal] : null;

  return React.createElement(React.Fragment, null,
    React.createElement(Screen),
    Modal && React.createElement('div', {
      className: 'modal-overlay',
      onClick: (e) => { if (e.target === e.currentTarget) setModal(null); }
    }, React.createElement(Modal))
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(App));
