/* P.E.S.T Web App — Projects (multi-category filter + search + recently added + pin) */
function Projects({ onNavigate }) {
  const store = useStore();
  const [cat, setCat] = useState("All");
  const [q, setQ] = useState("");
  const cats = ["All", "Pinned", ...window.PEST_APP.CATEGORIES];

  const pinnedSet = new Set(store.user.pinned);
  const full = store.user.pinned.length >= window.PEST_APP.MAX_PINS;

  // Cats live as array on each project; fall back to legacy single `category` if present.
  const projCats = (p) => (p.categories && p.categories.length) ? p.categories : (p.category ? [p.category] : []);

  const filtered = store.projects.filter((p) => {
    const pc = projCats(p);
    const okCat = cat === "All" ? true : cat === "Pinned" ? pinnedSet.has(p.id) : pc.indexOf(cat) !== -1;
    const okQ = !q.trim() || (p.name + " " + (p.desc || "") + " " + pc.join(" ")).toLowerCase().includes(q.trim().toLowerCase());
    return okCat && okQ;
  });

  const recent = [...store.projects].sort((a, b) => b.addedAt - a.addedAt).slice(0, 6);
  const showShelf = cat === "All" && !q.trim();

  const togglePin = (p) => {
    if (pinnedSet.has(p.id)) { store.unpinProject(p.id); toast(p.name + " unpinned"); }
    else if (full) { toast("Dashboard is full (" + window.PEST_APP.MAX_PINS + " max)", "err"); }
    else { store.pinProject(p.id); toast(p.name + " pinned to dashboard"); }
  };

  return (
    <div>
      <div className="page-head">
        <div className="eyebrow">Projects</div>
        <h1>The <span className="grad-text">directory</span></h1>
        <p className="sub">Curated by P.E.S.T. Pin the ones you use most — they orbit your dashboard for one-tap access ({store.user.pinned.length}/{window.PEST_APP.MAX_PINS} pinned).</p>
      </div>

      <div className="proj-toolbar">
        <div className="search-wrap">
          <window.AIcon.search />
          <input className="input" placeholder="Search projects…" value={q} onChange={(e) => setQ(e.target.value)} />
        </div>
        <div className="cat-row">
          {cats.map((c) => (
            <button key={c} className={"chip" + (cat === c ? " on" : "") + (c === "Pinned" ? " chip-pin" : "")} onClick={() => setCat(c)}>
              {c === "Pinned" ? <><window.AIcon.pinned /> Pinned ({store.user.pinned.length})</> : c}
            </button>
          ))}
        </div>
      </div>

      {showShelf && (
        <div className="shelf">
          <div className="shelf-head"><span className="eyebrow">Recently added</span></div>
          <div className="shelf-scroll">
            {recent.map((p) => {
              const pc = projCats(p);
              return (
                <div className="card shelf-card cut-sm" key={p.id}>
                  <LogoTile project={p} />
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <b style={{ display: "block", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</b>
                    <span className="when">{window.timeAgo(p.addedAt)} · {pc[0] || ""}</span>
                  </div>
                  <button className={"pin-btn" + (pinnedSet.has(p.id) ? " pinned" : "")} onClick={() => togglePin(p)} disabled={!pinnedSet.has(p.id) && full} title={pinnedSet.has(p.id) ? "Unpin" : "Pin"}>
                    {pinnedSet.has(p.id) ? <window.AIcon.pinned /> : <window.AIcon.pin />}
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {filtered.length === 0 ? (
        <div className="empty-note">{cat === "Pinned"
          ? "No pinned projects yet — hit Pin on any project to add it here for one-tap access."
          : ("No projects match \"" + q + "\"" + (cat !== "All" ? " in " + cat : "") + ".")}</div>
      ) : (
        <div className="proj-grid">
          {filtered.map((p) => {
            const isPinned = pinnedSet.has(p.id);
            const links = Object.keys(p.links || {}).filter((k) => p.links[k]);
            const pc = projCats(p);
            return (
              <div className="card p-card cut" key={p.id}>
                <div className="p-top">
                  <LogoTile project={p} />
                  <div className="p-id">
                    <h3>{p.name}</h3>
                    <div className="p-cats">
                      {pc.map((c) => <span key={c} className={"tag cat-" + c.replace(/[^A-Za-z0-9]/g, "")}>{c}</span>)}
                    </div>
                  </div>
                </div>
                <p className="p-desc">{p.desc}</p>
                <div className="p-foot">
                  <div className="p-links">
                    {links.map((k) => { const meta = window.A_SOCIAL[k]; if (!meta) return null; const I = meta.icon; return <a className="icon-link" key={k} href={p.links[k]} target="_blank" rel="noreferrer" title={meta.label}><I /></a>; })}
                  </div>
                  <button className={"pin-btn" + (isPinned ? " pinned" : "")} onClick={() => togglePin(p)} disabled={!isPinned && full} title={isPinned ? "Unpin" : (full ? "Dashboard full" : "Pin to dashboard")}>
                    {isPinned ? <window.AIcon.pinned /> : <window.AIcon.pin />} {isPinned ? "Pinned" : "Pin"}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

window.Projects = Projects;
