import React from 'react';
import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest';
import { render, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';

import BottomNav from '../BottomNav';

const originalGetBoundingClientRect = HTMLElement.prototype.getBoundingClientRect;
const originalResizeObserver = globalThis.ResizeObserver;

vi.mock('../../hooks/useEventData', () => ({
  useEventData: () => ({
    status: 'ready',
    event: {
      id: 1,
      default_locale: 'de',
    },
  }),
}));

vi.mock('../../i18n/useTranslation', () => ({
  useTranslation: () => ({
    t: (key: string) => key,
  }),
}));

vi.mock('../../context/EventBrandingContext', () => ({
  useEventBranding: () => ({
    branding: {
      primaryColor: '#0f172a',
      secondaryColor: '#38bdf8',
      backgroundColor: '#ffffff',
      palette: {
        surface: '#ffffff',
      },
      buttons: {
        radius: 12,
        style: 'filled',
        linkColor: '#0f172a',
      },
    },
  }),
}));

vi.mock('../../lib/engagement', () => ({
  isTaskModeEnabled: () => false,
}));

describe('BottomNav', () => {
  beforeEach(() => {
    HTMLElement.prototype.getBoundingClientRect = () =>
      ({
        x: 0,
        y: 0,
        width: 0,
        height: 80,
        top: 0,
        left: 0,
        right: 0,
        bottom: 80,
        toJSON: () => ({}),
      }) as DOMRect;

    (globalThis as unknown as { ResizeObserver: typeof ResizeObserver }).ResizeObserver = class {
      private callback: () => void;

      constructor(callback: () => void) {
        this.callback = callback;
      }

      observe() {
        this.callback();
      }

      disconnect() {}
    };

    document.documentElement.style.removeProperty('--guest-bottom-nav-offset');
  });

  afterEach(() => {
    HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect;
    document.documentElement.style.removeProperty('--guest-bottom-nav-offset');
    if (originalResizeObserver) {
      globalThis.ResizeObserver = originalResizeObserver;
    } else {
      delete (globalThis as unknown as { ResizeObserver?: typeof ResizeObserver }).ResizeObserver;
    }
  });

  it('sets the bottom nav offset CSS variable', async () => {
    render(
      <MemoryRouter initialEntries={['/e/demo']}>
        <Routes>
          <Route path="/e/:token/*" element={<BottomNav />} />
        </Routes>
      </MemoryRouter>
    );

    await waitFor(() => {
      expect(document.documentElement.style.getPropertyValue('--guest-bottom-nav-offset')).toBe('80px');
    });
  });
});
