const SCROLL_STORAGE_PREFIX = "codexRemote.conversationScroll:";

export function loadConversationScroll(storage, sessionId) {
  if (!storage || !sessionId) return null;
  try {
    const raw = storage.getItem(scrollKey(sessionId));
    if (raw === null) return null;
    const value = Number(raw);
    return Number.isFinite(value) && value >= 0 ? value : null;
  } catch {
    return null;
  }
}

export function saveConversationScroll(storage, sessionId, scrollTop) {
  if (!storage || !sessionId || !Number.isFinite(scrollTop)) return;
  try {
    storage.setItem(scrollKey(sessionId), String(Math.max(0, Math.round(scrollTop))));
  } catch {
    // Storage failures must not interfere with normal scrolling.
  }
}

function scrollKey(sessionId) {
  return `${SCROLL_STORAGE_PREFIX}${encodeURIComponent(sessionId)}`;
}
