// ============ App + ruteo ============

const SCREEN_TITLES = {
  inicio: "Inicio",
  cursos: "Mis Cursos",
  calendario: "Calendario",
  tareas: "Tareas",
  certificados: "Certificados",
  progreso: "Mi progreso",
};

function App() {
  const [route, setRoute] = useState({ screen: "inicio", params: {} });
  const [query, setQuery] = useState("");
  const [ready, setReady] = useState(false);
  const [session, setSession] = useState(API.getSession());
  const [showSupport, setShowSupport] = useState(false);

  useEffect(() => {
    if (!session || (session.user && session.user.is_admin)) return;
    API.getCampus()
      .then((data) => { window.DATA = data; setReady(true); })
      .catch((err) => { console.warn("No se pudo cargar el campus", err); API.clearSession(); setSession(null); setReady(true); });
  }, [session]);

  if (!session) return <AuthScreen />;
  if (session.user && session.user.is_admin) {
    window.location.href = "/admin";
    return null;
  }

  const go = (screen, params = {}) => {
    setRoute({ screen, params });
    const main = document.querySelector(".main-scroll");
    if (main) main.scrollTop = 0;
  };

  const pendingTasks = DATA.assignments.filter((a) => a.status === "pending").length;

  // map "curso", "leccion", "sala" to nav highlight
  const navScreen = ["curso", "leccion"].includes(route.screen) ? "cursos" : route.screen === "sala" ? "calendario" : route.screen;

  let content, title, crumb = null;
  switch (route.screen) {
    case "inicio": content = <Dashboard go={go} />; title = "Inicio"; break;
    case "cursos": content = <CourseList go={go} query={query} />; title = "Mis Cursos"; break;
    case "curso": {
      const c = DATA.courses.find((x) => x.id === route.params.courseId);
      content = <CourseDetail courseId={route.params.courseId} go={go} />;
      title = c ? c.title : "Curso";
      crumb = <button className="crumb" onClick={() => go("cursos")}>Mis Cursos <Icon name="chevR" size={13} /></button>;
      break;
    }
    case "leccion": content = <LessonView {...route.params} go={go} />; title = ""; break;
    case "calendario": content = <Calendar go={go} />; title = "Calendario"; break;
    case "sala": content = <LiveRoom sessionId={route.params.sessionId} go={go} />; title = "Sesión en vivo"; break;
    case "tareas": content = <TasksScreen go={go} openId={route.params.open} />; title = "Tareas"; break;
    case "certificados": content = <Certificates go={go} />; title = "Certificados"; break;
    case "progreso": content = <Progress go={go} />; title = "Mi progreso"; break;
    default: content = <Dashboard go={go} />; title = "Inicio";
  }

  const bare = route.screen === "leccion";

  if (!ready) {
    return <div className="app"><div className="main"><div className="screen"><div className="panel" style={{ padding: 24 }}>Cargando campus...</div></div></div></div>;
  }

  return (
    <div className="app">
      <Sidebar route={{ screen: navScreen }} go={go} pendingTasks={pendingTasks} onSupport={() => setShowSupport(true)} />
      <div className="main">
        {!bare && <TopBar title={title} crumb={crumb} onSearch={setQuery} query={query} />}
        <div className="main-scroll">{content}</div>
      </div>
      {showSupport && <SupportModal onClose={() => setShowSupport(false)} />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
