function TrainingView({ openSession }) {
  const { TRAINING_SESSIONS, TAGS } = window.DATA;
  const { Btn, Tag } = window.UI;
  const [filter, setFilter] = useState("all");
  const [sort, setSort] = useState("newest");

  const filtered = TRAINING_SESSIONS.filter(s => filter === "all" || s.category === filter);

  return (
    <>
      <window.TopBar
        title="Training Sessions"
        subtitle="Stay up-to-date with on-demand training from our expert student-athlete advisors and guest speakers."
        right={
          <div style={{ display: "flex", gap: 10 }}>
            <select value={sort} onChange={e => setSort(e.target.value)} style={{
              padding: "8px 10px", border: "1px solid var(--line)", borderRadius: 8,
              background: "var(--card)", fontSize: 13,
            }}>
              <option value="newest">Newest first</option>
              <option value="oldest">Oldest first</option>
              <option value="popular">Most watched</option>
            </select>
          </div>
        }
      />

      <div style={{ padding: 32 }}>
        {/* Filter pills */}
        <div style={{ display: "flex", gap: 8, marginBottom: 24, flexWrap: "wrap" }}>
          <FilterPill active={filter === "all"} onClick={() => setFilter("all")} label={`All sessions (${TRAINING_SESSIONS.length})`} />
          {Object.entries(TAGS).map(([key, def]) => {
            const count = TRAINING_SESSIONS.filter(s => s.category === key).length;
            if (!count) return null;
            return (
              <FilterPill
                key={key}
                active={filter === key}
                onClick={() => setFilter(key)}
                label={`${def.label} (${count})`}
                color={def.color}
              />
            );
          })}
        </div>

        {/* Featured current */}
        {filter === "all" && (
          <div style={{ marginBottom: 32 }}>
            <div style={{ fontSize: 11, letterSpacing: 0.06, textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 500, marginBottom: 12 }}>
              April 2026 · This month's session
            </div>
            <FeaturedSessionCard session={TRAINING_SESSIONS[0]} onOpen={() => openSession(TRAINING_SESSIONS[0])} />
          </div>
        )}

        <div style={{ fontSize: 11, letterSpacing: 0.06, textTransform: "uppercase", color: "var(--ink-3)", fontWeight: 500, marginBottom: 12 }}>
          {filter === "all" ? "Archive" : TAGS[filter]?.label + " sessions"}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 16 }}>
          {(filter === "all" ? filtered.slice(1) : filtered).map(s => (
            <SessionCard key={s.id} session={s} onOpen={() => openSession(s)} />
          ))}
        </div>
      </div>
    </>
  );
}

function FilterPill({ active, onClick, label, color }) {
  return (
    <button
      onClick={onClick}
      style={{
        padding: "7px 13px", borderRadius: 999,
        fontSize: 12.5, fontWeight: 500, letterSpacing: -0.005,
        background: active ? "var(--ink)" : "var(--card)",
        color: active ? "white" : "var(--ink-2)",
        border: active ? "1px solid var(--ink)" : "1px solid var(--line)",
        display: "inline-flex", alignItems: "center", gap: 7,
      }}
    >
      {color && <span style={{ width: 6, height: 6, borderRadius: 999, background: `var(--${color})` }} />}
      {label}
    </button>
  );
}

function FeaturedSessionCard({ session, onOpen }) {
  const pct = session.completed ? 100 : (session.watchedSeconds / (session.duration * 60)) * 100;
  return (
    <div
      onClick={onOpen}
      className="hover-lift"
      style={{
        display: "grid", gridTemplateColumns: "400px 1fr", gap: 0,
        border: "1px solid var(--line)", borderRadius: "var(--radius-lg)",
        overflow: "hidden", cursor: "pointer", background: "var(--card)",
      }}
    >
      <div style={{ aspectRatio: "16/10", background: session.thumb, position: "relative", overflow: "hidden" }}>
        {/* Subtle bottom gradient for legibility */}
        <div style={{
          position: "absolute", left: 0, right: 0, bottom: 0, height: "55%",
          background: "linear-gradient(to top, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0) 100%)",
          pointerEvents: "none",
        }} />
        <div style={{ position: "absolute", top: 14, left: 14 }}>
          <window.UI.Tag cat={session.category} />
        </div>
        {/* Playback pill — bottom-left */}
        <div style={{
          position: "absolute", bottom: 14, left: 14,
          display: "inline-flex", alignItems: "center", gap: 6,
          background: "rgba(255,255,255,0.95)",
          borderRadius: 999, padding: 5,
          boxShadow: "0 4px 14px -4px rgba(0,0,0,0.3)",
        }}>
          <div style={{
            width: 32, height: 32, borderRadius: 999,
            background: "#1B3D2F", color: "white",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            paddingLeft: 2,
          }}>
            <window.I.Play size={13} stroke="white" sw={2.5} />
          </div>
          <div style={{ fontSize: 12, fontWeight: 500, color: "var(--ink)", padding: "0 10px 0 2px", letterSpacing: -0.005 }}>
            Play episode
          </div>
        </div>
        {/* Duration chip — bottom-right */}
        <div style={{
          position: "absolute", bottom: 16, right: 14,
          fontSize: 11, color: "white",
          background: "rgba(0,0,0,0.55)",
          padding: "4px 9px", borderRadius: 999,
          fontFamily: "Geist Mono, monospace",
          display: "inline-flex", alignItems: "center", gap: 5,
        }}>
          <window.I.Clock size={11} stroke="white" />
          {session.duration}:00
        </div>
        {pct > 0 && pct < 100 && (
          <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 3, background: "rgba(0,0,0,0.3)" }}>
            <div style={{ width: `${pct}%`, height: "100%", background: "#E8A020" }} />
          </div>
        )}
      </div>
      <div style={{ padding: 28, display: "flex", flexDirection: "column", justifyContent: "center" }}>
        <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginBottom: 6, letterSpacing: 0.02 }}>
          {new Date(session.date).toLocaleDateString("en-US", { month: "long", year: "numeric" })}
        </div>
        <h3 className="serif" style={{ fontSize: 28, lineHeight: 1.1, margin: "0 0 10px", letterSpacing: -0.015 }}>{session.title}</h3>
        <p style={{ color: "var(--ink-3)", fontSize: 14, lineHeight: 1.5, margin: "0 0 18px", maxWidth: 520 }}>{session.subtitle}</p>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <window.UI.Avatar initials={session.instructor.split(" ").map(n => n[0]).join("").slice(0, 2)} size={30} color="var(--ink-2)" />
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: -0.005 }}>{session.instructor}</div>
            <div style={{ fontSize: 11.5, color: "var(--ink-3)" }}>{session.role}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function SessionCard({ session, onOpen }) {
  const pct = session.completed ? 100 : (session.watchedSeconds / (session.duration * 60)) * 100;
  return (
    <div
      onClick={onOpen}
      className="hover-lift"
      style={{
        border: "1px solid var(--line)", borderRadius: "var(--radius)",
        overflow: "hidden", cursor: "pointer", background: "var(--card)",
      }}
    >
      <div style={{ aspectRatio: "16/10", background: session.thumb, position: "relative", overflow: "hidden" }}>
        {/* Subtle bottom gradient for legibility */}
        <div style={{
          position: "absolute", left: 0, right: 0, bottom: 0, height: "55%",
          background: "linear-gradient(to top, rgba(0,0,0,0.5) 0%, rgba(0,0,0,0) 100%)",
          pointerEvents: "none",
        }} />
        <div style={{ position: "absolute", top: 10, left: 10 }}>
          <window.UI.Tag cat={session.category} />
        </div>
        {session.completed && (
          <div style={{ position: "absolute", top: 10, right: 10, display: "inline-flex", alignItems: "center", gap: 5, padding: "3px 8px", background: "rgba(0,0,0,0.5)", color: "white", borderRadius: 999, fontSize: 10.5, fontWeight: 500 }}>
            <window.I.Check size={11} sw={3} /> Watched
          </div>
        )}
        {/* Playback pill — bottom-left */}
        <div style={{
          position: "absolute", bottom: 10, left: 10,
          display: "inline-flex", alignItems: "center", gap: 5,
          background: "rgba(255,255,255,0.95)",
          borderRadius: 999, padding: 4,
          boxShadow: "0 3px 10px -3px rgba(0,0,0,0.3)",
        }}>
          <div style={{
            width: 24, height: 24, borderRadius: 999,
            background: "#1B3D2F", color: "white",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            paddingLeft: 1,
          }}>
            <window.I.Play size={10} stroke="white" sw={2.5} />
          </div>
          <div style={{ fontSize: 11, fontWeight: 500, color: "var(--ink)", padding: "0 8px 0 1px", letterSpacing: -0.005 }}>
            Play
          </div>
        </div>
        {/* Duration chip */}
        <div style={{
          position: "absolute", bottom: 12, right: 10,
          fontSize: 10.5, padding: "3px 7px",
          background: "rgba(0,0,0,0.55)", color: "white",
          borderRadius: 999, fontFamily: "Geist Mono, monospace",
          display: "inline-flex", alignItems: "center", gap: 4,
        }}>
          <window.I.Clock size={10} stroke="white" />
          {session.duration}:00
        </div>
        {pct > 0 && pct < 100 && (
          <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 3, background: "rgba(0,0,0,0.3)" }}>
            <div style={{ width: `${pct}%`, height: "100%", background: "#E8A020" }} />
          </div>
        )}
      </div>
      <div style={{ padding: 14 }}>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginBottom: 4, letterSpacing: 0.02 }}>
          {new Date(session.date).toLocaleDateString("en-US", { month: "short", year: "numeric" })} · {session.instructor}
        </div>
        <div style={{ fontSize: 14, fontWeight: 500, lineHeight: 1.3, letterSpacing: -0.005, marginBottom: 6 }}>{session.title}</div>
        <div style={{ fontSize: 12, color: "var(--ink-3)", lineHeight: 1.4, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{session.subtitle}</div>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 10, fontSize: 11.5, color: "var(--ink-3)" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><window.I.Clock size={11} /> {session.duration} min</span>
          <span>·</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><window.I.Eye size={11} /> {session.views}</span>
          <span>·</span>
          <span>{session.resources.length} resources</span>
        </div>
      </div>
    </div>
  );
}

function SessionModal({ session, onClose }) {
  const { Modal, Btn, Tag } = window.UI;
  const [playing, setPlaying] = useState(false);
  const [progress, setProgress] = useState(session ? (session.watchedSeconds / (session.duration * 60)) * 100 : 0);
  const startProgress = useRef(session ? (session.watchedSeconds / (session.duration * 60)) * 100 : 0);

  useEffect(() => {
    if (!playing) return;
    const iv = setInterval(() => setProgress(p => Math.min(100, p + 0.7)), 80);
    return () => clearInterval(iv);
  }, [playing]);

  // On close, record the minutes watched this visit into the engagement log.
  const handleClose = () => {
    if (session) {
      const delta = Math.max(0, progress - startProgress.current);
      const minutes = Math.round((delta / 100) * session.duration);
      if (minutes > 0) {
        window.trackWatch && window.trackWatch({
          source: "training", refId: session.id, title: session.title,
          pillar: session.category, grade: null, assetType: "video", minutes,
        });
      }
      if (progress >= 99 && !session.completed) {
        window.trackComplete && window.trackComplete({
          source: "training", refId: session.id, title: session.title,
          pillar: session.category, grade: null, assetType: "video",
        });
      }
    }
    onClose();
  };

  if (!session) return null;

  const elapsed = (progress / 100) * session.duration;
  const fmtTime = (mins) => `${Math.floor(mins)}:${String(Math.floor((mins % 1) * 60)).padStart(2, "0")}`;

  return (
    <Modal open={!!session} onClose={handleClose} width={880}>
      <div style={{
        aspectRatio: "16/9", background: session.thumb, position: "relative",
        display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer",
      }} onClick={() => setPlaying(p => !p)}>
        {!playing && (
          <div style={{
            width: 76, height: 76, borderRadius: 999,
            background: "rgba(255,255,255,0.95)",
            display: "flex", alignItems: "center", justifyContent: "center", paddingLeft: 5,
            boxShadow: "0 8px 32px rgba(0,0,0,0.3)",
          }}>
            <window.I.Play size={30} stroke="var(--ink)" sw={2.5} />
          </div>
        )}
        {playing && (
          <div style={{ fontSize: 13, color: "white", fontFamily: "Geist Mono, monospace", background: "rgba(0,0,0,0.5)", padding: "4px 10px", borderRadius: 4 }}>
            ▶ Playing · {fmtTime(elapsed)} / {session.duration}:00
          </div>
        )}
        <button
          onClick={(e) => { e.stopPropagation(); handleClose(); }}
          style={{ position: "absolute", top: 14, right: 14, width: 32, height: 32, borderRadius: 999, background: "rgba(0,0,0,0.5)", color: "white", display: "flex", alignItems: "center", justifyContent: "center" }}
        >
          <window.I.X size={15} />
        </button>
        {/* Progress bar */}
        <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "0 16px 12px" }}>
          <div style={{ height: 4, background: "rgba(255,255,255,0.25)", borderRadius: 2, overflow: "hidden" }}>
            <div style={{ width: `${progress}%`, height: "100%", background: "#E8A020", transition: "width 80ms linear" }} />
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", marginTop: 6, color: "white", fontSize: 11, fontFamily: "Geist Mono, monospace", opacity: 0.85 }}>
            <span>{fmtTime(elapsed)}</span>
            <span>{session.duration}:00</span>
          </div>
        </div>
      </div>

      <div style={{ padding: 28 }}>
        <div style={{ display: "flex", gap: 8, marginBottom: 10 }}>
          <Tag cat={session.category} size="md" />
          <span style={{ fontSize: 12, color: "var(--ink-3)" }}>
            {new Date(session.date).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" })} · {session.duration} min
          </span>
        </div>
        <h2 className="serif" style={{ fontSize: 30, margin: "0 0 10px", letterSpacing: -0.015, lineHeight: 1.1 }}>{session.title}</h2>
        <p style={{ color: "var(--ink-3)", fontSize: 14.5, lineHeight: 1.55, margin: 0 }}>{session.subtitle}</p>

        <div style={{ display: "flex", alignItems: "center", gap: 12, marginTop: 20, paddingTop: 20, borderTop: "1px solid var(--line)" }}>
          <window.UI.Avatar initials={session.instructor.split(" ").map(n => n[0]).join("").slice(0, 2)} size={40} color="var(--ink-2)" />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: -0.005 }}>{session.instructor}</div>
            <div style={{ fontSize: 12.5, color: "var(--ink-3)" }}>{session.role}</div>
          </div>
          <Btn variant="outline" size="sm" icon={<window.I.Bookmark size={13} />}>Save</Btn>
          <Btn variant="outline" size="sm" icon={<window.I.Share size={13} />}>Share</Btn>
        </div>

        {/* Resources */}
        <div style={{ marginTop: 28 }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 12 }}>
            <div style={{ fontSize: 14, fontWeight: 500, letterSpacing: -0.005 }}>Supplemental resources</div>
            <div style={{ fontSize: 12, color: "var(--ink-3)" }}>{session.resources.length} files</div>
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {session.resources.map((r, i) => (
              <div key={i} style={{
                display: "flex", alignItems: "center", gap: 12,
                padding: "12px 14px", border: "1px solid var(--line)", borderRadius: 10,
                background: "var(--bg-2)",
              }}>
                <div style={{
                  width: 38, height: 38, borderRadius: 8,
                  background: r.type === "PDF" ? "#F5F0EE" : r.type === "DOCX" ? "var(--accent-soft)" : "var(--success-soft)",
                  color: r.type === "PDF" ? "#5A2A00" : r.type === "DOCX" ? "var(--accent-ink)" : "#14504F",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 10, fontWeight: 600, letterSpacing: 0.03,
                }}>
                  {r.type}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, letterSpacing: -0.005 }}>{r.name}</div>
                  <div style={{ fontSize: 11.5, color: "var(--ink-3)", marginTop: 2 }}>{r.size}</div>
                </div>
                <Btn variant="ghost" size="sm" icon={<window.I.Share size={13} />}>Share</Btn>
                <Btn variant="outline" size="sm" icon={<window.I.Download size={13} />}
                  onClick={() => window.trackDownload && window.trackDownload({
                    source: "training", refId: session.id, title: r.name,
                    pillar: session.category, grade: null, assetType: (r.type || "pdf").toLowerCase(),
                  })}
                >Download</Btn>
              </div>
            ))}
          </div>
        </div>
      </div>
    </Modal>
  );
}

window.TrainingView = TrainingView;
window.SessionModal = SessionModal;
