// Sidebar: block palette grouped by category, draggable to canvas
function Sidebar({ onDragStart, query, setQuery }) {
  const [username, setUsername] = React.useState(window.USER_CONTEXT.username);
  const agentName = window.USER_CONTEXT.agentName 
  React.useEffect(() => {
    const handleReady = () => setUsername(window.USER_CONTEXT.username);
    window.addEventListener('userContextReady', handleReady);
    return () => window.removeEventListener('userContextReady', handleReady);
  }, []);

  const q = query.trim().toLowerCase();
  const filtered = window.BLOCK_CATALOG.map((cat) => ({
    ...cat,
    blocks: cat.blocks.filter(
      (b) => !q || b.label.toLowerCase().includes(q) || cat.category.toLowerCase().includes(q)
    ),
  })).filter((cat) => cat.blocks.length > 0);

  return (
    <aside className="sidebar">
      <div className="sidebar-head">
        <div className="eyebrow">Agents names</div>
        <h2 className="sidebar-title">Agent: {agentName}</h2>
        <div className="sidebar-sub">Drag a block onto the canvas to compose your flow.</div>
        <div className="search-wrap">
          <input
            type="text"
            className="search"
            placeholder="Search blocks…"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
          />
          <span className="search-icon">⌕</span>
        </div>
      </div>

      <div className="sidebar-scroll">
        {filtered.map((cat) => (
          <section key={cat.category} className="palette-cat">
            <header className="palette-cat-head">
              <span className="palette-cat-rule" style={{ background: cat.accent }} />
              <span className="palette-cat-name">{cat.category}</span>
              <span className="palette-cat-count">{cat.blocks.length}</span>
            </header>
            <div className="palette-list">
              {cat.blocks.map((b) => (
                <PaletteBlock key={b.id} block={b} accent={cat.accent} onDragStart={onDragStart} />
              ))}
            </div>
          </section>
        ))}
        {filtered.length === 0 && (
          <div className="empty-pal">No blocks match "{query}"</div>
        )}
      </div>
    </aside>
  );
}

function PaletteBlock({ block, accent, onDragStart }) {
  const glyph = window.KIND_GLYPH[block.kind] || "·";
  return (
    <div
      className={`pal-block kind-${block.kind}`}
      draggable
      onDragStart={(e) => {
        e.dataTransfer.effectAllowed = "copy";
        e.dataTransfer.setData("text/block-id", block.id);
        onDragStart && onDragStart(block.id);
      }}
    >
      <span className="pal-block-rule" style={{ background: accent }} />
      <span className="pal-block-glyph" style={{ color: accent }}>{glyph}</span>
      <span className="pal-block-label">{block.label}</span>
      <span className="pal-block-grip">⠿</span>
    </div>
  );
}

Object.assign(window, { Sidebar });
