// Exercise 3: useMemo for reference stability, feeding React.memo + useEffect
//
// `ChartPanel` receives `config` from its parent. `MemoizedChart` is wrapped
// in React.memo, so it should only re-render when its props actually change
// by value — but `config` is rebuilt as a new object literal on every parent
// render, defeating React.memo. A `useEffect` inside `MemoizedChart` also
// depends on `config`, so it re-runs every single render too.
//
// TODO 1: implement buildChartConfig (pure, no hooks)
// TODO 2: memoize `config` in ChartPanel with useMemo so MemoizedChart
//         (and its internal effect) only react to real changes in
//         `theme`/`maxValue`, not unrelated parent re-renders

import { memo, useEffect, useMemo, useState } from "react";

interface ChartConfig {
  theme: "light" | "dark";
  maxValue: number;
}

// TODO 1: return a ChartConfig built from theme and maxValue.
function buildChartConfig(theme: "light" | "dark", maxValue: number): ChartConfig {
  return { theme: "light", maxValue: 0 }; // TODO: return { theme, maxValue }
}

let effectRunCount = 0; // test hook: counts how many times the effect below fires

const MemoizedChart = memo(function MemoizedChart({ config }: { config: ChartConfig }) {
  useEffect(() => {
    effectRunCount++;
    // pretend this configures a charting library using `config`
  }, [config]);

  return (
    <div>
      Chart theme={config.theme} max={config.maxValue}
    </div>
  );
});

function ChartPanel({ theme, maxValue }: { theme: "light" | "dark"; maxValue: number }) {
  const [unrelatedTick, setUnrelatedTick] = useState(0);

  // TODO 2: replace this with useMemo(() => buildChartConfig(theme, maxValue), [theme, maxValue])
  const config = buildChartConfig(theme, maxValue);

  return (
    <div>
      <button onClick={() => setUnrelatedTick((t) => t + 1)}>
        Unrelated re-render ({unrelatedTick})
      </button>
      <MemoizedChart config={config} />
    </div>
  );
}

export { ChartPanel, MemoizedChart, buildChartConfig, effectRunCount };

// --- self-check: do not modify below this line ---
const c1 = buildChartConfig("dark", 100);
const check1 = c1.theme === "dark" && c1.maxValue === 100;
console.log(check1 ? "PASS (buildChartConfig)" : "FAIL (buildChartConfig)");

// Verify visually: mount <ChartPanel theme="light" maxValue={100} />, click
// "Unrelated re-render" several times. Before fixing TODO 2, `effectRunCount`
// increments on every click (config is a new reference every render, so
// React.memo can't help and the effect's dependency never matches). After
// fixing TODO 2 with useMemo, `effectRunCount` should stay at 1 across those
// clicks, since `theme`/`maxValue` never actually changed.
