/* global React, useSession, asViewer, Icons, Button, Input, IconButton, Card, Heading, Text, Avatar, AvatarGroup, Badge, Progress, Checkbox, Divider, AppShell, navigate, DATA, MiniCourseCard, Select, Tabs */

const CatalogPage = () => {
  const signedIn = useSession();
  const [query, setQuery] = React.useState("");
  const [tracks, setTracks] = React.useState(new Set());
  const [levels, setLevels] = React.useState(new Set());
  const [langs, setLangs] = React.useState(new Set());
  const [cert, setCert] = React.useState(false);
  const [sort, setSort] = React.useState("available");

  const toggle = (set, setter, val) => {
    const n = new Set(set);
    n.has(val) ? n.delete(val) : n.add(val);
    setter(n);
  };

  const filtered = React.useMemo(() => {
    let list = DATA.COURSES.map(c => asViewer(c, signedIn)).filter(c => {
      if (query && !(c.title + " " + c.subtitle + " " + c.track).toLowerCase().includes(query.toLowerCase())) return false;
      if (tracks.size && !tracks.has(c.track)) return false;
      if (levels.size && !levels.has(c.level)) return false;
      if (cert && !c.cert) return false;
      return true;
    });
    // Courses open for enrolment first; "Próximamente" entries after them.
    list = [...list].sort((a, b) => (a.comingSoon ? 1 : 0) - (b.comingSoon ? 1 : 0));
    if (sort === "new") list = [...list].sort((a, b) => (b.new ? 1 : 0) - (a.new ? 1 : 0));
    return list;
  }, [query, tracks, levels, cert, sort, signedIn]);

  const activeFilters = tracks.size + levels.size + (cert ? 1 : 0);

  return (
    <AppShell active="#/cursos" breadcrumbs={signedIn ? [{ label: "Mi espacio", href: "#/mi-espacio" }, { label: "Catálogo de cursos" }] : null}>
      <div data-screen-label="03 Catálogo">
        {/* Landing hero — navy (same as the app bar), content-sized, illustration along the bottom */}
        <section className="bh-landing" aria-labelledby="landing-title">
          <div className="bh-landing-top">
            <LandingRings />
            <div className="bh-landing-inner">
              <div className="bh-landing-copy">
                <h1 id="landing-title" className="bh-landing-title">
                  Formación para quienes protegen la <em>dignidad humana</em>
                </h1>
                <p className="bh-landing-lead">
                  Cursos y programas en derechos humanos, acción humanitaria y construcción de paz,
                  para profesionales, organizaciones y personas comprometidas con su defensa.
                </p>

                <div className="bh-landing-actions">
                  <a href="#catalogo" className="gs-btn gs-btn--lg bh-landing-btn-primary"
                     onClick={e => { e.preventDefault(); document.getElementById("catalogo")?.scrollIntoView({ behavior: "smooth" }); }}>
                    Explorar cursos
                  </a>
                  <a href={signedIn ? "#/mi-espacio" : "#/login"} className="gs-btn gs-btn--lg gs-btn--inverse">
                    Acceder al Campus
                  </a>
                </div>
              </div>
            </div>
          </div>

          <div className="bh-landing-people-wrap">
            <img className="bh-landing-people" src="/images/hero-people.webp" width="2400" height="563"
                 alt="Ilustración de personas diversas de distintas culturas, edades y orígenes" />
          </div>
        </section>

        <div id="catalogo" className="grid" style={{ gridTemplateColumns: "260px minmax(0, 1fr)", scrollMarginTop: 96 }}>
          {/* Filters */}
          <aside>
            <div className="flex items-center justify-between mb-4">
              <Heading size="h5">Filtros</Heading>
              {activeFilters > 0 && (
                <Button variant="link" size="sm" onClick={() => { setTracks(new Set()); setLevels(new Set()); setCert(false); }}>
                  Limpiar ({activeFilters})
                </Button>
              )}
            </div>

            <div className="flex-col gap-6">
              <FilterGroup title="Área temática">
                {DATA.TRACKS.map(t => (
                  <div key={t.id} className="flex items-center justify-between">
                    <Checkbox
                      label={t.label}
                      checked={tracks.has(t.label)}
                      onChange={() => toggle(tracks, setTracks, t.label)}
                    />
                    <Text size="xs" subtle>{DATA.COURSES.filter(c => c.track === t.label).length}</Text>
                  </div>
                ))}
              </FilterGroup>

              <FilterGroup title="Nivel">
                {["Introductorio", "Intermedio", "Avanzado"].map(l => (
                  <Checkbox
                    key={l}
                    label={l}
                    checked={levels.has(l)}
                    onChange={() => toggle(levels, setLevels, l)}
                  />
                ))}
              </FilterGroup>

              <FilterGroup title="Idioma">
                {["Español", "Inglés", "Francés", "Árabe"].map(l => (
                  <Checkbox
                    key={l}
                    label={l}
                    checked={langs.has(l)}
                    onChange={() => toggle(langs, setLangs, l)}
                  />
                ))}
              </FilterGroup>

              <FilterGroup title="Duración">
                <div className="flex-col gap-2">
                  <Checkbox label="Menos de 5 horas" />
                  <Checkbox label="5 a 10 horas" />
                  <Checkbox label="10 a 20 horas" />
                  <Checkbox label="Más de 20 horas" />
                </div>
              </FilterGroup>

              <FilterGroup title="Otros">
                <Checkbox label="Con certificación" checked={cert} onChange={setCert} />
                <Checkbox label="Gratuitos" />
                <Checkbox label="Con sesión en vivo" />
              </FilterGroup>
            </div>
          </aside>

          {/* Results */}
          <div>
            <div className="flex items-center justify-between mb-4 wrap gap-3">
              <Text>
                <strong>{filtered.length}</strong> {filtered.length === 1 ? "curso" : "cursos"}
                {activeFilters > 0 && <span style={{ color: "var(--text-muted)" }}> · {activeFilters} {activeFilters === 1 ? "filtro" : "filtros"} activos</span>}
              </Text>
              <div className="flex items-center gap-3">
                <Select
                  value={sort} onChange={setSort}
                  options={[
                    { value: "available", label: "Disponibles primero" },
                    { value: "new",       label: "Más recientes" },
                  ]}
                />
              </div>
            </div>

            {/* Active chips */}
            {activeFilters > 0 && (
              <div className="flex items-center gap-2 wrap mb-4">
                {[...tracks].map(t => (
                  <Chip key={t} label={t} onRemove={() => toggle(tracks, setTracks, t)} />
                ))}
                {[...levels].map(l => (
                  <Chip key={l} label={l} onRemove={() => toggle(levels, setLevels, l)} />
                ))}
                {cert && <Chip label="Con certificación" onRemove={() => setCert(false)} />}
              </div>
            )}

            <div className="grid grid-3">
              {filtered.map(c => <CatalogCard key={c.id} course={c} />)}
            </div>

            {filtered.length === 0 && (
              <Card className="text-center" style={{ padding: 64 }}>
                <div style={{ width: 56, height: 56, borderRadius: "50%", background: "var(--surface-2)", display: "grid", placeItems: "center", margin: "0 auto 16px" }}>
                  <Icons.Search size={24} style={{ color: "var(--text-subtle)" }} />
                </div>
                <Heading size="h4" className="mb-2">No encontramos cursos</Heading>
                <Text muted>Prueba con otros términos o limpia los filtros.</Text>
              </Card>
            )}
          </div>
        </div>
      </div>
    </AppShell>
  );
};



// Slow, concentric rings echoing the hemicycle of the Council room — the background motion.
const LandingRings = () => (
  <svg className="bh-landing-rings" viewBox="0 0 1000 1000" preserveAspectRatio="xMidYMid slice">
    {[140, 220, 300, 380, 460, 540, 620].map((r, i) => (
      <circle key={r} cx="760" cy="980" r={r}
              className={`bh-ring bh-ring--${i % 3}`}
              strokeDasharray={i % 2 ? "2 10" : "60 18"} />
    ))}
  </svg>
);

const FilterGroup = ({ title, children }) => (
  <div>
    <div style={{
      fontSize: 13, fontWeight: 600, color: "var(--text-strong)", paddingBottom: 10,
      borderBottom: "1px solid var(--border)", marginBottom: 14,
    }}>{title}</div>
    <div className="flex-col gap-2">{children}</div>
  </div>
);

const Chip = ({ label, onRemove }) => (
  <span className="gs-badge gs-badge--outline" style={{ padding: "4px 8px", fontSize: 12, gap: 6, cursor: "default" }}>
    {label}
    <button onClick={onRemove} style={{ background: "none", border: "none", padding: 0, color: "inherit", cursor: "pointer", display: "grid", placeItems: "center" }}>
      <Icons.X size={12} stroke={2.5} />
    </button>
  </span>
);

const CatalogCard = ({ course }) => {
  const status = course.comingSoon ? "Próximamente" : course.completed ? "Completado" : course.enrolled ? "Inscrito" : course.new ? "Nuevo" : null;
  return (
    <a href={`#/curso/${course.id}`} className="course-card">
      <div className="photo photo--plain" style={{ backgroundImage: `url(${course.photo})` }}>
        {course.badge && <img className="course-badge course-badge--card" src={course.badge} alt="" width="64" height="64" />}
      </div>
      <div className="course-card-body">
        <div className="course-card-kicker">
          <span>{course.track}</span>
          {status && <span className="course-card-status">{status}</span>}
        </div>
        <div className="course-card-title">{course.title}</div>
        <p className="course-card-summary">{course.subtitle}</p>

        {course.enrolled && course.progress > 0 && (
          <div className="flex items-center gap-3 mt-1">
            <div style={{ flex: 1 }}><Progress value={course.progress} variant={course.completed ? "success" : undefined} /></div>
            <Text size="xs" style={{ fontWeight: 600, color: "var(--text-strong)" }}>{course.progress}%</Text>
          </div>
        )}

        <div className="course-card-meta">
          <span>{course.level}</span>
          <span aria-hidden="true">·</span>
          <span>{course.duration}</span>
          <span aria-hidden="true">·</span>
          <span>{course.units ? `${course.units.length} unidades` : `${course.modules} módulos`}</span>
        </div>
        <div className="course-card-author">{course.instructor.name}</div>
      </div>
    </a>
  );
};

window.CatalogPage = CatalogPage;
window.CatalogCard = CatalogCard;
