import React from 'react';
import '@testing-library/jest-dom';
import { render, screen, fireEvent } from '@testing-library/react';
import { ConfirmProvider, useConfirm } from './confirm';
import { I18nProvider } from './i18n/I18nProvider';

function Demo() {
  const { confirm } = useConfirm();
  return (
    <button onClick={() => void confirm({ title: 'Delete job', message: 'Are you sure?', confirmLabel: 'Delete', destructive: true })}>
      Open confirm
    </button>
  );
}

function DefaultDemo() {
  const { confirm } = useConfirm();
  return <button onClick={() => void confirm({ message: 'Fortsett?' })}>Open localized confirm</button>;
}

test('renders app-owned confirmation dialog', async () => {
  render(
    <ConfirmProvider>
      <Demo />
    </ConfirmProvider>,
  );

  fireEvent.click(screen.getByRole('button', { name: /open confirm/i }));

  expect(await screen.findByText(/are you sure/i)).toBeInTheDocument();
  expect(screen.getByRole('button', { name: /delete/i })).toBeInTheDocument();
});

test('uses the selected language for shared dialog defaults', async () => {
  window.localStorage.setItem('uiLanguage', 'nb');
  render(
    <I18nProvider>
      <ConfirmProvider>
        <DefaultDemo />
      </ConfirmProvider>
    </I18nProvider>,
  );

  fireEvent.click(screen.getByRole('button', { name: /open localized confirm/i }));
  expect(await screen.findByRole('heading', { name: 'Bekreft handling' })).toBeInTheDocument();
  expect(screen.getByRole('button', { name: 'Bekreft' })).toBeInTheDocument();
  window.localStorage.removeItem('uiLanguage');
});
