// Exercise 3: useCallback as a dependency of useEffect (harder)
//
// `useWindowWidthLogger` subscribes to window resize events inside a
// useEffect. The subscribe callback (`handleResize`) is recreated every
// render because it isn't memoized, so the effect's cleanup+resubscribe
// cycle runs on EVERY render, not just when `label` changes — defeating the
// purpose of having a stable subscription.
//
// TODO 1: implement formatWidthMessage (pure, no hooks)
// TODO 2: wrap handleResize in useCallback with the correct dependencies
//         so the effect only resubscribes when `label` actually changes

import { useCallback, useEffect, useState } from "react";

let subscribeCount = 0; // test hook: counts how many times the effect (re)subscribed

// TODO 1: return a message like "[label] width is now 1024px"
function formatWidthMessage(label: string, width: number): string {
  return ""; // TODO: return `[${label}] width is now ${width}px`
}

function useWindowWidthLogger(label: string) {
  const [messages, setMessages] = useState<string[]>([]);

  // TODO 2: this is a NEW function every render (no useCallback at all),
  // so the effect below — which lists handleResize as a dependency — tears
  // down and resubscribes on every render, not just when `label` changes.
  // Wrap it in useCallback with the correct dependency array. Use the
  // functional updater form for setMessages so `label` is the only real
  // dependency needed.
  const handleResize = () => {
    const width = typeof window !== "undefined" ? window.innerWidth : 0;
    setMessages((prev) => [...prev, formatWidthMessage(label, width)]);
  };

  useEffect(() => {
    subscribeCount++;
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [handleResize]);

  return messages;
}

export { useWindowWidthLogger, formatWidthMessage, subscribeCount };

// --- self-check: do not modify below this line ---
const check1 = formatWidthMessage("sidebar", 1024) === "[sidebar] width is now 1024px";
const check2 = formatWidthMessage("header", 0) === "[header] width is now 0px";
console.log(check1 && check2 ? "PASS (formatWidthMessage)" : "FAIL (formatWidthMessage)");

// Verify visually: render a component using useWindowWidthLogger("sidebar"),
// force several unrelated re-renders (e.g. via a parent's counter state).
// Before fixing TODO 2, `subscribeCount` increments on every re-render.
// After wrapping handleResize in useCallback([label]), `subscribeCount`
// should stay at 1 across those re-renders, only increasing if `label`
// itself changes.
