#!/usr/bin/env bash
# PR #23503 (fix(web): markdown previews keep their scroll position across tabs)
# Claim: already-fixed. #43254 (9c4ab6d47a) restores the rendered Markdown reading position per
# environment, thread, workspace and file, and closed #22300, the issue this PR fixes.
# Shows: this PR's regression (scroll file A, switch the panel to file B, back to A) plus a
# source/rendered toggle, written for the chunked Markdown list, fail at #43254's parent and pass at
# #43254 and on current main. Needs deps installed (`vp i`), `gh` authenticated, and a Playwright
# Chromium headless shell (set PLAYWRIGHT_BROWSERS_PATH if it is not in the default location).
set -euo pipefail

REPO=pingdotgg/t3code
FIX=9c4ab6d47ad340f8286be083b26e18333fe96d1e
CHUNKED=fb4558d77d0437a056bdd1604a48b47b3f5db069
TEST=apps/web/src/components/files/FilePreviewPanel.browser.test.tsx
ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
WORK=$(mktemp -d)
cleanup() {
  git checkout -q -f -- . 2>/dev/null || true
  git checkout -q -f "$ORIG"
  rm -rf "$WORK"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
git fetch -q origin pull/23503/head
PR_HEAD=$(git rev-parse FETCH_HEAD)
echo "main=$MAIN pr_head=$PR_HEAD fix=$FIX"

# 1. #43254 is merged, on main, closed the PR's issue, and names this PR as the same fix.
if git merge-base --is-ancestor "$FIX" "$MAIN"; then
  pass "#43254 is on main as ${FIX:0:10} ($(git log -1 --format=%s "$FIX"))"
else
  fail "${FIX:0:10} is not on main"
fi
merged=$(gh pr view 43254 --repo "$REPO" --json state,mergeCommit --jq '"\(.state) \(.mergeCommit.oid)"')
if [ "$merged" = "MERGED $FIX" ]; then
  pass "gh: #43254 is MERGED with merge commit ${FIX:0:10}"
else
  fail "gh: #43254 state/merge commit is '$merged'"
fi
issue=$(gh issue view 22300 --repo "$REPO" --json state,closedByPullRequestsReferences --jq '"\(.state) \([.closedByPullRequestsReferences[].number]|map(tostring)|join(","))"')
case "$issue" in
  "CLOSED "*43254*) pass "gh: issue #22300 (this PR's 'Fixes') is CLOSED by #43254" ;;
  *) fail "gh: issue #22300 is '$issue'" ;;
esac
if gh pr view 43254 --repo "$REPO" --json body --jq .body | grep -q "#23503 fixes the same bug"; then
  pass "gh: #43254's description says '#23503 fixes the same bug' and reimplements it on the chunked list"
else
  fail "gh: #43254's description does not reference #23503"
fi

# 2. The code this PR patches was replaced: it wraps a ScrollArea; at the fix the surface is the
#    chunked list (#40631, ${CHUNKED:0:10}), which now saves and restores the reading position.
surface() { git show "$1:apps/web/src/components/files/FilePreviewPanel.tsx" | awk '/^function RenderedMarkdownSurface/{f=1} f{print} f&&/^}$/{exit}'; }
if surface "$PR_HEAD" | grep -q '<ScrollArea ref={scrollAreaRef}' \
  && surface "$FIX" | grep -q '<ChunkedMarkdown' && ! surface "$FIX" | grep -q '<ScrollArea' \
  && git merge-base --is-ancestor "$CHUNKED" "$FIX"; then
  pass "this PR restores scrollTop on a ScrollArea in RenderedMarkdownSurface; since #40631 that surface renders ChunkedMarkdown"
else
  fail "RenderedMarkdownSurface shape at the PR head / fix is not as described"
fi
if git show "$FIX:apps/web/src/components/files/ChunkedMarkdown.tsx" | grep -q 'const savedPositions = new Map' \
  && git show "$FIX:apps/web/src/components/files/ChunkedMarkdown.tsx" | grep -q 'initialScrollIndex'; then
  pass "at ${FIX:0:10}, ChunkedMarkdown saves the first visible chunk per file and restores it with initialScrollIndex"
else
  fail "ChunkedMarkdown at ${FIX:0:10} has no saved reading position"
fi

# 3. Behavior: one mounted panel switches file tabs and toggles source view.
write_block() {
  cat >> "$TEST" <<'EOF'

// PR #23503's regression, adapted to the chunked Markdown list: one mounted panel switches
// file tabs (A -> B -> A) and A must come back at the same reading position.
describe("pr-23503 rendered Markdown keeps its scroll across file tabs", () => {
  const doc = (name: string) =>
    Array.from(
      { length: 200 },
      (_, index) => `## ${name} section ${index}\n\n${name} paragraph ${index}.\n`,
    ).join("\n");
  const scroller = () =>
    document.querySelector<HTMLElement>(".scrollbar-gutter-both") ?? expect.unreachable();
  const readingPosition = () => {
    const top = scroller().getBoundingClientRect().top;
    for (const heading of scroller().querySelectorAll("h2")) {
      const offset = Math.round(heading.getBoundingClientRect().top - top);
      if (offset > -100) return { heading: heading.textContent, offset };
    }
    return null;
  };
  const tab = (name: string): ReactNode => (
    <div style={{ width: 500, height: 400, display: "flex", flexDirection: "column" }}>
      {markdownPreview(false, doc(name), `${name}.md`)}
    </div>
  );
  const withAppCss = () => {
    const style = document.createElement("style");
    style.textContent = appCss;
    document.head.append(style);
    return { [Symbol.dispose]: () => style.remove() };
  };
  const scrollDown = async (name: string) => {
    scroller().scrollTop = 1800;
    scroller().dispatchEvent(new Event("scroll"));
    await vi.waitFor(() => expect(readingPosition()?.heading).not.toBe(`${name} section 0`));
    return readingPosition();
  };
  const expectReadingPosition = (saved: ReturnType<typeof readingPosition>) =>
    vi.waitFor(() => {
      const position = readingPosition();
      expect(position?.heading).toBe(saved?.heading);
      expect(Math.abs((position?.offset ?? 0) - (saved?.offset ?? 0))).toBeLessThanOrEqual(2);
    });

  it("pr-23503 returns to a file tab at the position it was left", async () => {
    using _settings = setup();
    using _style = withAppCss();
    await using screen = await render(tab("AGENTS"));
    await expect.element(screen.getByText("AGENTS section 0", { exact: true })).toBeInTheDocument();
    const saved = await scrollDown("AGENTS");

    await screen.rerender(tab("README"));
    await expect.element(screen.getByText("README section 0", { exact: true })).toBeInTheDocument();
    await vi.waitFor(() => expect(scroller().scrollTop).toBe(0));

    await screen.rerender(tab("AGENTS"));
    await expectReadingPosition(saved);
  });

  it("pr-23503 returns to the rendered view at the position it was left after showing the source", async () => {
    using _settings = setup();
    using _style = withAppCss();
    await using screen = await render(tab("GUIDE"));
    await expect.element(screen.getByText("GUIDE section 0", { exact: true })).toBeInTheDocument();
    const saved = await scrollDown("GUIDE");

    await screen.getByRole("button", { name: "Show markdown source" }).click();
    await vi.waitFor(() => expect(document.querySelector(".scrollbar-gutter-both")).toBeNull());
    await screen.getByRole("button", { name: "Show rendered markdown" }).click();
    await expect.element(screen.getByText(saved?.heading ?? "", { exact: true })).toBeInTheDocument();
    await expectReadingPosition(saved);
  });
});
EOF
}

run_block() {
  git checkout -q --detach "$1"
  write_block
  (cd apps/web && vp test run "${TEST#apps/web/}" -t "pr-23503") > "$2" 2>&1 || true
  git checkout -q -f -- "$TEST"
  if grep -qE "Executable doesn't exist|browserType\.launch" "$2"; then
    echo "SETUP  Playwright Chromium headless shell is missing; install it or set PLAYWRIGHT_BROWSERS_PATH"
    exit 2
  fi
  grep -E "^ +Tests +[0-9]" "$2" || true
}

run_block "$FIX^" "$WORK/parent.log"
grep -E "AssertionError" "$WORK/parent.log" | head -2 || true
if grep -qE "Tests +2 failed" "$WORK/parent.log" \
  && grep -q "expected 'AGENTS section 0' to be 'AGENTS section" "$WORK/parent.log" \
  && grep -q "expected 'GUIDE section 0' to be 'GUIDE section" "$WORK/parent.log"; then
  pass "at #43254's parent ${FIX:0:10}^, both tests fail: returning to the file, or to the rendered view, lands back at section 0"
else
  fail "the tests do not fail at ${FIX:0:10}^ with the reset-to-top assertion"
fi

for target in "$FIX" "$MAIN"; do
  run_block "$target" "$WORK/run.log"
  if grep -qE "Tests +2 passed" "$WORK/run.log" && ! grep -qE "Tests +.*[0-9]+ failed" "$WORK/run.log"; then
    pass "at ${target:0:10}, both tests pass: the file tab and the rendered view come back at the same heading, within 2px"
  else
    fail "the tests do not both pass at ${target:0:10}"
    grep -E "FAIL|AssertionError" "$WORK/run.log" | head -5 || true
  fi
done

if [ "$ok" = 1 ]; then
  echo "VERDICT: CLOSE (already-fixed) - #43254 restores the rendered Markdown reading position across file tabs, which is what this PR delivers"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: claim not supported"
exit 1
