/* main.jsx — Entry point con History API routing.

   Rutas reales en la URL:
     /              → login (sin sesion) o mis-citas (con sesion)
     /mis-citas     → EmployeeView
     /agendar       → PatientView
     /beneficiarios → BeneficiariesView
     /admin         → AdminView
     /doctor        → DoctorView

   El boton Atras del navegador funciona via popstate.
   ?design en la URL sigue montando el canvas de diseno. */

/* --- Mapa de vistas a paths -------------------------------------- */
const VIEWS = {
  LOGIN:         'login',
  EMPLOYEE:      'employee',
  PATIENT:       'patient',
  BENEFICIARIES: 'beneficiaries',
  DOCTOR:        'doctor',
  ADMIN:         'admin',
  RRHH:          'rrhh',
};

const VIEW_TO_PATH = {
  [VIEWS.LOGIN]:         '/',
  [VIEWS.EMPLOYEE]:      '/mis-citas',
  [VIEWS.PATIENT]:       '/agendar',
  [VIEWS.BENEFICIARIES]: '/beneficiarios',
  [VIEWS.DOCTOR]:        '/doctor',
  [VIEWS.ADMIN]:         '/admin',
  [VIEWS.RRHH]:          '/rrhh',
};

const PATH_TO_VIEW = {};
Object.entries(VIEW_TO_PATH).forEach(([v, p]) => { PATH_TO_VIEW[p] = v; });

function viewFromPath() {
  return PATH_TO_VIEW[window.location.pathname] || null;
}

/* --- App real con routing ---------------------------------------- */
function MainApp() {
  const [user, setUser]   = React.useState(null);
  const [view, setView]   = React.useState(VIEWS.LOGIN);
  const [ready, setReady] = React.useState(false);

  /* Navegar: actualiza estado + pushState */
  function navigate(v, replace) {
    const path = VIEW_TO_PATH[v] || '/';
    if (replace) {
      window.history.replaceState({ view: v }, '', path);
    } else {
      window.history.pushState({ view: v }, '', path);
    }
    setView(v);
  }

  /* Popstate: boton Atras del navegador */
  React.useEffect(() => {
    function onPop(e) {
      const v = e.state?.view || viewFromPath();
      if (v) setView(v);
    }
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  /* Al montar: verifica sesion activa (cookie valida) */
  React.useEffect(() => {
    window.apiFetch('/api/auth/me')
      .then(r => r.ok ? r.json() : null)
      .then(data => {
        if (data?.professional) {
          const u = { ...data.professional, type: 'professional' };
          setUser(u);
          /* Si la URL actual es valida para el profesional, respetarla */
          const urlView = viewFromPath();
          if (urlView === VIEWS.DOCTOR) {
            navigate(VIEWS.DOCTOR, true);
          } else {
            navigate(VIEWS.DOCTOR, true);
          }
        } else if (data?.employee) {
          setUser(data.employee);
          /* Respetar la URL si el empleado tiene permiso */
          const urlView = viewFromPath();
          const allowed = [VIEWS.EMPLOYEE, VIEWS.PATIENT, VIEWS.BENEFICIARIES];
          if (data.employee.role === 'admin') allowed.push(VIEWS.ADMIN);
          if (data.employee.role === 'rrhh' || data.employee.role === 'admin') allowed.push(VIEWS.RRHH);

          if (urlView && allowed.includes(urlView)) {
            navigate(urlView, true);
          } else {
            const defaultView = data.employee.role === 'admin' ? VIEWS.ADMIN
              : data.employee.role === 'rrhh' ? VIEWS.RRHH : VIEWS.EMPLOYEE;
            navigate(defaultView, true);
          }
        } else {
          navigate(VIEWS.LOGIN, true);
        }
      })
      .catch(() => { navigate(VIEWS.LOGIN, true); })
      .finally(() => setReady(true));
  }, []);

  function handleLogin(userData) {
    setUser(userData);
    if (userData.type === 'professional') {
      navigate(VIEWS.DOCTOR);
    } else if (userData.role === 'admin') {
      navigate(VIEWS.ADMIN);
    } else if (userData.role === 'rrhh') {
      navigate(VIEWS.RRHH);
    } else {
      navigate(VIEWS.EMPLOYEE);
    }
  }

  function handleLogout() {
    window.apiFetch('/api/auth/logout', { method: 'POST' })
      .finally(() => {
        setUser(null);
        navigate(VIEWS.LOGIN, true);
      });
  }

  /* Splash de carga mientras verifica sesion */
  if (!ready) {
    return (
      <div className="min-h-screen bg-midnight-950 grid place-items-center">
        <div className="flex flex-col items-center gap-4">
          <Logo tone="light" size="lg" />
          <div className="flex gap-1.5 mt-2">
            {[0,1,2].map(i => (
              <div key={i}
                className="h-1.5 w-1.5 rounded-full bg-mint-400 animate-bounce"
                style={{ animationDelay: `${i * 0.15}s` }}/>
            ))}
          </div>
        </div>
      </div>
    );
  }

  /* -- Vistas ---------------------------------------------------- */
  if (view === VIEWS.LOGIN) {
    return <LoginView onLogin={handleLogin} />;
  }

  /* Doctor: tiene su propio layout (sidebar), no usa TopNav */
  if (view === VIEWS.DOCTOR) {
    return <DoctorView user={user} onNavigate={navigate} onLogout={handleLogout} />;
  }

  /* RRHH: su propio sidebar */
  if (view === VIEWS.RRHH) {
    if (user?.role !== 'rrhh' && user?.role !== 'admin') {
      navigate(VIEWS.EMPLOYEE, true);
      return null;
    }
    return <RRHHView user={user} onNavigate={navigate} onLogout={handleLogout} />;
  }

  /* Admin: tiene su propio sidebar, pero necesita poder salir a vistas de empleado */
  if (view === VIEWS.ADMIN) {
    if (user?.role !== 'admin') {
      navigate(VIEWS.EMPLOYEE, true);
      return null;
    }
    return <AdminView user={user} onNavigate={navigate} onLogout={handleLogout} />;
  }

  /* Vistas de empleado: comparten TopNav */
  const viewContent = {
    [VIEWS.EMPLOYEE]:      <EmployeeView user={user} onNavigate={navigate} onLogout={handleLogout} />,
    [VIEWS.PATIENT]:       <PatientView user={user} onNavigate={navigate} onLogout={handleLogout} />,
    [VIEWS.BENEFICIARIES]: <BeneficiariesView user={user} onNavigate={navigate} onLogout={handleLogout} />,
  };

  return viewContent[view] || null;
}

/* --- Punto de montaje -------------------------------------------- */
const isDesignMode = new URLSearchParams(window.location.search).has('design');

if (isDesignMode) {
  ReactDOM.createRoot(document.getElementById('root')).render(<App />);
} else {
  ReactDOM.createRoot(document.getElementById('root')).render(<MainApp />);
}
