// Exercise 3: render counter WITHOUT causing more renders
//
// Implement `RenderCounter`, which displays how many times it has rendered,
// using a REF that is incremented directly in the function body (not inside
// an effect, and never via useState) — proving that reading/incrementing a
// ref during render doesn't cause an infinite loop or extra renders, because
// mutating a ref never schedules anything.
//
// Then implement the pure helper `wouldCauseInfiniteLoop`, which explains
// (as a boolean) whether a given approach ("ref" vs "state") to
// incrementing-during-render would cause an infinite re-render loop.
//
// TODO 1: create a ref initialized to 0
// TODO 2: increment ref.current by 1 directly in the render body (top of
//         the component function, before the return)
// TODO 3: implement wouldCauseInfiniteLoop(approach)

import { useRef } from "react";

function RenderCounter() {
  const renderCount = useRef(0);
  // TODO 2: renderCount.current += 1;   (this line, mutating during render,
  // is safe ONLY because it's a ref — see theory section 4 for the caveat
  // about why this specific narrow pattern is acceptable)

  return <p>This component has rendered {renderCount.current} time(s).</p>;
}

// A version that would be WRONG if written with useState instead of useRef:
//
// function BrokenRenderCounter() {
//   const [renderCount, setRenderCount] = useState(0);
//   setRenderCount(renderCount + 1); // calling the setter DURING render
//   // schedules another render, which calls setRenderCount again, which
//   // schedules another render... → infinite loop / React throws an error
//   return <p>{renderCount}</p>;
// }

// TODO 3: return true for "state" (it schedules a re-render every time,
// which re-triggers itself endlessly), false for "ref" (mutating .current
// never schedules anything, so there's nothing to re-trigger).
function wouldCauseInfiniteLoop(approach: "ref" | "state"): boolean {
  return false; // TODO: only "state" should return true
}

export { RenderCounter, wouldCauseInfiniteLoop };

// --- self-check: do not modify below this line ---
const refCheck = wouldCauseInfiniteLoop("ref") === false;
const stateCheck = wouldCauseInfiniteLoop("state") === true;
console.log(refCheck && stateCheck ? "PASS (pure logic)" : "FAIL (pure logic)");

// Verify visually: mount <RenderCounter /> alongside a sibling that
// re-renders the parent on a button click. Each parent re-render should
// bump the displayed count by exactly 1 — never more, and it should never
// loop or freeze the page (which is what the commented-out
// BrokenRenderCounter using useState would do).
