import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { mockStoreFactory, setMockStore, resetMockStore } from '../../test/mockStore';

vi.mock('../../store/useStore', () => mockStoreFactory());

const { HealthStats } = await import('./HealthStats');

const healthActions = {
  loadStats: vi.fn(),
  createStat: vi.fn(),
  updateStat: vi.fn(),
  deleteStat: vi.fn(),
  loadTrends: vi.fn(),
  clearError: vi.fn(),
  isLoading: false,
  error: null,
  stats: [],
  trends: [],
};

describe('HealthStats', () => {
  beforeEach(() => resetMockStore());

  it('shows the empty state when there are no readings', () => {
    setMockStore({ useHealthStore: { ...healthActions } });
    render(<HealthStats />);
    expect(screen.getByText(/No health readings yet/i)).toBeInTheDocument();
  });

  it('renders the readings table when stats exist', () => {
    setMockStore({
      useHealthStore: {
        ...healthActions,
        stats: [
          {
            stat_id: 's1',
            stat_type: 'weight',
            value: 78.5,
            unit: 'kg',
            measured_at: '2026-06-01T10:00:00.000Z',
          },
        ],
      },
    });
    render(<HealthStats />);
    // "weight" appears in both the chart selector and the table; the value
    // string is unique to the table cell.
    expect(screen.getByText('78.5 kg')).toBeInTheDocument();
    expect(screen.getByText('Jun 1, 07:00')).toBeInTheDocument();
  });

  it('opens the record dialog when Record is clicked', () => {
    setMockStore({ useHealthStore: { ...healthActions } });
    render(<HealthStats />);
    fireEvent.click(screen.getByText('Record'));
    expect(screen.getByText('Record a measurement')).toBeInTheDocument();
  });
});
