// Presentational Courses view for Adventure and Space Explorer.
const stxCourseTypeIcon = (lesson) => {
  if (lesson.type === "video") return "video";
  if (lesson.type === "quiz") return "quiz";
  if (lesson.type === "text") return "book";
  if (lesson.type === "homework") return "homework";
  return "book";
};

const stxCourseActionLabel = (lesson) => {
  if (lesson.type === "video") return "Play";
  if (lesson.type === "quiz") return "Take quiz";
  if (lesson.type === "homework") return "Submit";
  if (lesson.type === "text") return "Read";
  return "Open";
};

const StxCourseReaders = ({
  courseId,
  fileLesson,
  setFileLesson,
  textLesson,
  setTextLesson,
  videoLesson,
  setVideoLesson,
}) => (
  <>
    {fileLesson && (
      <FileViewer
        courseId={fileLesson.course_id || courseId}
        fileId={fileLesson.file_id}
        title={fileLesson.title}
        fileType={fileLesson.file_type}
        onClose={() => setFileLesson(null)}
      />
    )}
    {textLesson && (
      <div
        className="stx-reader-backdrop"
        onClick={(event) => event.target === event.currentTarget && setTextLesson(null)}
      >
        <div className="stx-reader-surface codeland">
          <header>
            <strong>{textLesson.title}</strong>
            <button
              type="button"
              aria-label="Close lesson"
              onClick={() => setTextLesson(null)}
            >
              ×
            </button>
          </header>
          <div className="stx-reader-content">
            <RichTextView html={textLesson.body}/>
          </div>
        </div>
      </div>
    )}
    {videoLesson && (
      <div
        className="stx-reader-backdrop"
        onClick={(event) => event.target === event.currentTarget && setVideoLesson(null)}
      >
        <div className="stx-video-surface">
          <header>
            <strong>{videoLesson.title}</strong>
            <button
              type="button"
              aria-label="Close video"
              onClick={() => setVideoLesson(null)}
            >
              ×
            </button>
          </header>
          <SafeYouTube
            videoId={ytId(videoLesson.youtube_id)}
            title={videoLesson.title}
            autoplay
            style={{ borderRadius: 0 }}
          />
        </div>
      </div>
    )}
  </>
);

const StxCoursesView = ({
  student,
  courseContent,
  activeUnit,
  setActiveUnit,
  isDone,
  markComplete,
  courseId,
  videoLesson,
  setVideoLesson,
  fileLesson,
  setFileLesson,
  textLesson,
  setTextLesson,
  go,
}) => {
  const units = Array.isArray(courseContent) ? courseContent : [];
  const totalLessons = units.reduce(
    (sum, unit) => sum + (unit.lessons || []).length,
    0,
  );
  const completedLessons = units.reduce(
    (sum, unit) => sum + (unit.lessons || []).filter(isDone).length,
    0,
  );
  const overallPct = totalLessons
    ? Math.round((completedLessons / totalLessons) * 100)
    : 0;
  const selectedIndex = units.findIndex((unit) => unit.id === activeUnit);
  const selectedUnit = units[selectedIndex] || null;
  const selectedLessons = selectedUnit?.lessons || [];
  const selectedDone = selectedLessons.filter(isDone).length;

  const openLesson = (lesson) => {
    if (lesson.type === "video" && lesson.youtube) {
      markComplete(lesson.id);
      setVideoLesson({ title: lesson.title, youtube_id: lesson.youtube });
    } else if (lesson.type === "file" && lesson.file_id) {
      markComplete(lesson.id);
      setFileLesson({
        file_id: lesson.file_id,
        title: lesson.title,
        file_type: lesson.file_type,
        course_id: lesson.file_course_id || courseId,
      });
    } else if (lesson.type === "text" && lesson.body) {
      markComplete(lesson.id);
      setTextLesson({ title: lesson.title, body: lesson.body });
    } else if (lesson.type === "quiz") {
      go("/app/student/quiz");
    } else if (lesson.type === "homework") {
      go("/app/student/homework");
    }
  };

  const canOpen = (lesson) => (
    (lesson.type === "video" && lesson.youtube)
    || (lesson.type === "file" && lesson.file_id)
    || (lesson.type === "text" && lesson.body)
    || lesson.type === "quiz"
    || lesson.type === "homework"
  );

  if (!student.course_id && !student.course_name) {
    return (
      <div className="stx-courses stx-page">
        <StxPageTitle>My courses</StxPageTitle>
        <p className="stx-page-subtitle">Your learning path</p>
        <StxEmpty>No course has been assigned yet.</StxEmpty>
      </div>
    );
  }

  return (
    <div className="stx-courses stx-page">
      <StxCourseReaders
        courseId={courseId}
        fileLesson={fileLesson}
        setFileLesson={setFileLesson}
        textLesson={textLesson}
        setTextLesson={setTextLesson}
        videoLesson={videoLesson}
        setVideoLesson={setVideoLesson}
      />

      <StxCard className="stx-course-header">
        <div className="stx-course-heading">
          <StxPageTitle>{student.course_name || "My course"}</StxPageTitle>
          <p className="stx-page-subtitle">
            {student.batch && student.teacher
              ? `${student.batch} · ${student.teacher}`
              : student.batch || student.teacher || "Course overview"}
          </p>
        </div>
        <div className="stx-course-shortcuts">
          <StxButton variant="ghost" onClick={() => go("/app/student/quiz")}>
            {stxIcon("quiz", 20)} Quiz
          </StxButton>
          <StxButton variant="ghost" onClick={() => go("/app/student/homework")}>
            {stxIcon("homework", 20)} Homework
          </StxButton>
        </div>
        <div className="stx-course-progress">
          <div className="stx-course-summary">
            <strong>{overallPct}%</strong>
            <span>{completedLessons} of {totalLessons} lessons done</span>
          </div>
          <StxProgress
            value={completedLessons}
            max={Math.max(totalLessons, 1)}
            label="Overall course progress"
            valueText={`${completedLessons} of ${totalLessons} lessons`}
          />
        </div>
      </StxCard>

      {units.length === 0 ? (
        <StxEmpty>No units are available for this course yet.</StxEmpty>
      ) : (
        <div className="stx-course-layout">
          <StxCard className="stx-unit-list">
            <h2>Units</h2>
            <div className="stx-unit-buttons">
              {units.map((unit) => {
                const lessons = unit.lessons || [];
                const done = lessons.filter(isDone).length;
                const pct = lessons.length
                  ? Math.round((done / lessons.length) * 100)
                  : 0;
                return (
                  <button
                    type="button"
                    className={activeUnit === unit.id ? "stx-unit-active" : ""}
                    key={unit.id}
                    aria-pressed={activeUnit === unit.id}
                    aria-current={activeUnit === unit.id ? "true" : undefined}
                    onClick={() => setActiveUnit(unit.id)}
                  >
                    <span>
                      <strong>{unit.unit}</strong>
                      <small>{done} of {lessons.length} lessons</small>
                    </span>
                    <b>{pct}%</b>
                    <StxProgress
                      value={done}
                      max={Math.max(lessons.length, 1)}
                      label={`${unit.unit} progress`}
                      valueText={`${done} of ${lessons.length} lessons`}
                    />
                  </button>
                );
              })}
            </div>
          </StxCard>

          <StxCard className="stx-unit-detail">
            {!selectedUnit ? (
              <StxEmpty>Select a unit to see its lessons.</StxEmpty>
            ) : (
              <>
                <header className="stx-unit-heading">
                  <div>
                    <h2>{selectedUnit.unit}</h2>
                    <p>{selectedDone} of {selectedLessons.length} lessons done</p>
                  </div>
                  {units.length > 1 && (
                    <div className="stx-unit-nav">
                      <StxButton
                        variant="ghost"
                        disabled={selectedIndex <= 0}
                        aria-disabled={selectedIndex <= 0}
                        onClick={() => setActiveUnit(units[selectedIndex - 1].id)}
                      >
                        {stxIcon("chevronLeft", 18)} Previous
                      </StxButton>
                      <StxButton
                        variant="ghost"
                        disabled={selectedIndex >= units.length - 1}
                        aria-disabled={selectedIndex >= units.length - 1}
                        onClick={() => setActiveUnit(units[selectedIndex + 1].id)}
                      >
                        Next {stxIcon("chevronRight", 18)}
                      </StxButton>
                    </div>
                  )}
                </header>

                {(selectedUnit.lessons || []).length === 0 ? (
                  <StxEmpty>No lessons are available in this unit yet.</StxEmpty>
                ) : (
                  <div className="stx-lesson-list">
                    {selectedUnit.lessons.map((lesson, index) => {
                      const done = isDone(lesson);
                      return (
                        <article className="stx-lesson-row" key={lesson.id || index}>
                          <div className="stx-lesson-icon">
                            <StxIconTile
                              tint={(index % 5) + 1}
                              icon={stxIcon(stxCourseTypeIcon(lesson), 22)}
                            />
                            {done && (
                              <span aria-label="Completed">
                                {stxIcon("check", 12)}
                              </span>
                            )}
                          </div>
                          <div className="stx-lesson-copy">
                            <strong>{lesson.title}</strong>
                            <span>
                              {lesson.type || "lesson"}
                              {lesson.duration ? ` · ${lesson.duration}` : ""}
                              {!lesson.duration && lesson.questions
                                ? ` · ${lesson.questions} questions`
                                : ""}
                            </span>
                          </div>
                          {done ? (
                            <span className="stx-lesson-status">
                              {stxIcon("check", 17)} Completed
                            </span>
                          ) : (
                            <StxButton
                              variant="ghost"
                              className="stx-lesson-done"
                              onClick={() => markComplete(lesson.id)}
                            >
                              Mark as done
                            </StxButton>
                          )}
                          {canOpen(lesson) && (
                            <StxButton
                              className="stx-lesson-open"
                              onClick={() => openLesson(lesson)}
                            >
                              {stxCourseActionLabel(lesson)}
                            </StxButton>
                          )}
                        </article>
                      );
                    })}
                  </div>
                )}
              </>
            )}
          </StxCard>
        </div>
      )}
    </div>
  );
};

window.StxCoursesView = StxCoursesView;
