// Exercise 2: fix the stale closure inside a memoized callback
//
// `useLoggedSearch` memoizes a search handler with useCallback, but the
// dependency array is missing `query` — so the cached function keeps
// closing over whatever `query` was on the FIRST render, even after the
// user types something new.
//
// TODO 1: implement buildSearchLogEntry (pure, no hooks)
// TODO 2: fix the useCallback dependency array so the handler always logs
//         the CURRENT query, not a stale one

import { useCallback, useState } from "react";

interface LogEntry {
  query: string;
  timestamp: number;
}

// TODO 1: given a query and a fixed timestamp, return a LogEntry.
function buildSearchLogEntry(query: string, timestamp: number): LogEntry {
  return { query: "", timestamp: 0 }; // TODO: return { query, timestamp }
}

function useLoggedSearch(onSearch: (query: string) => void) {
  const [query, setQuery] = useState("");
  const [log, setLog] = useState<LogEntry[]>([]);

  // TODO 2: this dependency array is missing `query` (and `onSearch`), so
  // the SAME closure from the first render is reused forever — it always
  // logs whatever `query` was when the component first mounted (likely "").
  // Fix the dependency array so a fresh closure (with the current `query`)
  // is used whenever `query` or `onSearch` changes.
  const handleSearch = useCallback(() => {
    const entry = buildSearchLogEntry(query, Date.now());
    setLog((prev) => [...prev, entry]);
    onSearch(query);
  }, []); // BUG: missing deps

  return { query, setQuery, log, handleSearch };
}

export { useLoggedSearch, buildSearchLogEntry };

// --- self-check: do not modify below this line ---
const entry = buildSearchLogEntry("shoes", 1000);
const check1 = entry.query === "shoes" && entry.timestamp === 1000;
console.log(check1 ? "PASS (buildSearchLogEntry)" : "FAIL (buildSearchLogEntry)");

// Verify with React Testing Library or manually: render a component using
// useLoggedSearch, call setQuery("shoes"), then setQuery("boots"), calling
// handleSearch after each. Before the fix, every logged entry has an empty
// `query` (the stale closure from mount). After fixing the dependency
// array, the log should contain entries for "shoes" and then "boots".
