// ============ Pantallas: Mis Cursos + Detalle de curso ============

function CourseCard({ c, go }) {
  const done = c.progress === 100;
  const started = c.progress > 0;
  const totalLessons = c.modules.reduce((s, m) => s + m.lessons.length, 0);
  const doneLessons = c.modules.reduce((s, m) => s + m.lessons.filter((l) => l.done).length, 0);
  return (
    <div className="course-card" onClick={() => go("curso", { courseId: c.id })}>
      <div className="course-banner" style={{ background: c.color }}>
        <span className="cb-level">{c.level}</span>
        {done && <span className="cb-done"><Icon name="checkc" size={15} /> Completado</span>}
        <div className="cb-pattern" />
      </div>
      <div className="course-body">
        <h4>{c.title}</h4>
        <p>{c.subtitle}</p>
        <div className="course-meta">
          <span><Icon name="user" size={15} /> {c.instructor}</span>
          <span><Icon name="clock" size={15} /> {c.hours}</span>
        </div>
      </div>
      <div className="course-foot">
        <ProgressBar value={c.progress} color={done ? "var(--green)" : "var(--orange)"} />
        <div className="cf-row">
          <span>{doneLessons}/{totalLessons} lecciones</span>
          <strong className="cf-cta">{done ? "Repasar" : started ? "Continuar" : "Empezar"} <Icon name="chevR" size={14} /></strong>
        </div>
      </div>
    </div>
  );
}

function CourseList({ go, query = "" }) {
  const [tab, setTab] = useState("todos");
  const q = query.toLowerCase().trim();
  const filtered = DATA.courses.filter((c) => {
    if (q && !c.title.toLowerCase().includes(q) && !(c.subtitle || "").toLowerCase().includes(q)) return false;
    if (tab === "curso") return c.progress > 0 && c.progress < 100;
    if (tab === "completados") return c.progress === 100;
    if (tab === "nuevos") return c.progress === 0;
    return true;
  });
  const tabs = [["todos", "Todos"], ["curso", "En curso"], ["completados", "Completados"], ["nuevos", "Por empezar"]];
  return (
    <div className="screen">
      <div className="tabs">
        {tabs.map(([id, l]) => (
          <button key={id} className={"tab" + (tab === id ? " active" : "")} onClick={() => setTab(id)}>{l}</button>
        ))}
      </div>
      <div className="course-grid">
        {filtered.map((c) => <CourseCard key={c.id} c={c} go={go} />)}
      </div>
    </div>
  );
}

function ModuleRow({ m, courseId, openDefault, go }) {
  const [open, setOpen] = useState(openDefault);
  const locked = m.state === "locked";
  const doneCount = m.lessons.filter((l) => l.done).length;
  const allDone = doneCount === m.lessons.length;
  return (
    <div className={"module" + (locked ? " locked" : "")}>
      <button className="module-head" onClick={() => !locked && setOpen((o) => !o)}>
        <div className={"mod-status " + (allDone ? "done" : locked ? "locked" : "active")}>
          {allDone ? <Icon name="check" size={16} /> : locked ? <Icon name="lock" size={15} /> : <span>{doneCount}/{m.lessons.length}</span>}
        </div>
        <div className="mod-title">
          <strong>{m.title}</strong>
          <span>{m.lessons.length} lecciones · {locked ? "Se desbloquea al avanzar" : allDone ? "Completado" : "En progreso"}</span>
        </div>
        {!locked && <Icon name={open ? "chevD" : "chevR"} size={20} className="mod-chev" />}
      </button>
      {open && !locked && (
        <div className="lesson-list">
          {m.lessons.map((l) => {
            const meta = TYPE_META[l.type];
            return (
              <button key={l.id} className="lesson-row" onClick={() => go("leccion", { courseId, moduleId: m.id, lessonId: l.id })}>
                <div className={"lesson-icon" + (l.done ? " done" : "")}>
                  <Icon name={l.done ? "check" : meta.icon} size={18} />
                </div>
                <div className="lesson-info">
                  <strong>{l.title}</strong>
                  <span>{meta.label} · {l.dur}</span>
                </div>
                {l.done && <Badge tone="green">Visto</Badge>}
                <Icon name="chevR" size={18} className="lesson-go" />
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function CourseDetail({ courseId, go }) {
  const c = DATA.courses.find((x) => x.id === courseId);
  const totalLessons = c.modules.reduce((s, m) => s + m.lessons.length, 0);
  const doneLessons = c.modules.reduce((s, m) => s + m.lessons.filter((l) => l.done).length, 0);
  const activeIdx = c.modules.findIndex((m) => m.state === "active");
  return (
    <div className="screen course-detail">
      <div className="cd-hero" style={{ "--accent": c.color }}>
        <div className="cd-hero-main">
          <span className="cd-level">{c.level}</span>
          <h2>{c.title}</h2>
          <p>{c.subtitle}</p>
          <div className="cd-meta">
            <span><Icon name="user" size={16} /> {c.instructor}</span>
            <span><Icon name="clock" size={16} /> {c.hours} de contenido</span>
            <span><Icon name="book" size={16} /> {c.modules.length} módulos</span>
          </div>
        </div>
        <div className="cd-hero-side">
          <Ring value={c.progress} size={84} sw={8} color="#fff" />
          <span>{doneLessons} de {totalLessons} lecciones</span>
          <Btn variant="onaccent" icon="play"
            onClick={() => {
              for (const m of c.modules) for (const l of m.lessons) if (!l.done) return go("leccion", { courseId: c.id, moduleId: m.id, lessonId: l.id });
              go("leccion", { courseId: c.id, moduleId: c.modules[0].id, lessonId: c.modules[0].lessons[0].id });
            }}>
            {c.progress === 0 ? "Empezar curso" : c.progress === 100 ? "Repasar" : "Continuar"}
          </Btn>
        </div>
      </div>

      <div className="cd-body">
        <h3 className="cd-section-title">Contenido del curso</h3>
        <div className="modules">
          {c.modules.map((m, i) => (
            <ModuleRow key={m.id} m={m} courseId={c.id} go={go} openDefault={i === activeIdx} />
          ))}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CourseCard, CourseList, ModuleRow, CourseDetail });
