// Exercise 2: broken dependency — the inline-object trap
//
// `useDashboardSummary` tries to memoize a summary computation but passes
// a freshly-created object literal as the dependency, which defeats the
// memoization entirely (a new object is never Object.is-equal to the last
// one). Fix the dependency array so the cache actually hits, WITHOUT
// changing what `computeSummary` receives.
//
// TODO 1: implement computeSummary (pure, no hooks)
// TODO 2: fix the useMemo dependency array so it depends on primitives,
//         not a freshly-created object literal

import { useMemo, useState } from "react";

interface Summary {
  total: number;
  average: number;
}

// TODO 1: given an array of numbers, return { total, average }.
// average should be 0 (not NaN) for an empty array.
function computeSummary(values: number[]): Summary {
  return { total: 0, average: 0 }; // TODO: implement real total/average
}

function useDashboardSummary(userId: string, values: number[]) {
  // TODO 2: this dependency array creates a NEW object every render, so
  // Object.is never matches and the memo never hits. Fix it to depend on
  // `userId` and `values` directly (or on primitives derived from them),
  // while still passing computeSummary the same `values` array.
  const summary = useMemo(() => computeSummary(values), [{ userId }]);
  return summary;
}

function Dashboard({ userId, values }: { userId: string; values: number[] }) {
  const [tick, setTick] = useState(0);
  const summary = useDashboardSummary(userId, values);

  return (
    <div>
      <button onClick={() => setTick((t) => t + 1)}>Re-render ({tick})</button>
      <p>
        Total: {summary.total}, Average: {summary.average}
      </p>
    </div>
  );
}

export { Dashboard, useDashboardSummary, computeSummary };

// --- self-check: do not modify below this line ---
const s1 = computeSummary([2, 4, 6]);
const check1 = s1.total === 12 && s1.average === 4;

const s2 = computeSummary([]);
const check2 = s2.total === 0 && s2.average === 0;

console.log(check1 ? "PASS (computeSummary basic)" : "FAIL (computeSummary basic)");
console.log(check2 ? "PASS (computeSummary empty array)" : "FAIL (computeSummary empty array)");

// Verify visually/manually: add a console.log inside the useMemo factory.
// Before the fix, it logs on every "Re-render" click even though `values`
// didn't change. After the fix, it should only log when `values` (or the
// primitives it depends on) actually changes, not on unrelated `tick` updates.
