import React from 'react';
import { MemoryRouter } from 'react-router-dom';
import { fireEvent, render, screen } from '@testing-library/react';
import { AnalyticsConsentProvider } from '../../contexts/AnalyticsConsentContext';
import AnalyticsConsentBanner from './AnalyticsConsentBanner';

const renderBanner = () =>
  render(
    <MemoryRouter>
      <AnalyticsConsentProvider>
        <AnalyticsConsentBanner />
      </AnalyticsConsentProvider>
    </MemoryRouter>,
  );

describe('AnalyticsConsentBanner', () => {
  const originalEnv = process.env;

  beforeEach(() => {
    localStorage.clear();
    process.env = { ...originalEnv, REACT_APP_DEPLOY_ENV: 'production' };
  });

  afterEach(() => {
    process.env = { ...originalEnv };
  });

  it('shows until the user accepts or declines', () => {
    renderBanner();
    expect(screen.getByRole('dialog', { name: /analytics consent/i })).toBeInTheDocument();
    expect(screen.getByText(/Help us improve Hesychia/i)).toBeInTheDocument();
    expect(screen.getByRole('link', { name: /Analytics and Cookies/i })).toHaveAttribute(
      'href',
      '/terms_of_service/#analytics',
    );
  });

  it('hides after accept and persists granted', () => {
    renderBanner();
    fireEvent.click(screen.getByRole('button', { name: /accept analytics/i }));
    expect(screen.queryByRole('dialog', { name: /analytics consent/i })).not.toBeInTheDocument();
    expect(localStorage.getItem('hesychia_analytics_consent_v1')).toBe('granted');
  });

  it('hides after decline and persists denied', () => {
    renderBanner();
    fireEvent.click(screen.getByRole('button', { name: /decline/i }));
    expect(screen.queryByRole('dialog', { name: /analytics consent/i })).not.toBeInTheDocument();
    expect(localStorage.getItem('hesychia_analytics_consent_v1')).toBe('denied');
  });
});
