/* global React, Icon, Button, Stat, SectionHead, VideoCard, CatTag, CleFlag, Av, cx, fmtLabel, VIDEOS, VIDEO_BY_ID, CAT, COLLATERAL, LEARNER, daysSince */
// LPE Learning Center — My Learning portal + Collateral library.

const { useState: useStateLearn, useMemo: useMemoL } = React;

function MyLearningScreen({ tweaks, progressMap, attendedSet, learner, saved, onSave, onOpen, onNavigate, openSpeaker, onToast, videos = window.VIDEOS, videoMap = window.VIDEO_BY_ID }) {
  const merged = useMemoL(() => videos.map((v) => ({ ...v, prog: progressMap[v.id] != null ? progressMap[v.id] : v.progress })), [progressMap, videos]);

  const inProgress = merged.filter((v) => v.prog > 0 && v.prog < 100).sort((a, b) => b.prog - a.prog);
  const completed = merged.filter((v) => v.prog >= 100);
  const attendedList = merged.filter((v) => attendedSet.has(v.id));
  const savedList = [...saved].map((id) => videoMap[id]).filter(Boolean);

  const minutesWatched = merged.reduce((s, v) => s + (parseFloat(v.duration) || 0) * (Math.min(100, parseFloat(v.prog) || 0) / 100), 0);
  const cleEarned = attendedList.reduce((s, v) => s + (v.cle && v.cle.eligible ? (parseFloat(v.cle.credits) || 0) : 0), 0);
  const certCount = attendedList.filter((v) => v.cle.eligible).length;

  const interestCats = {};
  [...completed, ...inProgress, ...attendedList].forEach((v) => v.cats.forEach((c) => { interestCats[c] = (interestCats[c] || 0) + 1; }));
  (learner.interests || []).forEach((c) => { interestCats[c] = (interestCats[c] || 0) + 2; });
  const topCats = Object.entries(interestCats).sort((a, b) => b[1] - a[1]).slice(0, 2).map((e) => e[0]);
  const recos = merged.filter((v) => v.prog === 0 && v.cats.some((c) => topCats.includes(c))).slice(0, 3);
  const topCatLabel = topCats.map((c) => CAT[c] && CAT[c].label).filter(Boolean).join(" and ");

  function exportCsv() {
    const rows = [["Program", "Code", "Topic", "Format", "Duration (min)", "CLE hours", "CLE type", "Status"]];
    completed.forEach((v) => rows.push([v.title, v.code, v.cats.map((c) => CAT[c] ? CAT[c].label : c).join("; "), fmtLabel(v.format), v.duration, v.cle.eligible ? v.cle.credits : 0, v.cle.type || "—", "Completed"]));
    
    const csvString = rows.map(e => e.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(",")).join("\n");
    const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.setAttribute("href", url);
    link.setAttribute("download", `lpe_learning_history_${new Date().toISOString().split('T')[0]}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    onToast(`Exported ${completed.length} rows to CSV`);
  }

  return (
    <div className="lc-page">
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow">My Learning</div>
          <h1>Welcome back, {learner.name.split(" ")[0]}</h1>
          <p className="subtitle">{tweaks.hideCle ? "Your progress and completed sessions in one place. Pick up where you left off below." : "Your progress, completed sessions, and CLE credit — all in one place. Pick up where you left off below."}</p>
        </div>
        <div className="header-actions">
          {!tweaks.hideCle && <Button variant="ghost" icon="award" onClick={() => onNavigate("cle")}>CLE center</Button>}
          <Button variant="primary" icon="video" onClick={() => onNavigate("library")}>Browse library</Button>
        </div>
      </div>

      <div className="lc-statgrid">
        <Stat label="Minutes watched" value={Math.round(minutesWatched)} sub="across all sessions" icon="clock" />
        <Stat label="Completed" value={completed.length} sub={`of ${videos.length} sessions`} icon="checkCircle" />
        {!tweaks.hideCle && <Stat label="CLE credits earned" value={cleEarned.toFixed(1)} accent sub="this reporting period" icon="award" />}
        {!tweaks.hideCle && <Stat label="Certificates" value={certCount} sub="ready to download" icon="certificate" />}
      </div>

      <div className="pace-chip" style={{ marginBottom: 28 }}>
        <Icon name="chart" size={16} />
        <span>You've completed <b>{completed.length}</b> {completed.length === 1 ? "session" : "sessions"} and watched <b>{Math.round(minutesWatched)} minutes</b> — about <b>{Math.round(minutesWatched / 6)} min/week</b> over the last six weeks.</span>
      </div>

      {inProgress.length ? (
        <>
          <SectionHead title="Continue watching" meta={`${inProgress.length} in progress`} />
          <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
            {inProgress.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" onClick={() => onOpen(v.id)}>
                  <div className="cthumb" style={thumbUrl ? { backgroundImage: `url(${thumbUrl})`, backgroundSize: "cover", backgroundPosition: "center" } : undefined}>
                    {!thumbUrl ? <Icon name="playFill" size={20} /> : null}
                    <div className="play-mini"><Icon name="playFill" size={16} /></div>
                    <div className="progress"><div className="fill" style={{ width: v.prog + "%" }} /></div>
                  </div>
                  <div className="continue-info">
                    <span className="code">{v.code} · {fmtLabel(v.format)}</span>
                    <h4>{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 style={{ display: "flex", alignItems: "center", gap: 14 }}>
                    <CleFlag cle={v.cle} />
                    <Button variant="secondary" size="sm" icon="playFill">Resume</Button>
                  </div>
                </div>
              );
            })}
          </div>
        </>
      ) : null}

      {savedList.length ? (
        <>
          <SectionHead title="Saved for later" meta={`${savedList.length} saved`} more="View all" onMore={() => onNavigate("saved")} />
          <div className="lc-grid">
            {savedList.slice(0, 3).map((v) => <VideoCard key={v.id} v={v} saved={saved.has(v.id)} onSave={onSave} onOpen={onOpen} openSpeaker={openSpeaker} />)}
          </div>
        </>
      ) : null}

      {recos.length ? (
        <>
          <SectionHead title="Recommended for you" more="See all" onMore={() => onNavigate("library")} />
          <div className="reco-reason"><Icon name="sparkle" size={13} /> Because you've been watching <b>{topCatLabel || "across topics"}</b></div>
          <div className="lc-grid">
            {recos.map((v) => <VideoCard key={v.id} v={v} saved={saved.has(v.id)} onSave={onSave} onOpen={onOpen} openSpeaker={openSpeaker} />)}
          </div>
        </>
      ) : null}

      <div className="lc-section-head">
        <h2>History</h2>
        <span className="meta">{completed.length} completed</span>
        {completed.length ? <a className="more" onClick={exportCsv}><Icon name="download" size={12} /> Export CSV</a> : null}
      </div>
      {completed.length ? (
        <table className="data-table">
          <thead>
            <tr>
              <th>Session</th>
              <th>Topic</th>
              <th>Format</th>
              <th className="num">Duration</th>
              {!tweaks.hideCle && <th className="num">CLE</th>}
              {!tweaks.hideCle && <th className="num">Ethics</th>}
              <th className="num">Status</th>
            </tr>
          </thead>
          <tbody>
            {completed.map((v) => (
              <tr key={v.id} onClick={() => onOpen(v.id)} style={{ cursor: "pointer" }}>
                <td><div className="t-title">{v.title}</div><div className="t-code">{v.code}</div></td>
                <td>{v.cats.map((c) => CAT[c].label).slice(0, 2).join(", ")}</td>
                <td>{fmtLabel(v.format)}</td>
                <td className="num">{v.durLabel}</td>
                {!tweaks.hideCle && <td className="num">{v.cle.eligible ? v.cle.credits.toFixed(1) : "—"}</td>}
                {!tweaks.hideCle && <td className="num">{v.cle.eligible && v.cle.type === "Ethics" ? v.cle.credits.toFixed(1) : "—"}</td>}
                <td className="num"><span className="link"><Icon name="check" size={12} /> Completed</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      ) : (
        <div className="empty"><Icon name="video" size={28} /><h4>Nothing completed yet</h4><p>{tweaks.hideCle ? "Finish a session and it'll show up here." : "Finish a session and it'll show up here with your CLE status."}</p></div>
      )}
    </div>
  );
}

// ---------- Collateral ----------
function collDownloads(id) { let h = 0; for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0; return 120 + (h % 880); }
function collRecent(updated) { const d = new Date(updated); return !isNaN(d) && daysSince(updated) <= 40; }

function CollateralScreen({ onToast, collateral = window.COLLATERAL || [] }) {
  const [cat, setCat] = useStateLearn("all");
  const [q, setQ] = useStateLearn("");
  const [sort, setSort] = useStateLearn("newest");
  const [preview, setPreview] = useStateLearn(null);
  const cats = [["all", "All"], ["buyer", "Buyer"], ["seller", "Seller"], ["valuation", "Valuation"], ["pe", "Private equity"], ["succession", "Succession"], ["brokerage", "Deal process"]];

  const list = useMemoL(() => {
    let l = collateral.map((d) => ({ ...d, downloads: collDownloads(d.id), recent: collRecent(d.updated) }));
    if (cat !== "all") l = l.filter((d) => d.cat === cat);
    const query = q.trim().toLowerCase();
    if (query) l = l.filter((d) => (d.name + " " + d.desc).toLowerCase().includes(query));
    if (sort === "newest") l.sort((a, b) => new Date(b.updated) - new Date(a.updated));
    else if (sort === "downloads") l.sort((a, b) => b.downloads - a.downloads);
    else if (sort === "az") l.sort((a, b) => a.name.localeCompare(b.name));
    return l;
  }, [cat, q, sort]);

  return (
    <div className="lc-page">
      <div className="page-header">
        <div className="ph-title">
          <div className="eyebrow">Collateral</div>
          <h1>Guides &amp; documents</h1>
          <p className="subtitle">Brochures, primers, and worksheets to share with clients or keep on hand. Members can download any item.</p>
        </div>
      </div>

      <div className="lc-toolbar">
        <div className="lc-search-inline" style={{ flex: "1 1 280px" }}>
          <Icon name="search" size={16} />
          <input placeholder="Search documents…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        <div className="lc-toolbar-right">
          <select className="select-styled" value={sort} onChange={(e) => setSort(e.target.value)}>
            <option value="newest">Newest</option>
            <option value="downloads">Most downloaded</option>
            <option value="az">A–Z</option>
          </select>
        </div>
      </div>

      <div className="lc-toolbar">
        <div className="lc-chiprow">
          {cats.map(([id, lab]) => (
            <button key={id} className={cx("lc-chip", cat === id && "active")} onClick={() => setCat(id)}>{lab}</button>
          ))}
        </div>
      </div>

      <p className="lc-results"><b>{list.length}</b> {list.length === 1 ? "document" : "documents"}</p>

      {list.length === 0 ? (
        <div className="empty"><Icon name="folder" size={28} /><h4>No documents found</h4><p>Try a different search term or category.</p></div>
      ) : (
        <div className="coll-grid">
          {list.map((d) => (
            <article key={d.id} className="coll-card" onClick={() => setPreview(d)} style={{ cursor: "pointer" }}>
              <div className="ctop">
                <span className="ficon"><Icon name={d.type === "VIDEO" ? "video" : "file"} size={18} /><span className="ext">{d.type}</span></span>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 6 }}>
                  {d.recent ? <span className="new-badge" style={{ background: "var(--gold)", color: "var(--navy)" }}>Updated</span> : null}
                  <CatTag id={d.cat} />
                </div>
              </div>
              <h4>{d.name}</h4>
              <p className="cdesc">{d.desc}</p>
              <div className="cfoot">
                <span className="meta">{d.type === "VIDEO" ? `Duration: ${d.size}` : d.size}{d.pages ? ` · ${d.pages} pp` : ""} · {d.updated}</span>
                {d.url ? (
                  <Button variant="ghost" size="sm" icon={d.type === "VIDEO" ? "eye" : "download"} onClick={(e) => {
                    e.stopPropagation();
                    if (d.url.startsWith("data:")) {
                      const link = document.createElement("a");
                      link.href = d.url;
                      link.download = `${d.name}.pdf`;
                      document.body.appendChild(link);
                      link.click();
                      document.body.removeChild(link);
                      onToast(`Downloaded ${d.name}`);
                    } else {
                      window.open(d.url, "_blank");
                    }
                  }}>{d.type === "VIDEO" ? "Watch" : "Download"}</Button>
                ) : (
                  <Button variant="ghost" size="sm" icon="download" onClick={(e) => { e.stopPropagation(); onToast(`Downloading “${d.name}”`); }}>Download</Button>
                )}
              </div>
            </article>
          ))}
        </div>
      )}

      {preview ? (
        <div className="drawer-scrim" onClick={() => setPreview(null)}>
          <div className="drawer" onClick={(e) => e.stopPropagation()}>
            <div className="dh">
              <div>
                <div className="eyebrow">{CAT[preview.cat] ? CAT[preview.cat].label : "Document"}</div>
                <h3 style={{ fontSize: 20, marginTop: 6 }}>{preview.name}</h3>
              </div>
              <button className="x" onClick={() => setPreview(null)}><Icon name="x" size={18} /></button>
            </div>
            <div className="db">
              <div className="doc-preview"><Icon name={preview.type === "VIDEO" ? "video" : "file"} size={40} /></div>
              <p className="prose" style={{ marginBottom: 18 }}>{preview.desc}</p>
              <table className="data-table" style={{ marginBottom: 18 }}>
                <tbody>
                  <tr><td className="t-title">Format</td><td className="num">{preview.type}</td></tr>
                  <tr><td className="t-title">{preview.type === "VIDEO" ? "Duration" : "Size"}</td><td className="num">{preview.size}</td></tr>
                  {preview.pages ? <tr><td className="t-title">Pages</td><td className="num">{preview.pages}</td></tr> : null}
                  <tr><td className="t-title">Updated</td><td className="num">{preview.updated}</td></tr>
                  <tr><td className="t-title">Downloads</td><td className="num">{collDownloads(preview.id).toLocaleString()}</td></tr>
                </tbody>
              </table>
              {preview.url ? (
                <Button variant="primary" icon={preview.type === "VIDEO" ? "eye" : "download"} onClick={() => {
                  if (preview.url.startsWith("data:")) {
                    const link = document.createElement("a");
                    link.href = preview.url;
                    link.download = `${preview.name}.pdf`;
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    onToast(`Downloaded ${preview.name}`);
                  } else {
                    window.open(preview.url, "_blank");
                  }
                  setPreview(null);
                }} style={{ width: "100%" }}>{preview.type === "VIDEO" ? "Watch Video" : `Download ${preview.type}`}</Button>
              ) : (
                <Button variant="primary" icon="download" onClick={() => { onToast(`Downloading “${preview.name}”`); setPreview(null); }} style={{ width: "100%" }}>Download {preview.type}</Button>
              )}
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { MyLearningScreen, CollateralScreen });
