import { describe, it, expect, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import Cart from './Cart';
import { useDesignStore } from '../store/designStore';
import type { Stone } from '../types';

const testStone: Stone = { id: 1, name: 'Akik', image: '/akik.jpg', active: true };
const testStone2: Stone = { id: 2, name: 'Amazonit', image: '/amazonit.jpg', active: true };

function resetStore() {
  useDesignStore.setState({
    jewelryType: 'bileklik',
    size: { label: 'M', circumferenceCm: 18 },
    stoneSizeMm: 8,
  });
  useDesignStore.getState().resetSlots();
}

describe('Cart — empty state', () => {
  beforeEach(resetStore);

  it('shows empty cart message when no stones placed', () => {
    render(<Cart />);
    expect(screen.getByText('Sepetiniz Boş!')).toBeInTheDocument();
    expect(
      screen.getByText('Taşları Modelin Üzerine Sürükleyip Bırakarak Burada Sepetinizi Görebilirsiniz'),
    ).toBeInTheDocument();
  });

  it('does not show counter when empty', () => {
    render(<Cart />);
    expect(screen.queryByTestId('cart-counter')).not.toBeInTheDocument();
  });
});

describe('Cart — with stones', () => {
  beforeEach(() => {
    resetStore();
    useDesignStore.getState().placeStone(0, testStone);
    useDesignStore.getState().placeStone(1, testStone2);
  });

  it('shows placed stones in the list', () => {
    render(<Cart />);
    expect(screen.getByText('Akik')).toBeInTheDocument();
    expect(screen.getByText('Amazonit')).toBeInTheDocument();
  });

  it('does not show empty message when stones are placed', () => {
    render(<Cart />);
    expect(screen.queryByText('Sepetiniz Boş!')).not.toBeInTheDocument();
  });

  it('shows X/Y counter', () => {
    render(<Cart />);
    const counter = screen.getByTestId('cart-counter');
    const slotCount = useDesignStore.getState().slotCount;
    expect(counter.textContent).toBe(`2/${slotCount}`);
  });

  it('removes a stone when X button is clicked', () => {
    render(<Cart />);
    const removeButtons = screen.getAllByRole('button', { name: /taşını çıkar/i });
    fireEvent.click(removeButtons[0]);

    const slots = useDesignStore.getState().slots;
    expect(slots[0].stone).toBeNull();
  });

  it('shows empty state after removing all stones', () => {
    // Remove stones directly via store, then verify Cart renders empty state
    useDesignStore.getState().removeStone(0);
    useDesignStore.getState().removeStone(1);

    render(<Cart />);
    expect(screen.getByText('Sepetiniz Boş!')).toBeInTheDocument();
  });
});
