
function VencidosPage(props) {
  var initialData = props && props.initialData ? props.initialData : {};
  window.__VENCIDOS_API_BASE = initialData.api_base || window.__VENCIDOS_API_BASE || 'https://andys.com.bo/vencidos/api';
  window.__VENCIDOS_BOOTSTRAP = initialData.bootstrap || {};
  window.__VENCIDOS_FLAGS_URL = initialData.flags_url || window.__VENCIDOS_FLAGS_URL || '';
  var asset = props ? props.asset : null;
  var api = props ? props.api : null;

  var currentUserState = React.useState(null);
  var currentUser = currentUserState[0];
  var setCurrentUser = currentUserState[1];

  var currentViewState = React.useState(null);
  var currentView = currentViewState[0];
  var setCurrentView = currentViewState[1];

  var apiReadyState = React.useState(false);
  var apiReady = apiReadyState[0];
  var setApiReady = apiReadyState[1];

  var apiErrorState = React.useState('');
  var apiError = apiErrorState[0];
  var setApiError = apiErrorState[1];

  var themeState = React.useState('dark');
  var theme = themeState[0];
  var setTheme = themeState[1];

  var style = 'cristal';

  var roleViews = {
    sala: ['registro', 'catalogo', 'historial', 'tabla'],
    supervisor: ['dashboard', 'registro', 'tabla', 'consolidado', 'catalogo', 'auditoria', 'usuarios', 'sincronizacion'],
    admin: ['dashboard', 'registro', 'tabla', 'consolidado', 'catalogo', 'auditoria', 'usuarios', 'sincronizacion']
  };

  var getHomeView = React.useCallback(function(user) {
    return user && user.role === 'sala' ? 'registro' : 'dashboard';
  }, []);

  var getViewKey = React.useCallback(function(user) {
    return 'vencidos_view_' + (user && user.id ? user.id : 'anon');
  }, []);

  var isAllowed = React.useCallback(function(user, view) {
    if (!user || !view) return false;
    var views = roleViews[user.role] || roleViews.sala;
    return views.indexOf(view) !== -1;
  }, []);

  var resolveUser = React.useCallback(function(raw) {
    if (!raw) return null;
    var users = window.MOCK && window.MOCK.USERS ? window.MOCK.USERS : [];
    for (var i = 0; i < users.length; i += 1) {
      var user = users[i];
      if (raw.id && user.id === raw.id) return user;
      if (raw.username && (user.username || '').toLowerCase() === String(raw.username).toLowerCase()) return user;
    }
    return raw;
  }, []);

  var activateUser = React.useCallback(function(rawUser) {
    var user = resolveUser(rawUser);
    if (!user || user.active === false) return false;

    setCurrentUser(user);

    var nextView = getHomeView(user);
    try {
      var savedView = localStorage.getItem(getViewKey(user));
      if (isAllowed(user, savedView)) nextView = savedView;
      localStorage.setItem('vencidos_user', JSON.stringify(user));
    } catch (e) {}

    setCurrentView(nextView);
    return true;
  }, [resolveUser, getHomeView, getViewKey, isAllowed]);

  React.useEffect(function() {
    document.documentElement.dataset.theme = theme;
    document.documentElement.dataset.style = style;
  }, [theme]);

  React.useEffect(function() {
    Promise.resolve()
      .then(function() {
        return window.MOCK.initFromAPI();
      })
      .then(function() {
        if (window.MOCK.startAutoSync) window.MOCK.startAutoSync(5000);
        setApiReady(true);

        if (activateUser(initialData.odoo_user)) return;

        try {
          var saved = localStorage.getItem('vencidos_user');
          if (saved) activateUser(JSON.parse(saved));
        } catch (e) {}
      })
      .catch(function(err) {
        setApiReady(true);
        setApiError('No se puede conectar con el servidor.');
        console.error('Vencidos init error', err);
      });
  }, [activateUser]);

  React.useEffect(function() {
    var versionUrl = (initialData && initialData.version_url) || '/mcp/webapp/33/api/version';
    var baseline = (initialData && initialData.build_version) || null;
    var reloading = false;
    function check() {
      fetch(versionUrl, { headers: { 'Accept': 'application/json' }, cache: 'no-store', credentials: 'include' })
        .then(function(r) { return r.ok ? r.json() : null; })
        .then(function(d) {
          if (!d || !d.version) return;
          if (baseline === null) { baseline = d.version; return; }
          if (d.version !== baseline && !reloading) {
            reloading = true;
            window.location.reload();
          }
        })
        .catch(function() {});
    }
    check();
    var timer = setInterval(check, 8000);
    return function() { clearInterval(timer); };
  }, []);

  var handleLogin = React.useCallback(function(user) {
    activateUser(user);
  }, [activateUser]);

  var handleNavigate = React.useCallback(function(view) {
    setCurrentView(view);
    if (!currentUser) return;
    try {
      localStorage.setItem(getViewKey(currentUser), view);
    } catch (e) {}
  }, [currentUser, getViewKey]);

  var handleLogout = React.useCallback(function() {
    setCurrentUser(null);
    setCurrentView(null);
    try {
      localStorage.removeItem('vencidos_user');
    } catch (e) {}
  }, []);

  var toggleTheme = React.useCallback(function() {
    setTheme(function(prev) {
      return prev === 'dark' ? 'light' : 'dark';
    });
  }, []);

  var renderView = React.useCallback(function() {
    if (!currentUser) return null;

    switch (currentView) {
      case 'registro':
        return React.createElement(SalaView, { user: currentUser, allowSucursalPick: currentUser.role !== 'sala' });
      case 'historial':
        return React.createElement(SalaHistorialView, { user: currentUser });
      case 'catalogo':
        return React.createElement(CatalogoView, { user: currentUser });
      case 'dashboard':
        return React.createElement(DashboardView, { role: currentUser.role, onNavigate: handleNavigate });
      case 'tabla':
        return React.createElement(DataTableView, null);
      case 'consolidado':
        return React.createElement(ConsolidadoView, null);
      case 'auditoria':
        return React.createElement(AuditView, null);
      case 'usuarios':
        return React.createElement(UsersView, null);
      case 'sincronizacion':
        return React.createElement(SyncStatusView, null);
      default:
        if (currentUser.role === 'sala') {
          return React.createElement(SalaView, { user: currentUser });
        }
        return React.createElement(DashboardView, { role: currentUser.role, onNavigate: handleNavigate });
    }
  }, [currentUser, currentView, handleNavigate]);

  if (!apiReady) {
    return React.createElement(
      'div',
      {
        style: {
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100vh',
          width: '100vw',
          background: theme === 'dark' ? '#09090B' : '#FAFAFA',
          color: theme === 'dark' ? '#A1A1AA' : '#71717A',
          fontFamily: 'sans-serif',
          flexDirection: 'column',
          gap: '12px'
        }
      },
      React.createElement('div', { style: { fontSize: '18px', fontWeight: '600' } }, 'Cargando Vencidos...'),
      apiError ? React.createElement('div', { style: { fontSize: '13px' } }, apiError) : null
    );
  }

  if (!currentUser) {
    return React.createElement(LoginScreen, {
      onLogin: handleLogin,
      style: style,
      theme: theme
    });
  }

  return React.createElement(
    AppShell,
    {
      user: currentUser,
      currentView: currentView,
      onNavigate: handleNavigate,
      onLogout: handleLogout,
      onToggleTheme: toggleTheme,
      theme: theme
    },
    renderView()
  );
}

window.VencidosPage = VencidosPage;
