// Left rail — the "inventory". Filterable component palette.

window.Inventory = function Inventory({
  nodes,
  resolved,
  selected,
  onToggleSelect,
  onHoverNode,
}) {
  const [filter, setFilter] = React.useState("all");
  const [q, setQ] = React.useState("");
  const selectedSet = React.useMemo(() => new Set(selected), [selected]);

  // Group nodes by type, ordered.
  const typeOrder = ["optimizer", "scheduler", "technique", "quantization", "architecture", "inference"];
  const counts = React.useMemo(() => {
    const c = { all: nodes.length };
    for (const t of typeOrder) c[t] = 0;
    for (const n of nodes) c[n.type] = (c[n.type] || 0) + 1;
    return c;
  }, [nodes]);

  const filtered = React.useMemo(() => {
    const lq = q.trim().toLowerCase();
    return nodes.filter(n => {
      if (filter !== "all" && n.type !== filter) return false;
      if (lq && !(n.name.toLowerCase().includes(lq) || n.canonical.includes(lq))) return false;
      return true;
    });
  }, [nodes, filter, q]);

  const grouped = React.useMemo(() => {
    const g = {};
    for (const n of filtered) (g[n.type] = g[n.type] || []).push(n);
    return g;
  }, [filtered]);

  return (
    <div className="rail-left">
      <div className="rail-head">
        <h2>Inventory</h2>
        <div className="sub">{nodes.length} components</div>
      </div>

      <div className="filters">
        <button className={"chip " + (filter === "all" ? "on" : "")}
                onClick={() => setFilter("all")}>
          All <span className="ct">{counts.all}</span>
        </button>
        {typeOrder.map(t => (
          counts[t] > 0 && (
            <button key={t}
                    className={"chip " + (filter === t ? "on" : "")}
                    onClick={() => setFilter(t)}>
              {window.TYPE_META[t].label}
              <span className="ct">{counts[t]}</span>
            </button>
          )
        ))}
      </div>

      <div className="search">
        <input
          type="text"
          placeholder="search components…"
          value={q}
          onChange={e => setQ(e.target.value)}
        />
      </div>

      <div className="inv-list">
        {typeOrder.map(t => {
          const list = grouped[t];
          if (!list || list.length === 0) return null;
          return (
            <div key={t} style={{ marginBottom: 6 }}>
              <div className="inv-group-title">
                {window.TYPE_META[t].label}
              </div>
              {list.map(n => {
                const r = resolved[n.canonical] || {};
                const isSelected = selectedSet.has(n.canonical);
                const cls = [
                  "inv-row",
                  `tier-${n.tier}`,
                  isSelected ? "selected" : "",
                  r.status === "blocked" ? "blocked" : "",
                  r.status === "conditional" ? "dim" : "",
                ].filter(Boolean).join(" ");
                const meta = window.TYPE_META[n.type];
                const metaText =
                  isSelected ? "equipped"
                  : r.status === "blocked" ? `blocked · ${r.reasons[0]?.label || "breaks"}`
                  : r.status === "conditional" ? (r.reasons[0]?.label || "awaiting")
                  : null;
                return (
                  <div
                    key={n.canonical}
                    className={cls}
                    style={{ ["--type-color"]: meta.color }}
                    onClick={() => onToggleSelect(n.canonical)}
                    onMouseEnter={e => onHoverNode(n, e)}
                    onMouseLeave={() => onHoverNode(null)}
                  >
                    <div className="type-ic">
                      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8"
                           strokeLinecap="round" strokeLinejoin="round"
                           dangerouslySetInnerHTML={{ __html: meta.icon }} />
                    </div>
                    <div>
                      <div className="inv-name">{n.name}</div>
                      <div className="inv-meta">
                        {metaText ? (
                          <span style={{
                            color: isSelected ? "var(--ember-2)"
                                  : r.status === "blocked" ? "var(--rust)"
                                  : "var(--amber)"
                          }}>{metaText}</span>
                        ) : (
                          <span className="canon">{n.canonical}</span>
                        )}
                      </div>
                    </div>
                    <div className={`tier-pip t${n.tier}`} title={`Tier ${n.tier}`}>T{n.tier}</div>
                  </div>
                );
              })}
            </div>
          );
        })}
        {filtered.length === 0 && (
          <div style={{ padding: "32px 16px", textAlign: "center", color: "var(--bone-4)", fontSize: 11, fontFamily: "var(--f-mono)" }}>
            no components match
          </div>
        )}
      </div>
    </div>
  );
};
