// Exercise 2: lazy initialization + immutable updates
//
// Implement `loadInitialTodos` (simulates a slow computation — pretend it's
// parsing a big cached blob) and pass it to useState as a LAZY initializer
// (a function), not a direct call, so it only runs once on mount.
//
// Then implement `addTodo` and `removeTodo` so they always produce a NEW
// array reference (never mutate `todos` in place with push/splice).
//
// TODO 1: loadInitialTodos — pure function, returns Todo[]
// TODO 2: pass it to useState as `() => loadInitialTodos()`, not a direct call
// TODO 3: addTodo — must return a new array via spread, never .push()
// TODO 4: removeTodo — must return a new array via .filter(), never .splice()

import { useState } from "react";

interface Todo {
  id: number;
  text: string;
}

let expensiveCallCount = 0; // instrumentation only, for the self-check below

// TODO 1: return a starter list of Todo objects (any 2-3 items are fine).
// Increment expensiveCallCount each time this runs, so the self-check can
// verify it only ran once even across multiple re-renders.
function loadInitialTodos(): Todo[] {
  expensiveCallCount++;
  return []; // TODO: return some starter todos, e.g. [{ id: 1, text: "Learn useState" }]
}

function TodoApp() {
  // TODO 2: use the LAZY initializer form — useState(() => loadInitialTodos())
  const [todos, setTodos] = useState<Todo[]>(loadInitialTodos()); // BUG: not lazy yet

  function addTodo(text: string) {
    // TODO 3: replace with an immutable update, e.g.
    // setTodos((prev) => [...prev, { id: Date.now(), text }]);
  }

  function removeTodo(id: number) {
    // TODO 4: replace with an immutable update, e.g.
    // setTodos((prev) => prev.filter((t) => t.id !== id));
  }

  return (
    <ul>
      {todos.map((t) => (
        <li key={t.id}>
          {t.text} <button onClick={() => removeTodo(t.id)}>x</button>
        </li>
      ))}
      <button onClick={() => addTodo("New item")}>Add</button>
    </ul>
  );
}

export { TodoApp, loadInitialTodos };

// --- self-check: do not modify below this line ---
const todosOnce = loadInitialTodos();
const hasStarterItems = todosOnce.length > 0;
console.log(hasStarterItems ? "PASS (starter todos exist)" : "FAIL (starter todos exist)");

// Verify visually: mount <TodoApp />, open React DevTools or add a
// console.log inside loadInitialTodos — it must log ONCE on mount, never
// again after clicking Add/remove (proves the lazy-initializer form is
// wired correctly). Clicking Add/remove must update the list on screen
// (proves the immutable array updates are wired correctly).
