/* Tree list item — sidebar entry, double-click to rename */
const { useState: usT, useRef: urT, useEffect: ueT } = React;

function TreeListItem({ tree, active, onClick, onRename, onDelete }) {
  const [editing, setEditing] = usT(false);
  const inputRef = urT(null);
  ueT(() => { if (editing && inputRef.current) { inputRef.current.focus(); inputRef.current.select(); } }, [editing]);

  const nodeCount = Object.keys(tree.nodes).length;

  return (
    <div className={`tree-item ${active ? 'active' : ''}`}
      onClick={onClick}
      onDoubleClick={(e) => { e.stopPropagation(); setEditing(true); }}
      onContextMenu={(e) => {
        e.preventDefault();
        if (confirm(`Delete "${tree.name}"?`)) onDelete();
      }}>
      <Icon name="tree" size={13} />
      {editing ? (
        <input ref={inputRef}
          className="tree-item-rename"
          defaultValue={tree.name}
          onClick={(e) => e.stopPropagation()}
          onBlur={(e) => { onRename(e.target.value || "Untitled"); setEditing(false); }}
          onKeyDown={(e) => {
            if (e.key === "Enter") e.target.blur();
            if (e.key === "Escape") setEditing(false);
          }} />
      ) : (
        <>
          <span className="tree-item-name">{tree.name}</span>
          <span className="tree-item-meta">{nodeCount}</span>
        </>
      )}
    </div>
  );
}

window.TreeListItem = TreeListItem;
