// ============ Pantalla: Inicio (dashboard con sesiones) ============

function SessionCard({ s, onOpen, big }) {
  const n = daysUntil(s.date);
  const when = n === 0 ? "Hoy" : n === 1 ? "Mañana" : fmtDate(s.date);
  const d = parseD(s.date);
  return (
    <div className={"session-card" + (big ? " big" : "")}>
      <div className="sc-date">
        <span className="sc-day">{d.getDate()}</span>
        <span className="sc-mon">{MES[d.getMonth()]}</span>
      </div>
      <div className="sc-body">
        <div className="sc-when">
          <Badge tone={n <= 1 ? "orange" : "neutral"}>{when} · {s.time}</Badge>
          <span className="sc-course">{s.course}</span>
        </div>
        <h4>{s.title}</h4>
        <div className="sc-host"><Icon name="user" size={15} /> {s.host}</div>
      </div>
      <div className="sc-action">
        {s.joinable
          ? <Btn variant="primary" size="sm" icon="video" onClick={() => onOpen && onOpen(s)}>Unirme</Btn>
          : <Btn variant="ghost" size="sm" icon="bell">Recordar</Btn>}
      </div>
    </div>
  );
}

function ContinueCard({ course, go }) {
  // find first active module / not-done lesson
  let target = null;
  for (const m of course.modules) {
    for (const l of m.lessons) { if (!l.done) { target = { m, l }; break; } }
    if (target) break;
  }
  return (
    <div className="continue-card" onClick={() => go("curso", { courseId: course.id })}>
      <div className="cc-thumb" style={{ background: course.color }}>
        <Icon name="play" size={26} />
      </div>
      <div className="cc-body">
        <span className="cc-label">Continuar donde quedaste</span>
        <h4>{course.title}</h4>
        <p>{target ? target.l.title : "Repasar contenido"}</p>
        <ProgressBar value={course.progress} />
        <span className="cc-prog">{course.progress}% completado</span>
      </div>
      <Icon name="chevR" size={22} className="cc-arrow" />
    </div>
  );
}

function Dashboard({ go }) {
  const u = DATA.user;
  const inProgress = DATA.courses.filter((c) => c.progress > 0 && c.progress < 100);
  const upcoming = [...DATA.sessions].sort((a, b) => parseD(a.date) - parseD(b.date));
  const next = upcoming[0];
  const pending = DATA.assignments.filter((a) => a.status === "pending");
  const totalProgress = DATA.courses.length ? Math.round(DATA.courses.reduce((s, c) => s + c.progress, 0) / DATA.courses.length) : 0;

  return (
    <div className="screen dashboard">
      <div className="hero">
        <div>
          <span className="hero-eyebrow">{MES_L[TODAY.getMonth()].toUpperCase()} · {TODAY.getDate()}, {TODAY.getFullYear()}</span>
          <h2>Hola, {u.name.split(" ")[0]} 👋</h2>
          <p>{u.program ? <>Vas avanzando muy bien en el programa <strong>{u.program}</strong>.</> : "Tu campus esta listo para recibir cursos asignados."}</p>
        </div>
        <div className="hero-stats">
          <div className="hstat"><Ring value={totalProgress} /><span>Avance global</span></div>
          <div className="hstat-divider" />
          <div className="hstat-num"><strong>{inProgress.length}</strong><span>cursos activos</span></div>
          <div className="hstat-num"><strong>{pending.length}</strong><span>tareas pendientes</span></div>
        </div>
      </div>

      <div className="dash-grid">
        <div className="dash-main">
          <div className="next-session">
            <div className="ns-tag"><Icon name="video" size={16} /> Próxima sesión en vivo</div>
            {next ? <SessionCard s={next} big onOpen={(s) => go("sala", { sessionId: s.id })} /> : <div className="empty-state"><h3>Sin sesiones programadas</h3><p>Cuando haya clases en vivo apareceran aca.</p></div>}
          </div>

          <div className="sec-head">
            <h3>Continúa aprendiendo</h3>
            <button className="link-btn" onClick={() => go("cursos")}>Ver todos los cursos <Icon name="chevR" size={15} /></button>
          </div>
          <div className="continue-list">
            {inProgress.map((c) => <ContinueCard key={c.id} course={c} go={go} />)}
            {inProgress.length === 0 && <div className="panel" style={{ padding: 20 }}>Todavía no hay cursos activos asignados.</div>}
          </div>
        </div>

        <div className="dash-side">
          <div className="panel">
            <div className="panel-head">
              <h3><Icon name="calendar" size={18} /> Agenda</h3>
              <button className="link-btn" onClick={() => go("calendario")}>Calendario</button>
            </div>
            <div className="agenda-list">
              {upcoming.slice(0, 4).map((s) => {
                const d = parseD(s.date);
                return (
                  <div key={s.id} className="agenda-item">
                    <div className="ai-date"><b>{d.getDate()}</b><span>{MES[d.getMonth()]}</span></div>
                    <div className="ai-body"><strong>{s.title}</strong><span>{s.time}</span></div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="panel">
            <div className="panel-head">
              <h3><Icon name="task" size={18} /> Tareas por entregar</h3>
              <button className="link-btn" onClick={() => go("tareas")}>Ver todas</button>
            </div>
            <div className="task-mini-list">
              {pending.map((a) => {
                const dl = dueLabel(a.due);
                return (
                  <div key={a.id} className="task-mini" onClick={() => go("tareas", { open: a.id })}>
                    <Icon name="task" size={18} style={{ color: "var(--navy)" }} />
                    <div><strong>{a.title}</strong><span>{a.course}</span></div>
                    <Badge tone={dl.tone}>{dl.txt}</Badge>
                  </div>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard, SessionCard, ContinueCard });
