const BOTTOM_THRESHOLD_PX = 80;
const DIRECT_SEND_TOP_OFFSET_PX = 80;
const ACTIVE_TURN_STATUSES = new Set(["starting", "thinking", "running", "waiting_approval"]);

export function isNearConversationBottom(viewport) {
  return viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= BOTTOM_THRESHOLD_PX;
}

export function shouldScrollConversation({ sessionChanged, wasNearBottom, turnAdded }) {
  return Boolean(sessionChanged || wasNearBottom || turnAdded);
}

export function conversationScrollTop(start, target, elapsedMs, durationMs = 220) {
  const progress = Math.min(1, Math.max(0, elapsedMs / durationMs));
  const eased = 1 - ((1 - progress) ** 3);
  return start + ((target - start) * eased);
}

export function shouldAnchorConversationSend(status) {
  return !ACTIVE_TURN_STATUSES.has(status);
}

export function shouldReleaseConversationDirectSendGuard({ guardSessionId, sessionId, status }) {
  return Boolean(guardSessionId) && guardSessionId === sessionId && !ACTIVE_TURN_STATUSES.has(status);
}

export function conversationTurnAnchorScrollTop({ currentScrollTop, viewportTop, turnTop }) {
  return Math.max(0, currentScrollTop + turnTop - viewportTop - DIRECT_SEND_TOP_OFFSET_PX);
}

export function conversationDirectSendSpacerHeight({ targetScrollTop, scrollHeight, clientHeight }) {
  const currentMaxScrollTop = Math.max(0, scrollHeight - clientHeight);
  return Math.max(0, targetScrollTop - currentMaxScrollTop);
}

export function conversationDirectSendScrollGuard({
  reservedSpaceHeight,
  sessionId,
  anchorScrollTop,
  initialScrollHeight,
  initialAvailableSpace
}) {
  if (reservedSpaceHeight <= 0) return null;
  return { sessionId, anchorScrollTop, initialScrollHeight, initialAvailableSpace };
}

export function conversationDirectSendMaxScrollTop({
  anchorScrollTop,
  initialScrollHeight,
  currentScrollHeight,
  initialAvailableSpace
}) {
  const contentGrowth = Math.max(0, currentScrollHeight - initialScrollHeight);
  return anchorScrollTop + Math.max(0, contentGrowth - initialAvailableSpace);
}
