// Exercise 1: derive, don't store (theory Section 5)
//
// CartSummary currently stores `total` as its OWN state and a useEffect
// re-syncs it whenever `items` changes. This is the classic "redundant
// state" bug: forget to add `items` to the effect deps, or update items
// through a path that skips the effect, and `total` goes stale.
//
// STEP 1: implement calculateTotal(items) — a PURE function, no React.
// STEP 2: delete the `total` state and the useEffect entirely; compute
//         the total directly during render instead.

import { useEffect, useState } from "react";

interface CartItem {
  name: string;
  price: number;
  quantity: number;
}

// STEP 1: pure — sum of price * quantity across all items
function calculateTotal(items: CartItem[]): number {
  // TODO: return items.reduce((sum, item) => sum + item.price * item.quantity, 0)
  return 0; // placeholder
}

function CartSummary({ items }: { items: CartItem[] }) {
  // TODO STEP 2: delete these two hooks and replace the JSX below with
  // `const total = calculateTotal(items);` computed directly during render
  const [total, setTotal] = useState(0);
  useEffect(() => {
    setTotal(calculateTotal(items));
  }, []); // BUG: missing `items` dependency — total goes stale on every update

  return (
    <div>
      <span>Items: {items.length}</span>
      <span>Total: ${total.toFixed(2)}</span>
    </div>
  );
}

export { calculateTotal, CartSummary };

// --- self-check: do not modify below this line ---
const empty = calculateTotal([]);
console.log(empty === 0 ? "PASS (empty cart totals 0)" : "FAIL (empty cart totals 0)");

const items: CartItem[] = [
  { name: "Book", price: 12.5, quantity: 2 },
  { name: "Pen", price: 1.5, quantity: 4 },
];
const total = calculateTotal(items);
const expected = 12.5 * 2 + 1.5 * 4; // 31
console.log(
  Math.abs(total - expected) < 1e-9 ? "PASS (total sums price * quantity)" : "FAIL (total sums price * quantity)",
);

const single = calculateTotal([{ name: "Mug", price: 9.99, quantity: 1 }]);
console.log(Math.abs(single - 9.99) < 1e-9 ? "PASS (single item works)" : "FAIL (single item works)");

// Verify visually: render <CartSummary items={[...]} />, then re-render it
// with a DIFFERENT items array (e.g. via a parent that adds an item on a
// button click). BEFORE fixing STEP 2, the displayed Total lags one render
// behind the actual items (or never updates at all, since the effect's
// dependency array is empty). AFTER computing `total` directly during
// render, the displayed total is always correct on the very same render
// that received the new items — there's no "sync" step to forget.
