// ============ Pantalla: Lección (video / quiz / tarea / material) ============

function VideoPlayer({ title, url }) {
  const [playing, setPlaying] = useState(false);
  const [t, setT] = useState(0.18);
  if (url) {
    return (
      <div className="player" style={{ background: "#000" }}>
        <video 
          src={url} 
          controls 
          className="player-stage" 
          style={{ width: "100%", height: "100%", borderRadius: "12px", background: "#000" }} 
        />
      </div>
    );
  }
  return (
    <div className="player" style={{ background: "#0e0e2c", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: "12px", color: "var(--muted-2)", borderRadius: "12px", minHeight: "360px" }}>
      <Icon name="video" size={48} />
      <span style={{ fontSize: "14.5px" }}>Grabación no disponible</span>
    </div>
  );
}

function Comments({ courseId, lessonId }) {
  const [list, setList] = useState([]);
  const [val, setVal] = useState("");

  useEffect(() => {
    API.getComments(courseId, lessonId)
      .then((data) => setList(data))
      .catch((err) => console.warn("No se pudieron cargar los comentarios", err));
  }, [courseId, lessonId]);

  const add = () => {
    if (!val.trim()) return;
    API.postComment(courseId, lessonId, val.trim())
      .then((newComment) => {
        setList((l) => [...l, newComment]);
        setVal("");
      })
      .catch((err) => console.warn("No se pudo guardar el comentario", err));
  };

  const user = window.DATA && window.DATA.user ? window.DATA.user : { name: "Alumno", role: "" };
  const getInitials = (name) => name.split(" ").slice(0, 2).map(n => n[0]).join("").toUpperCase() || "AL";
  const userInit = user.avatar || getInitials(user.name);

  return (
    <div className="comments">
      <div className="comment-box">
        <Avatar text={userInit} size={36} />
        <input placeholder="Escribe un comentario o pregunta…" value={val}
          onChange={(e) => setVal(e.target.value)} onKeyDown={(e) => e.key === "Enter" && add()} />
        <Btn variant="primary" size="sm" icon="send" onClick={add}>Enviar</Btn>
      </div>
      {list.map((c) => (
        <div key={c.id} className="comment">
          <Avatar text={c.init} size={36} bg={c.role ? "var(--orange)" : "var(--navy)"} />
          <div>
            <div className="cmt-head"><strong>{c.who}</strong>{c.role && <Badge tone="orange">{c.role}</Badge>}<span>{c.time}</span></div>
            <p>{c.txt}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

function Quiz({ go, courseId, lesson }) {
  const quiz = (lesson && lesson.questions && lesson.questions.length > 0)
    ? { title: lesson.title, course: "", questions: lesson.questions }
    : DATA.quiz;
  const [i, setI] = useState(0);
  const [answers, setAnswers] = useState({});
  const [picked, setPicked] = useState(null);
  const [done, setDone] = useState(false);
  const q = quiz.questions[i];
  const last = i === quiz.questions.length - 1;

  const choose = (idx) => { if (answers[i] !== undefined) return; setPicked(idx); setAnswers((a) => ({ ...a, [i]: idx })); };
  const nextQ = () => { if (last) { setDone(true); } else { setI(i + 1); setPicked(null); } };
  const score = quiz.questions.reduce((s, qq, idx) => s + (answers[idx] === qq.correct ? 1 : 0), 0);

  if (done) {
    const pct = Math.round((score / quiz.questions.length) * 100);
    const pass = pct >= 60;
    return (
      <div className="quiz-result">
        <div className={"qr-ring " + (pass ? "pass" : "fail")}><Ring value={pct} size={120} sw={10} color={pass ? "var(--green)" : "var(--orange)"} /></div>
        <h2>{pass ? "¡Aprobado! 🎉" : "Casi lo logras"}</h2>
        <p>Respondiste correctamente <strong>{score} de {quiz.questions.length}</strong> preguntas.</p>
        <div className="qr-actions">
          <Btn variant="ghost" onClick={() => { setI(0); setAnswers({}); setPicked(null); setDone(false); }}>Reintentar</Btn>
          <Btn variant="primary" icon="arrowL" onClick={() => go("curso", { courseId })}>Volver al curso</Btn>
        </div>
      </div>
    );
  }

  return (
    <div className="quiz">
      <div className="quiz-prog">
        <span>Pregunta {i + 1} de {quiz.questions.length}</span>
        <ProgressBar value={((i + (answers[i] !== undefined ? 1 : 0)) / quiz.questions.length) * 100} />
      </div>
      <h2 className="quiz-q">{q.q}</h2>
      <div className="quiz-opts">
        {q.options.map((o, idx) => {
          const answered = answers[i] !== undefined;
          let cls = "quiz-opt";
          if (answered) {
            if (idx === q.correct) cls += " correct";
            else if (idx === answers[i]) cls += " wrong";
            else cls += " dim";
          }
          return (
            <button key={idx} className={cls} onClick={() => choose(idx)}>
              <span className="qo-letter">{String.fromCharCode(65 + idx)}</span>
              <span className="qo-txt">{o}</span>
              {answered && idx === q.correct && <Icon name="checkc" size={20} className="qo-mark" />}
              {answered && idx === answers[i] && idx !== q.correct && <Icon name="x" size={20} className="qo-mark" />}
            </button>
          );
        })}
      </div>
      <div className="quiz-foot">
        {answers[i] !== undefined
          ? <Btn variant="primary" icon={last ? "checkc" : "chevR"} onClick={nextQ}>{last ? "Ver resultado" : "Siguiente"}</Btn>
          : <span className="quiz-hint">Selecciona una respuesta</span>}
      </div>
    </div>
  );
}

function LessonView({ courseId, moduleId, lessonId, go }) {
  const c = DATA.courses.find((x) => x.id === courseId);
  const m = c.modules.find((x) => x.id === moduleId);
  const idx = m.lessons.findIndex((x) => x.id === lessonId);
  const l = m.lessons[idx];
  const [tab, setTab] = useState("desc");
  const [completed, setCompleted] = useState(l.done);

  const prev = m.lessons[idx - 1];
  const next = m.lessons[idx + 1];

  if (l.type === "quiz") {
    return (
      <div className="screen lesson">
        <LessonTopNav c={c} m={m} go={go} title={l.title} />
        <div className="lesson-main quiz-wrap"><Quiz go={go} courseId={courseId} lesson={l} /></div>
      </div>
    );
  }
  if (l.type === "tarea") {
    return (
      <div className="screen lesson">
        <LessonTopNav c={c} m={m} go={go} title={l.title} />
        <div className="lesson-main"><TareaInline title={l.title} course={c.title} go={go} courseId={courseId} /></div>
      </div>
    );
  }

  const tabs = [["desc", "Descripción"], ["materiales", "Materiales"], ["comentarios", "Comentarios"]];
  return (
    <div className="screen lesson">
      <LessonTopNav c={c} m={m} go={go} title={l.title} />
      <div className="lesson-layout">
        <div className="lesson-main">
          {l.type === "video" ? (
            <VideoPlayer title={l.title} url={l.file ? l.file.url : null} />
          ) : l.file && l.file.url && l.file.url.toLowerCase().endsWith(".pdf") ? (
            <div className="pdf-viewer-wrap" style={{ width: "100%", height: "550px", borderRadius: "12px", overflow: "hidden", border: "1px solid var(--line)", marginBottom: "16px" }}>
              <iframe 
                src={l.file.url} 
                style={{ width: "100%", height: "100%", border: "none" }} 
                title={l.title} 
              />
            </div>
          ) : (
            <div className="reading"><div className="reading-ph"><Icon name="read" size={32} /><span>contenido de lectura</span></div></div>
          )}

          <div className="lesson-head">
            <div>
              <span className="lh-crumb">{m.title}</span>
              <h2>{l.title}</h2>
            </div>
            <div style={{ display: "flex", gap: "8px", alignItems: "center" }}>
              {l.file && l.file.url && (
                <Btn variant="ghost" size="sm" icon="download" onClick={() => window.open(l.file.url, "_blank")}>
                  Descargar archivo
                </Btn>
              )}
              <Btn variant={completed ? "done" : "primary"} icon={completed ? "checkc" : "check"}
                onClick={() => {
                  setCompleted(true);
                  API.completeLesson(courseId, l.id)
                    .then((course) => {
                      window.DATA.courses = DATA.courses.map((x) => x.id === course.id ? course : x);
                    })
                    .catch((err) => console.warn("No se pudo guardar el avance", err));
                }}>{completed ? "Completada" : "Marcar completada"}</Btn>
            </div>
          </div>

          <div className="tabs lesson-tabs">
            {tabs.map(([id, lb]) => (
              <button key={id} className={"tab" + (tab === id ? " active" : "")} onClick={() => setTab(id)}>{lb}</button>
            ))}
          </div>

          {tab === "desc" && (
            <div className="prose">
              {l.description ? (
                <p style={{ whiteSpace: "pre-wrap" }}>{l.description}</p>
              ) : (
                <>
                  <p>En esta sesión revisamos cómo {l.title.toLowerCase()} aplica al día a día de tu equipo. Verás ejemplos concretos del sector y un ejercicio práctico para aplicar de inmediato.</p>
                  <h4>Lo que aprenderás</h4>
                  <ul>
                    <li>Identificar oportunidades reales en tu operación</li>
                    <li>Aplicar el marco visto con un caso propio</li>
                    <li>Evitar los errores más comunes al empezar</li>
                  </ul>
                </>
              )}
            </div>
          )}
          {tab === "materiales" && (
            <div className="materials">
              {c.modules.flatMap(m => m.lessons.filter(ll => ll.file)).length > 0 ? (
                c.modules.flatMap(m => m.lessons.filter(ll => ll.file)).map((ll, k) => (
                  <div key={k} className="material-row">
                    <div className="mat-icon"><Icon name="file" size={20} /></div>
                    <div className="mat-info">
                      <strong>{ll.file.name}</strong>
                      <span>{ll.file.size ? `${Math.ceil(ll.file.size / 1024)} KB` : "Archivo"}</span>
                    </div>
                    <Btn variant="ghost" size="sm" icon="download" onClick={() => window.open(ll.file.url, "_blank")}>Descargar</Btn>
                  </div>
                ))
              ) : (
                <div className="panel" style={{ padding: 20 }}>No hay materiales adicionales cargados para este curso.</div>
              )}
            </div>
          )}
          {tab === "comentarios" && <Comments courseId={courseId} lessonId={lessonId} />}
        </div>

        <aside className="lesson-side">
          <div className="ls-head"><strong>{m.title}</strong><span>{m.lessons.filter((x) => x.done).length}/{m.lessons.length} completadas</span></div>
          <div className="ls-list">
            {m.lessons.map((ll) => {
              const meta = TYPE_META[ll.type];
              return (
                <button key={ll.id} className={"ls-item" + (ll.id === lessonId ? " current" : "")}
                  onClick={() => go("leccion", { courseId, moduleId, lessonId: ll.id })}>
                  <div className={"ls-ico" + (ll.done ? " done" : "")}><Icon name={ll.done ? "check" : meta.icon} size={16} /></div>
                  <div className="ls-txt"><strong>{ll.title}</strong><span>{meta.label} · {ll.dur}</span></div>
                </button>
              );
            })}
          </div>
        </aside>
      </div>

      <div className="lesson-nav">
        {prev ? <button className="ln-btn" onClick={() => go("leccion", { courseId, moduleId, lessonId: prev.id })}><Icon name="chevL" size={18} /><div><span>Anterior</span><strong>{prev.title}</strong></div></button> : <div />}
        {next ? <button className="ln-btn right" onClick={() => go("leccion", { courseId, moduleId, lessonId: next.id })}><div><span>Siguiente</span><strong>{next.title}</strong></div><Icon name="chevR" size={18} /></button> : <div />}
      </div>
    </div>
  );
}

function LessonTopNav({ c, m, go, title }) {
  return (
    <button className="back-link" onClick={() => go("curso", { courseId: c.id })}>
      <Icon name="arrowL" size={18} /> {c.title}
    </button>
  );
}

Object.assign(window, { VideoPlayer, Comments, Quiz, LessonView });
