import React from 'react';
import { render, screen } from '@testing-library/react';
import { userEvent } from '@testing-library/user-event';
import { CartProvider, useCart } from '../CartContext';

// Test component that uses the useCart hook
function TestComponent() {
  const { itemCount, addToCart } = useCart();
  
  const mockItem = {
    id: 'test-product',
    name: 'Test Product',
    price: 1000,
    image: '/test.jpg',
  };
  
  return (
    <div>
      <span data-testid="item-count">{itemCount}</span>
      <button onClick={() => addToCart(mockItem, 1)}>Add 1</button>
      <button onClick={() => addToCart(mockItem, 5)}>Add 5</button>
    </div>
  );
}

describe('CartContext', () => {
  beforeEach(() => {
    localStorage.clear();
  });

  describe('CartProvider', () => {
    it('renders children correctly', () => {
      render(
        <CartProvider>
          <div>Test Content</div>
        </CartProvider>
      );
      expect(screen.getByText('Test Content')).toBeInTheDocument();
    });

    it('provides initial itemCount of 0', () => {
      render(
        <CartProvider>
          <TestComponent />
        </CartProvider>
      );
      expect(screen.getByTestId('item-count')).toHaveTextContent('0');
    });

    it('increments itemCount when addToCart is called', async () => {
      const user = userEvent.setup();
      render(
        <CartProvider>
          <TestComponent />
        </CartProvider>
      );
      
      expect(screen.getByTestId('item-count')).toHaveTextContent('0');
      
      await user.click(screen.getByText('Add 1'));
      expect(screen.getByTestId('item-count')).toHaveTextContent('1');
    });

    it('accumulates itemCount across multiple addToCart calls', async () => {
      const user = userEvent.setup();
      render(
        <CartProvider>
          <TestComponent />
        </CartProvider>
      );
      
      await user.click(screen.getByText('Add 1'));
      expect(screen.getByTestId('item-count')).toHaveTextContent('1');
      
      await user.click(screen.getByText('Add 5'));
      expect(screen.getByTestId('item-count')).toHaveTextContent('6');
      
      await user.click(screen.getByText('Add 1'));
      expect(screen.getByTestId('item-count')).toHaveTextContent('7');
    });
  });

  describe('useCart', () => {
    it('throws error when used outside CartProvider', () => {
      // Suppress console.error for this test
      const consoleSpy = jest.spyOn(console, 'error').mockImplementation();
      
      expect(() => {
        render(<TestComponent />);
      }).toThrow('useCart must be used within a CartProvider');
      
      consoleSpy.mockRestore();
    });
  });
});
