/* global React, Icons, Button, IconButton, Card, Heading, Text, Avatar, Badge, Progress, Divider, AppShell, navigate, DATA */

const CourseIndexPage = ({ courseId }) => {
  const course = DATA.COURSES.find(c => c.id === courseId) || DATA.COURSES[0];
  const syllabus = course.syllabus || [];

  const totalLessons = syllabus.reduce((a, m) => a + m.lessons.length, 0);
  const doneLessons  = syllabus.flatMap(m => m.lessons).filter(l => l.done).length;

  const [filter, setFilter] = React.useState("all");

  return (
    <AppShell
      active="#/cursos"
      breadcrumbs={[
        { label: "Mi espacio", href: "#/mi-espacio" },
        { label: "Catálogo", href: "#/cursos" },
        { label: course.title, href: `#/curso/${course.id}` },
        { label: "Índice de contenidos" },
      ]}
    >
      <div data-screen-label="06 Índice de contenidos">
        {/* Header */}
        <div className="page-header">
          <span className="page-eyebrow"><Icons.Layers size={12}/> Índice del curso</span>
          <Heading size="h1" className="mb-2">{course.title}</Heading>
          <Text size="lg" muted>
            {syllabus.length} módulos · {totalLessons} lecciones · {course.duration} de contenido
          </Text>
        </div>

        {/* Progress strip */}
        <Card className="mb-6">
          <div className="flex items-center gap-6 wrap">
            <div style={{ flex: 1, minWidth: 240 }}>
              <div className="flex items-center justify-between mb-2">
                <Text size="sm" style={{ fontWeight: 600 }}>
                  Has completado {doneLessons} de {totalLessons} lecciones
                </Text>
                <Text size="sm" style={{ fontWeight: 700, color: "var(--primary-600)" }}>{course.progress}%</Text>
              </div>
              <Progress value={course.progress} size="lg" />
            </div>
            <div className="flex gap-2">
              <Button variant="outline" icon={<Icons.Download size={16}/>}>Descargar plan</Button>
              <Button icon={<Icons.PlayCircle size={16}/>} onClick={() => navigate(`#/curso/${course.id}/leccion`)}>
                Continuar
              </Button>
            </div>
          </div>
        </Card>

        {/* Filter pills */}
        <div className="flex items-center gap-2 mb-5 wrap">
          {[
            { v: "all",      l: "Todo",        c: totalLessons },
            { v: "video",    l: "Videos",      c: countByType(syllabus, "video") },
            { v: "reading",  l: "Lecturas",    c: countByType(syllabus, "reading") },
            { v: "quiz",     l: "Evaluaciones", c: countByType(syllabus, "quiz") },
            { v: "done",     l: "Completadas",  c: doneLessons },
            { v: "pending",  l: "Pendientes",   c: totalLessons - doneLessons },
          ].map(f => (
            <button
              key={f.v}
              onClick={() => setFilter(f.v)}
              className="gs-btn"
              style={{
                height: 32, padding: "0 14px", fontSize: 13,
                background: filter === f.v ? "var(--bh-navy)" : "var(--bg-elev)",
                color: filter === f.v ? "#fff" : "var(--text)",
                borderColor: filter === f.v ? "var(--bh-navy)" : "var(--border)",
              }}>
              {f.l}
              <span style={{ marginLeft: 6, opacity: 0.8, fontWeight: 500 }}>{f.c}</span>
            </button>
          ))}
        </div>

        {/* Module list */}
        <div className="flex-col gap-5">
          {syllabus.map((m, mi) => (
            <ModuleBlock key={mi} module={m} index={mi} filter={filter} courseId={course.id} />
          ))}
        </div>

        {/* Final certificate teaser */}
        <Card style={{
          marginTop: 28,
          background: "var(--inverse-bg)",
          border: "none", color: "#fff",
          display: "grid", gridTemplateColumns: "1fr auto", alignItems: "center", gap: 24,
        }}>
          <div>
            <div className="flex items-center gap-2 mb-2">
              <Icons.Award size={16}/>
              <Text size="xs" style={{ color: "rgba(255,255,255,0.85)", fontWeight: 600 }}>
                Certificado final
              </Text>
            </div>
            <Heading size="h3" style={{ color: "#fff", marginBottom: 6 }}>
              Completa el curso para obtener tu certificado
            </Heading>
            <Text style={{ color: "rgba(255,255,255,0.85)" }}>
              Verificable, con firma de la dirección académica y código único. Te faltan {totalLessons - doneLessons} lecciones y la evaluación final.
            </Text>
          </div>
          <div style={{
            width: 160, height: 110, borderRadius: "var(--r-lg)",
            background: "rgba(255,255,255,0.12)", border: "1px solid rgba(255,255,255,0.25)",
            display: "grid", placeItems: "center", color: "#fff",
            position: "relative", overflow: "hidden",
          }}>
            <Icons.Award size={56} stroke={1.5}/>
            <div style={{
              position: "absolute", bottom: 8, left: 12, right: 12,
              fontSize: 9, fontFamily: "var(--font-display)", opacity: 0.7, textAlign: "center",
            }}>
              BH Academy · 2026
            </div>
          </div>
        </Card>
      </div>
    </AppShell>
  );
};

const ModuleBlock = ({ module, index, filter, courseId }) => {
  const lessons = module.lessons.filter(l => {
    if (filter === "all") return true;
    if (filter === "video") return l.type === "video";
    if (filter === "reading") return l.type === "reading";
    if (filter === "quiz") return l.type === "quiz";
    if (filter === "done") return l.done;
    if (filter === "pending") return !l.done;
    return true;
  });
  if (lessons.length === 0) return null;

  const state = module.done ? "done" : module.current ? "current" : "todo";

  return (
    <Card flush>
      <div style={{
        padding: "18px 22px",
        background: state === "current" ? "var(--primary-50)" : "var(--surface)",
        borderBottom: "1px solid var(--border)",
        display: "flex", alignItems: "center", gap: 16,
      }}>
        <div style={{
          width: 44, height: 44, borderRadius: "var(--r-md)", flexShrink: 0,
          background: state === "done" ? "var(--bh-ocean)" : state === "current" ? "var(--bh-ocean)" : "var(--bg-elev)",
          color: state === "done" || state === "current" ? "#fff" : "var(--text-muted)",
          border: state === "todo" ? "1px solid var(--border-strong)" : "none",
          display: "grid", placeItems: "center",
          fontSize: 16, fontWeight: 600, fontFamily: "var(--font-display)",
        }}>
          {state === "done" ? <Icons.Check size={20} stroke={3}/> : index + 1}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="flex items-center gap-2 mb-1">
            <Text size="xs" muted style={{ fontWeight: 600 }}>
              Módulo {index + 1}
            </Text>
            {state === "current" && <Badge variant="primary">En curso</Badge>}
            {state === "done" && <Badge variant="success">Completado</Badge>}
          </div>
          <Heading size="h4">{module.title.replace(/^Módulo \d+ ·\s*/, "")}</Heading>
        </div>
        <div className="text-right">
          <Text size="sm" muted>{module.lessons.length} lecciones</Text>
          <Text size="xs" muted>{moduleDur(module)}</Text>
        </div>
      </div>

      <div style={{ padding: "4px 0" }}>
        {lessons.map((l, li) => (
          <LessonRow key={li} lesson={l} index={li} courseId={courseId} />
        ))}
      </div>
    </Card>
  );
};

const LessonRow = ({ lesson, index, courseId }) => {
  const Ico = { video: Icons.Video, reading: Icons.Doc, quiz: Icons.Quiz, doc: Icons.Doc }[lesson.type] || Icons.Video;
  const typeLabel = { video: "Video", reading: "Lectura", quiz: "Evaluación", doc: "Documento" }[lesson.type] || "Lección";

  return (
    <div
      className="flex items-center gap-4"
      style={{
        padding: "14px 22px",
        borderBottom: "1px solid var(--border)",
        cursor: lesson.locked ? "not-allowed" : "pointer",
        opacity: lesson.locked ? 0.6 : undefined,
        background: lesson.current ? "var(--primary-50)" : undefined,
      }}
      title={lesson.locked ? "Se desbloquea al completar lo anterior" : undefined}
      onClick={() => !lesson.locked && navigate(lesson.href || `#/curso/${courseId}/leccion`)}
      onMouseEnter={e => { if (!lesson.current && !lesson.locked) e.currentTarget.style.background = "var(--surface)"; }}
      onMouseLeave={e => { if (!lesson.current) e.currentTarget.style.background = "transparent"; }}
    >
      <div style={{
        width: 24, height: 24, borderRadius: "50%", flexShrink: 0,
        background: lesson.done ? "var(--bh-ocean)" : lesson.current ? "var(--primary-500)" : "transparent",
        border: lesson.done || lesson.current ? "none" : "1.5px solid var(--border-strong)",
        color: "#fff", display: "grid", placeItems: "center",
      }}>
        {lesson.done && <Icons.Check size={12} stroke={3}/>}
        {lesson.current && <Icons.Play size={10}/>}
      </div>

      <div style={{
        width: 32, height: 32, borderRadius: "var(--r-sm)", flexShrink: 0,
        background: lesson.done ? "var(--success-soft)" : "var(--surface-2)",
        color: lesson.done ? "var(--bh-ocean)" : "var(--text-muted)",
        display: "grid", placeItems: "center",
      }}>
        <Ico size={15}/>
      </div>

      <div style={{ flex: 1, minWidth: 0 }}>
        <Text size="sm" style={{
          fontWeight: lesson.current ? 600 : 500,
          color: lesson.current ? "var(--primary-700)" : "var(--text-strong)",
        }}>
          {lesson.title}
        </Text>
        <div className="flex items-center gap-3 mt-1">
          <Text size="xs" muted>{typeLabel}</Text>
          <span style={{ width: 3, height: 3, borderRadius: "50%", background: "var(--text-subtle)" }}/>
          <Text size="xs" muted>{lesson.dur}</Text>
          {lesson.done && <>
            <span style={{ width: 3, height: 3, borderRadius: "50%", background: "var(--text-subtle)" }}/>
            <Text size="xs" style={{ color: "var(--success)" }}>Completada</Text>
          </>}
        </div>
      </div>

      <div className="flex gap-2 items-center">
        <IconButton size="sm" title="Apuntes" onClick={e => e.stopPropagation()}><Icons.Notes size={14}/></IconButton>
        <IconButton size="sm" title="Guardar" onClick={e => e.stopPropagation()}><Icons.Bookmark size={14}/></IconButton>
        {lesson.locked
          ? <Icons.Lock size={15} style={{ color: "var(--text-subtle)" }} aria-label="Bloqueada" />
          : <Icons.ChevronRight size={16} style={{ color: "var(--text-subtle)" }}/>}
      </div>
    </div>
  );
};

function countByType(syllabus, type) {
  return syllabus.flatMap(m => m.lessons).filter(l => l.type === type).length;
}

function moduleDur(m) {
  const mins = m.lessons.reduce((a, l) => {
    const n = parseInt(l.dur);
    return isNaN(n) ? a : a + n;
  }, 0);
  if (mins < 60) return `${mins} min`;
  return `${Math.floor(mins / 60)} h ${mins % 60} min`;
}

window.CourseIndexPage = CourseIndexPage;
