// Recursive MLS — Screen: Knowledgebase (Realtor-facing training & help center).
// Videos, PDFs, and written articles. LMS-ready: content is grouped into learning
// paths (courses) with progress, alongside a browsable library by section.
function Knowledge({ go }) {
  const KB = window.RC_KB;
  const [section, setSection] = useState("all");
  const [type, setType] = useState("all");
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(null); // article being viewed

  const groups = [];
  KB.sections.forEach((s) => { if (!groups.find((g) => g.group === s.group)) groups.push({ group: s.group, items: [] }); groups.find((g) => g.group === s.group).items.push(s); });

  let list = KB.articles.filter((a) =>
    (section === "all" || a.section === section) &&
    (type === "all" || a.type === type) &&
    (!q || (a.title + a.desc).toLowerCase().includes(q.toLowerCase())));
  const featured = KB.articles.filter((a) => a.featured);

  const typeBadge = (t) => {
    const m = KB.typeMeta[t];
    const tones = { video: ["#faece3", "#c0612f"], pdf: ["#eef4f1", "#006747"], article: ["#eef1f6", "#16243A"] };
    const [bg, fg] = tones[t] || tones.article;
    return <span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 10.5, fontWeight: 600, letterSpacing: ".3px", color: fg, background: bg, borderRadius: 4, padding: "3px 7px" }}><Icon name={m.icon} size={12} color={fg} /> {m.label}</span>;
  };
  const metaText = (a) => a.type === "video" ? a.duration : a.type === "pdf" ? a.pages + " pages" : a.readingTime;

  const Thumb = ({ a, h = 132 }) => (
    <div style={{ height: h, borderRadius: "3px 3px 0 0", position: "relative", overflow: "hidden", background: a.thumb ? `center/cover url(${a.thumb})` : "#f0efe9", display: "flex", alignItems: "center", justifyContent: "center" }}>
      {!a.thumb && <Icon name={KB.typeMeta[a.type].icon} size={34} color="#c4c2b8" />}
      {a.type === "video" && a.thumb && (
        <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center", background: "rgba(0,40,28,.28)" }}>
          <span style={{ width: 44, height: 44, borderRadius: "50%", background: "rgba(255,255,255,.92)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="play" size={20} color="#006747" /></span>
        </span>
      )}
      {a.type === "video" && <span style={{ position: "absolute", bottom: 8, right: 8, fontFamily: "'Space Mono',monospace", fontSize: 10.5, fontWeight: 600, color: "#fff", background: "rgba(0,0,0,.6)", borderRadius: 4, padding: "2px 6px" }}>{a.duration}</span>}
    </div>
  );

  return (
    <div style={{ height: "100%", overflowY: "auto", background: "#f4f3ef" }}>
      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "26px 28px 64px" }}>

        {/* header */}
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 18, flexWrap: "wrap", marginBottom: 22 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 6 }}>Learn</div>
            <h1 style={{ margin: 0, fontSize: 27, fontWeight: 600, letterSpacing: "-0.6px" }}>Knowledgebase</h1>
            <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Training videos, guides, and documents for every Recursive tool.</p>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 9, background: "#fff", border: "1px solid #e2e0d8", borderRadius: 8, padding: "9px 13px", minWidth: 280 }}>
            <Icon name="search" size={16} color="#a8aca6" />
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search articles, videos & guides…" style={{ flex: 1, border: 0, background: "transparent", outline: 0, fontFamily: "inherit", fontSize: 13, color: "#1d241f" }} />
          </div>
        </div>

        {/* learning paths (LMS) */}
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <Icon name="graduation-cap" size={16} color="#006747" />
          <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".4px", color: "#1d241f" }}>Learning paths</span>
          <span style={{ fontSize: 11, fontWeight: 600, color: "#9a6a12", background: "#fbf2dc", borderRadius: 4, padding: "2px 7px", letterSpacing: ".3px" }}>LMS coming soon</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14, marginBottom: 30 }}>
          {KB.paths.map((p) => {
            const pct = Math.round((p.done / p.lessons) * 100);
            return (
              <div key={p.id} style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 18, display: "flex", flexDirection: "column", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                  <span style={{ width: 38, height: 38, borderRadius: 8, background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="route" size={18} color={p.color} /></span>
                  {p.ce && <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".5px", textTransform: "uppercase", color: "#16243A", background: "#eef1f6", borderRadius: 4, padding: "2px 7px" }}>CE</span>}
                </div>
                <div>
                  <div style={{ fontSize: 15, fontWeight: 600, color: "#1d241f" }}>{p.title}</div>
                  <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 3, lineHeight: 1.45 }}>{p.desc}</div>
                </div>
                <div style={{ marginTop: "auto" }}>
                  <div style={{ height: 6, borderRadius: 4, background: "#eef0ec", overflow: "hidden" }}><div style={{ width: pct + "%", height: "100%", background: "#006747", borderRadius: 4 }} /></div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginTop: 7, fontSize: 11.5, color: "#8a8e88" }}>
                    <span>{p.done}/{p.lessons} lessons · {p.hours} hrs</span>
                    <span style={{ fontWeight: 600, color: "#006747" }}>{pct ? "Resume" : "Start"} ›</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* featured */}
        {section === "all" && type === "all" && !q && (
          <div style={{ marginBottom: 30 }}>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: ".4px", color: "#1d241f", marginBottom: 12 }}>Featured</div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 14 }}>
              {featured.map((a) => (
                <div key={a.id} onClick={() => setOpen(a)} className="rc-row" style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", cursor: "pointer", overflow: "hidden" }}>
                  <Thumb a={a} />
                  <div style={{ padding: "11px 13px 14px" }}>
                    {typeBadge(a.type)}
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 8, lineHeight: 1.3 }}>{a.title}</div>
                    <div style={{ fontSize: 11.5, color: "#a8aca6", marginTop: 6 }}>{metaText(a)} · {a.views.toLocaleString()} views</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* browse: section rail + grid */}
        <div style={{ display: "grid", gridTemplateColumns: "210px 1fr", gap: 24, alignItems: "start" }}>
          <div style={{ position: "sticky", top: 0 }}>
            <div style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6", padding: "0 10px 8px" }}>Browse</div>
            <div onClick={() => setSection("all")} className="rc-nav-item" style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 7, cursor: "pointer", fontSize: 13.5, background: section === "all" ? "#eef4f1" : "transparent", color: section === "all" ? "#006747" : "#4a504a", fontWeight: section === "all" ? 600 : 400 }}>
              <Icon name="layers" size={16} color={section === "all" ? "#006747" : "#8a8e88"} /> All content
            </div>
            {groups.map((g) => (
              <div key={g.group} style={{ marginTop: 14 }}>
                <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#bcbfba", padding: "0 10px 5px" }}>{g.group}</div>
                {g.items.map((s) => (
                  <div key={s.id} onClick={() => setSection(s.id)} className="rc-nav-item" style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 7, cursor: "pointer", fontSize: 13.5, background: section === s.id ? "#eef4f1" : "transparent", color: section === s.id ? "#006747" : "#4a504a", fontWeight: section === s.id ? 600 : 400 }}>
                    <Icon name={s.icon} size={16} color={section === s.id ? "#006747" : "#8a8e88"} /> {s.label}
                  </div>
                ))}
              </div>
            ))}
          </div>

          <div>
            {/* type filter */}
            <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16 }}>
              {[["all", "All", "layers"], ["video", "Videos", "play-circle"], ["pdf", "Documents", "file-text"], ["article", "Articles", "book-open"]].map(([v, label, ic]) => (
                <button key={v} onClick={() => setType(v)} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, border: "1px solid", borderColor: type === v ? "#006747" : "#e2e0d8", background: type === v ? "#006747" : "#fff", color: type === v ? "#fff" : "#6b706a", borderRadius: 999, padding: "7px 13px", cursor: "pointer" }}>
                  <Icon name={ic} size={13} color={type === v ? "#fff" : "#8a8e88"} /> {label}
                </button>
              ))}
              <div style={{ flex: 1 }} />
              <span style={{ fontSize: 12, color: "#a8aca6" }}>{list.length} items</span>
            </div>

            <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
              {list.map((a) => (
                <div key={a.id} onClick={() => setOpen(a)} className="rc-row" style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", cursor: "pointer", overflow: "hidden" }}>
                  <Thumb a={a} h={120} />
                  <div style={{ padding: "11px 13px 14px" }}>
                    {typeBadge(a.type)}
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 8, lineHeight: 1.3 }}>{a.title}</div>
                    <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 5, lineHeight: 1.45 }}>{a.desc}</div>
                    <div style={{ fontSize: 11.5, color: "#a8aca6", marginTop: 8 }}>{metaText(a)} · Updated {a.updated}</div>
                  </div>
                </div>
              ))}
            </div>
            {list.length === 0 && <div style={{ padding: 40, textAlign: "center", color: "#a8aca6", fontSize: 13 }}>No content matches.</div>}
          </div>
        </div>
      </div>

      {/* viewer */}
      {open && <KBViewer a={open} onClose={() => setOpen(null)} go={go} />}
    </div>
  );
}

// Content viewer overlay (video / pdf / article)
function KBViewer({ a, onClose, go }) {
  const KB = window.RC_KB;
  const m = KB.typeMeta[a.type];
  return (
    <div onClick={onClose} style={{ position: "absolute", inset: 0, background: "rgba(20,28,22,.5)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 40, padding: 30 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: 760, maxHeight: "100%", background: "#fff", borderRadius: 4, boxShadow: "0 18px 60px rgba(0,0,0,.3)", overflow: "hidden", display: "flex", flexDirection: "column" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 18px", borderBottom: "1px solid #ececec" }}>
          <Icon name={m.icon} size={17} color="#006747" />
          <span style={{ fontSize: 14, fontWeight: 600, flex: 1 }}>{a.title}</span>
          <button onClick={onClose} style={{ border: 0, background: "none", cursor: "pointer", color: "#8a8e88", display: "flex" }}><Icon name="x" size={20} color="#8a8e88" /></button>
        </div>
        <div style={{ overflowY: "auto" }}>
          {a.type === "video" ? (
            <div style={{ height: 380, background: a.thumb ? `center/cover url(${a.thumb})` : "#1c1c1c", position: "relative", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <span style={{ position: "absolute", inset: 0, background: "rgba(0,40,28,.4)" }} />
              <span style={{ position: "relative", width: 64, height: 64, borderRadius: "50%", background: "rgba(255,255,255,.92)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="play" size={28} color="#006747" /></span>
              <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, height: 4, background: "rgba(255,255,255,.25)" }}><div style={{ width: (a.lms && a.lms.progress ? a.lms.progress : 0) + "%", height: "100%", background: "#006747" }} /></div>
            </div>
          ) : a.type === "pdf" ? (
            <div style={{ background: "#f0efe9", padding: 28, display: "flex", flexDirection: "column", alignItems: "center", gap: 14 }}>
              <div style={{ width: 300, height: 388, background: "#fff", boxShadow: "0 4px 20px rgba(0,0,0,.12)", borderRadius: 2, padding: 26 }}>
                <div style={{ height: 8, width: "55%", background: "#e7e5df", borderRadius: 2, marginBottom: 18 }} />
                {[100, 95, 90, 97, 60, 0, 92, 88, 70].map((w, i) => <div key={i} style={{ height: 5, width: w ? w + "%" : 0, background: "#f0efe9", borderRadius: 2, marginBottom: 10 }} />)}
              </div>
              <button style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 7, padding: "10px 16px", cursor: "pointer" }}><Icon name="download" size={15} color="#fff" /> Download PDF ({a.pages} pages)</button>
            </div>
          ) : (
            <div style={{ padding: "24px 30px 30px", maxWidth: 680 }}>
              <p style={{ fontSize: 15, lineHeight: 1.7, color: "#4a504a", margin: "0 0 14px" }}>{a.desc}</p>
              {[1, 2, 3].map((i) => <div key={i} style={{ marginBottom: 16 }}>
                <div style={{ height: 6, width: ["40%", "55%", "48%"][i - 1], background: "#eef0ec", borderRadius: 3, marginBottom: 10 }} />
                {[100, 96, 92, 70].map((w, j) => <div key={j} style={{ height: 5, width: w + "%", background: "#f4f3ee", borderRadius: 3, marginBottom: 9 }} />)}
              </div>)}
            </div>
          )}
          {/* LMS strip */}
          {a.lms && (
            <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "13px 18px", borderTop: "1px solid #ececec", background: "#faf9f5" }}>
              <Icon name="graduation-cap" size={15} color="#006747" />
              <span style={{ fontSize: 12.5, color: "#4a504a" }}>Part of <strong style={{ fontWeight: 600 }}>{a.lms.course}</strong> · {a.lms.module}</span>
              {a.lms.required && <Pill tone="pending">Required</Pill>}
              {a.lms.ce && <Pill tone="active">CE eligible</Pill>}
              <div style={{ flex: 1 }} />
              <button style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 7, padding: "8px 14px", cursor: "pointer" }}><Icon name="check" size={14} color="#fff" /> Mark complete</button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

window.Knowledge = Knowledge;
