/* global React, Icon, Button, CatTag, CleFlag, VideoCard, VideoRow, SectionHead, cx, fmtLabel, CATEGORIES, CAT, VIDEOS, VIDEO_BY_ID, isNewVideo */
// LPE Learning Center — Library (browse + filter + featured).

const { useState: useStateLib, useMemo: useMemoLib } = React;

function FeaturedRibbon({ v, onOpen }) {
  return (
    <div className="ribbon">
      <div className="ribbon-tab">Featured</div>
      <div className="ribbon-body">
        <div className="text">
          <b>{v.title} — {v.sub}</b>
          <span className="sub">{v.code} · {v.durLabel} · {v.cle.eligible ? `${v.cle.credits.toFixed(1)} CLE ${v.cle.type.toLowerCase()}` : "No credit"} · {v.speaker.name}</span>
        </div>
        <div className="ribbon-actions">
          <Button variant="outline-light" size="sm" icon="playFill" onClick={() => onOpen(v.id)}>Watch now</Button>
        </div>
      </div>
    </div>
  );
}

function FeaturedHero({ v, onOpen }) {
  return (
    <div className="cle-hero" style={{ marginBottom: 24 }}>
      <div>
        <div className="ch-eyebrow"><span className="pip" />Featured webinar</div>
        <h1>{v.title}</h1>
        <p className="ch-sub">{v.sub}. {v.blurb}</p>
        <div style={{ display: "flex", gap: 10, marginTop: 20 }}>
          <Button variant="primary" icon="playFill" onClick={() => onOpen(v.id)}>Watch now</Button>
          <Button variant="outline-light" onClick={() => onOpen(v.id)}>View details</Button>
        </div>
      </div>
      <div className="ch-figs">
        <div className="f"><div className="v">{v.durLabel.replace(/\s/g, "")}</div><div className="l">Runtime</div></div>
        <div className="f"><div className="v">{v.cle.eligible ? v.cle.credits.toFixed(1) : "—"}</div><div className="l">CLE hours</div></div>
        <div className="f"><div className="v">{v.rating}</div><div className="l">Rating</div></div>
      </div>
    </div>
  );
}

function ContinueStrip({ items, onOpen, onNavigate }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div className="lc-section-head" style={{ marginTop: 0, marginBottom: 12 }}>
        <h2>Continue watching</h2>
        <a className="more" onClick={() => onNavigate("learning")}>My Learning<Icon name="arrowRight" size={12} /></a>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
        {items.slice(0, 3).map((v) => {
          const thumbUrl = v.thumbnailUrl || (v.youtubeId ? `https://img.youtube.com/vi/${v.youtubeId}/0.jpg` : null);
          return (
            <div key={v.id} className="continue-row" style={{ gridTemplateColumns: "120px 1fr", gap: 14 }} onClick={() => onOpen(v.id)}>
              <div className="cthumb" style={thumbUrl ? { width: 120, backgroundImage: `url(${thumbUrl})`, backgroundSize: "cover", backgroundPosition: "center" } : { width: 120 }}>
                <div className="play-mini"><Icon name="playFill" size={14} /></div>
                <div className="progress"><div className="fill" style={{ width: v.prog + "%" }} /></div>
              </div>
              <div className="continue-info">
                <span className="code">{v.code}</span>
                <h4 style={{ fontSize: 14, margin: "3px 0 5px" }}>{v.title}</h4>
                <div className="pct">{Math.round(v.prog)}% <span className="left">· {Math.round(v.duration * (1 - v.prog / 100))} min left</span></div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LibraryScreen({ query, tweaks, saved, onSave, onOpen, onNavigate, openSpeaker, progressMap, videos = window.VIDEOS, videoMap = window.VIDEO_BY_ID }) {
  const [activeCat, setActiveCat] = useStateLib("all");
  const [format, setFormat] = useStateLib("all");
  const [cleOnly, setCleOnly] = useStateLib(false);
  const [ethicsOnly, setEthicsOnly] = useStateLib(false);
  const [creditsMin, setCreditsMin] = useStateLib("all");
  const [speaker, setSpeaker] = useStateLib("all");
  const [sort, setSort] = useStateLib("newest");
  const [view, setView] = useStateLib(tweaks.libraryView || "grid");

  React.useEffect(() => { setView(tweaks.libraryView || "grid"); }, [tweaks.libraryView]);

  const featured = videoMap["LPE-W18"] || videos[0];
  const speakers = useMemoLib(() => [...new Set(videos.map((v) => v.speaker.name))], [videos]);

  const inProgress = useMemoLib(() => videos
    .map((v) => ({ ...v, prog: progressMap[v.id] != null ? progressMap[v.id] : v.progress }))
    .filter((v) => v.prog > 0 && v.prog < 100)
    .sort((a, b) => b.prog - a.prog), [progressMap, videos]);

  const counts = useMemoLib(() => {
    const c = { all: videos.length };
    CATEGORIES.forEach((cat) => { c[cat.id] = videos.filter((v) => v.cats.includes(cat.id)).length; });
    return c;
  }, [videos]);

  const filtered = useMemoLib(() => {
    let list = videos.slice();
    const q = (query || "").trim().toLowerCase();
    if (q) list = list.filter((v) =>
      (v.title + " " + v.sub + " " + v.code + " " + v.speaker.name + " " + v.cats.map((c) => CAT[c].label).join(" ")).toLowerCase().includes(q)
    );
    if (activeCat !== "all") list = list.filter((v) => v.cats.includes(activeCat));
    if (format !== "all") list = list.filter((v) => v.format === format);
    if (speaker !== "all") list = list.filter((v) => v.speaker.name === speaker);
    if (cleOnly) list = list.filter((v) => v.cle.eligible);
    if (ethicsOnly) list = list.filter((v) => v.cle.eligible && v.cle.type === "Ethics");
    if (creditsMin !== "all") {
      const minVal = parseFloat(creditsMin);
      list = list.filter((v) => v.cle.eligible && v.cle.credits >= minVal);
    }
    if (sort === "newest") list.sort((a, b) => new Date(b.date) - new Date(a.date));
    else if (sort === "added") list.sort((a, b) => new Date(b.addedOn) - new Date(a.addedOn));
    else if (sort === "popular") list.sort((a, b) => b.views - a.views);
    else if (sort === "rating") list.sort((a, b) => b.rating - a.rating);
    else if (sort === "shortest") list.sort((a, b) => a.duration - b.duration);
    else if (sort === "credits") list.sort((a, b) => (b.cle.eligible ? b.cle.credits : 0) - (a.cle.eligible ? a.cle.credits : 0));
    return list;
  }, [query, activeCat, format, speaker, cleOnly, ethicsOnly, creditsMin, sort, videos]);

  return (
    <div className="lc-page">
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow">Learning Center</div>
          <h1>Webinars &amp; tutorials</h1>
          <p className="subtitle">{tweaks.hideCle ? "On-demand sessions on valuing, buying, and selling a law practice. Filter by topic, expand your expertise, and pick up where you left off." : "On-demand sessions on valuing, buying, and selling a law practice. Filter by topic, earn CLE credit, and pick up where you left off."}</p>
        </div>
        <div className="header-actions">
          <Button variant="ghost" icon="calendar" onClick={() => onNavigate("upcoming")}>Upcoming live</Button>
        </div>
      </div>

      {inProgress.length ? <ContinueStrip items={inProgress} onOpen={onOpen} onNavigate={onNavigate} /> : null}

      {tweaks.hero === "ribbon" ? <FeaturedRibbon v={featured} onOpen={onOpen} /> : null}
      {tweaks.hero === "feature" ? <FeaturedHero v={featured} onOpen={onOpen} /> : null}

      <div className="lc-toolbar">
        <div className="lc-chiprow">
          <button className={cx("lc-chip", activeCat === "all" && "active")} onClick={() => setActiveCat("all")}>
            All topics <span className="ct">{counts.all}</span>
          </button>
          {CATEGORIES.map((c) => (
            <button key={c.id} className={cx("lc-chip", activeCat === c.id && "active")} onClick={() => setActiveCat(c.id)}>
              {c.label} <span className="ct">{counts[c.id]}</span>
            </button>
          ))}
        </div>
      </div>

      <div className="lc-toolbar">
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <div className="lc-segment">
            {[["all", "All"], ["webinar", "Webinars"], ["tutorial", "Tutorials"], ["session", "Sessions"]].map(([id, lab]) => (
              <button key={id} className={cx(format === id && "active")} onClick={() => setFormat(id)}>{lab}</button>
            ))}
          </div>
          {!tweaks.hideCle && (
            <>
              <button className={cx("lc-chip", cleOnly && "active")} onClick={() => setCleOnly((s) => !s)} style={{ height: 34 }}>
                <Icon name="award" size={13} /> CLE eligible
              </button>
              <button className={cx("lc-chip", ethicsOnly && "active")} onClick={() => setEthicsOnly((s) => !s)} style={{ height: 34 }}>
                Ethics
              </button>
              <select className="select-styled" value={creditsMin} onChange={(e) => setCreditsMin(e.target.value)}>
                <option value="all">All credits</option>
                <option value="1.0">1.0+ credits</option>
                <option value="1.5">1.5+ credits</option>
              </select>
            </>
          )}
          <select className="select-styled" value={speaker} onChange={(e) => setSpeaker(e.target.value)}>
            <option value="all">All speakers</option>
            {speakers.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
        </div>
        <div className="lc-toolbar-right">
          <span className="lc-results" style={{ margin: 0 }}><b>{filtered.length}</b> {filtered.length === 1 ? "session" : "sessions"}</span>
          <select className="select-styled" value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="newest">Newest</option>
            <option value="rating">Rating</option>
            {!tweaks.hideCle && <option value="credits">Credits</option>}
            <option value="added">Newly added</option>
            <option value="popular">Most watched</option>
            <option value="shortest">Shortest</option>
          </select>
          <div className="view-toggle">
            <button className={cx(view === "grid" && "active")} onClick={() => setView("grid")} title="Grid"><Icon name="grid" size={16} /></button>
            <button className={cx(view === "list" && "active")} onClick={() => setView("list")} title="List"><Icon name="list" size={16} /></button>
          </div>
        </div>
      </div>

      {(activeCat !== "all" || query || speaker !== "all" || cleOnly || ethicsOnly || creditsMin !== "all") ? (
        <p className="lc-results">Showing {filtered.length} {filtered.length === 1 ? "result" : "results"}{activeCat !== "all" ? <> in <b>{CAT[activeCat].label}</b></> : null}{speaker !== "all" ? <> by <b>{speaker}</b></> : null}{creditsMin !== "all" ? <> with <b>{creditsMin}+ credits</b></> : null}{query ? <> matching “{query}”</> : null}</p>
      ) : null}

      {filtered.length === 0 ? (
        <div className="empty">
          <Icon name="search" size={28} />
          <h4>No sessions match these filters</h4>
          <p>Remove a topic or format filter, or clear your search to see the full library.</p>
        </div>
      ) : view === "grid" ? (
        <div className="lc-grid">
          {filtered.map((v) => (
            <VideoCard key={v.id} v={v} saved={saved.has(v.id)} onSave={onSave} onOpen={onOpen} openSpeaker={openSpeaker} />
          ))}
        </div>
      ) : (
        <div className="lc-list">
          {filtered.map((v) => <VideoRow key={v.id} v={v} onOpen={onOpen} openSpeaker={openSpeaker} />)}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { LibraryScreen, FeaturedRibbon, FeaturedHero });
