import React from 'react';
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import Csempe from './Csempe';
import { useAuth } from '../Bejel_Regisz/AuthContext';
import * as fetchModule from '../../apiFetch';

// AuthContext mock
jest.mock('../Bejel_Regisz/AuthContext', () => ({
  useAuth: jest.fn()
}));

// mosdokFetch mock
jest.mock('../../apiFetch', () => ({
  mosdokFetch: jest.fn()
}));

describe('Csempe komponens', () => {
  const mockMosdok = [
    {
      id: 1,
      nev: 'Nyilvános WC',
      kerulet: { kerulet_nev: 'V. kerület' },
      kozeli_megall: 'Astoria',
      ar: 200,
      nyitva: '0-24',
      akadalym: 1,
      utvonal: 'https://maps.example.com/utvonal'
    }
  ];

  beforeEach(() => {
    fetch.resetMocks?.(); // ha használsz jest-fetch-mock-ot
    jest.clearAllMocks();
  });

  test('Adminnak megjelenik a Törlés gomb', async () => {
    useAuth.mockReturnValue({ user: { is_admin: true } });
    fetchModule.mosdokFetch.mockResolvedValue(mockMosdok);

    render(<Csempe />);

    await waitFor(() => {
      expect(screen.getByText(/Törlés/i)).toBeInTheDocument();
    });
  });

  test('Nem adminnak nem jelenik meg a Törlés gomb', async () => {
    useAuth.mockReturnValue({ user: { is_admin: false } });
    fetchModule.mosdokFetch.mockResolvedValue(mockMosdok);

    render(<Csempe />);

    await waitFor(() => {
      expect(screen.queryByText(/Törlés/i)).not.toBeInTheDocument();
    });
  });

  test('Hiba esetén megjelenik hibaüzenet', async () => {
    useAuth.mockReturnValue({ user: { is_admin: true } });
    fetchModule.mosdokFetch.mockResolvedValue(null);

    render(<Csempe />);

    await waitFor(() => {
      expect(screen.getByText(/Nem sikerült betölteni/i)).toBeInTheDocument();
    });
  });

  test('Betöltés alatt megjelenik spinner', async () => {
    useAuth.mockReturnValue({ user: { is_admin: true } });
    fetchModule.mosdokFetch.mockImplementation(() => new Promise(() => {})); // never resolves

    render(<Csempe />);
    expect(screen.getByRole('status')).toBeInTheDocument(); // a spinner div-ben legyen pl. role="status"
  });
});
