// Exercise 4: object dependency infinite loop — find and fix it
//
// `SearchResults` re-fetches on every single render because `queryOptions`
// is a brand-new object literal each time, and `Object.is` never considers
// two different object references "equal" even when their contents match.
// Fix it by depending on the PRIMITIVE fields directly instead of the
// object wrapping them.
//
// TODO 1: implement depsAreEqual(a, b) — pure function, Object.is per index,
//         same length required (mirrors what React does internally)
// TODO 2: fix SearchResults to depend on [query, page] instead of [queryOptions]

import { useEffect, useState } from "react";

// TODO 1: return true only if a and b have the same length AND every index
// is Object.is-equal. This mirrors React's own dependency comparison.
function depsAreEqual(a: unknown[], b: unknown[]): boolean {
  return false; // TODO: implement using Object.is per element
}

function SearchResults({ query, page }: { query: string; page: number }) {
  const [results, setResults] = useState<string[]>([]);
  const queryOptions = { query, page }; // BUG: new object reference every render

  useEffect(() => {
    // pretend this fetches search results using queryOptions
    setResults([`result for "${queryOptions.query}" page ${queryOptions.page}`]);
    // TODO 2: change the dependency array below from [queryOptions] to
    // [query, page] so this effect only re-runs when the PRIMITIVES change,
    // not on every render (queryOptions is recreated every render).
  }, [queryOptions]);

  return <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>;
}

export { SearchResults, depsAreEqual };

// --- self-check: do not modify below this line ---
const check1 = depsAreEqual([1, "a"], [1, "a"]) === true;
const check2 = depsAreEqual([1, "a"], [1, "b"]) === false;
const check3 = depsAreEqual([NaN], [NaN]) === true; // Object.is(NaN, NaN) is true
const check4 = depsAreEqual([{ x: 1 }], [{ x: 1 }]) === false; // different object references
console.log(check1 && check2 && check3 && check4 ? "PASS (depsAreEqual)" : "FAIL (depsAreEqual)");

// Verify visually: mount <SearchResults query="react" page={1} />, add a
// console.log inside the effect. Before the fix, the log fires on EVERY
// re-render of the parent (even ones unrelated to query/page) because
// queryOptions is a new object each time. After switching the dependency
// array to [query, page], the log should only fire when those primitive
// values actually change.
