/** The bot as a draggable bubble. Drag it anywhere; flick or drop it past the right edge to
 *  dismiss, and it collapses into the header icon beside "ordenar por" — tapping that brings
 *  the bubble back where it was. */
function BotBubble({ open, onOpen, dismissed, onDismiss }) {
  const [pos, setPos] = React.useState({ x: null, y: null });
  const drag = React.useRef(null);
  const [dragging, setDragging] = React.useState(false);
  const [armed, setArmed] = React.useState(false); // held long enough to show the dismiss ×
  const hold = React.useRef(null);
  const ref = React.useRef(null);
  const D = 54;

  // default resting place: bottom right, above the categories
  React.useEffect(() => {
    if (pos.x != null || !ref.current) return;
    const shell = ref.current.closest(".beco-shell");
    if (!shell) return;
    const b = shell.getBoundingClientRect();
    setPos({ x: b.width - D - 14, y: b.height - D - 132 });
  }, [pos.x]);

  const onDown = (e) => {
    e.stopPropagation();
    const shell = ref.current.closest(".beco-shell").getBoundingClientRect();
    drag.current = { x: e.clientX, y: e.clientY, ox: pos.x, oy: pos.y, shell, moved: false };
    hold.current = setTimeout(() => setArmed(true), 420);
    ref.current.setPointerCapture && ref.current.setPointerCapture(e.pointerId);
  };
  const onMove = (e) => {
    if (!drag.current) return;
    const dx = e.clientX - drag.current.x, dy = e.clientY - drag.current.y;
    if (!drag.current.moved && Math.abs(dx) + Math.abs(dy) > 6) {
      drag.current.moved = true; setDragging(true); clearTimeout(hold.current);
    }
    if (!drag.current.moved) return;
    const s = drag.current.shell;
    setPos({
      x: Math.max(-D * 0.4, Math.min(s.width - D * 0.6, drag.current.ox + dx)),
      y: Math.max(38, Math.min(s.height - D - 8, drag.current.oy + dy))
    });
  };
  const onUp = (e) => {
    clearTimeout(hold.current);
    const d = drag.current;
    drag.current = null;
    setDragging(false);
    if (!d) return;
    if (!d.moved) { if (!armed) onOpen(); return; }
    // dropped mostly off the right edge → dismiss to the header
    if (pos.x > d.shell.width - D * 0.72) { onDismiss(true); return; }
    // otherwise snap to whichever side it is nearest
    setPos(p => ({ ...p, x: p.x + D / 2 < d.shell.width / 2 ? 14 : d.shell.width - D - 14 }));
  };

  if (dismissed) return null;

  return (
    <div ref={ref}
      onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
      onClick={e => e.stopPropagation()}
      style={{
        position: "absolute", left: pos.x == null ? undefined : pos.x, top: pos.y == null ? undefined : pos.y,
        right: pos.x == null ? 14 : undefined, bottom: pos.y == null ? 132 : undefined,
        width: D, height: D, zIndex: 300, touchAction: "none", cursor: dragging ? "grabbing" : "grab",
        opacity: open ? 0 : 1, pointerEvents: open ? "none" : "auto",
        transform: dragging ? "scale(1.06)" : "scale(1)",
        transition: (dragging ? "transform 120ms var(--ease-out)" : "left 260ms var(--ease-out), top 260ms var(--ease-out), transform 160ms var(--ease-out)") + ", opacity var(--dur-base) var(--ease-out)"
      }}>
      <div style={{
        width: "100%", height: "100%", borderRadius: "var(--radius-pill)",
        background: "var(--black)", border: "1px solid " + (armed ? "var(--ink-500)" : "var(--white)"),
        color: "var(--white)", display: "flex", alignItems: "center", justifyContent: "center",
        boxShadow: dragging ? "0 10px 24px rgb(0 0 0 / 0.6)" : "none",
        opacity: armed ? 0.4 : 1, transition: "opacity var(--dur-fast) var(--ease-out)"
      }}>
        <Icon d={P.chat} size={21} />
      </div>
      {armed && (
        <button type="button" aria-label="Dispensar o bot"
          onPointerDown={e => e.stopPropagation()}
          onClick={e => { e.stopPropagation(); setArmed(false); onDismiss(true); }}
          style={{
            position: "absolute", inset: 0, borderRadius: "var(--radius-pill)",
            background: "transparent", border: "none", cursor: "pointer", color: "var(--white)",
            display: "flex", alignItems: "center", justifyContent: "center"
          }}>
          <Icon d={P.x} size={20} stroke={2.5} />
        </button>
      )}
    </div>
  );
}
Object.assign(window, { BotBubble });
