// src/components/MapView.test.tsx
import React from 'react';
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MapView } from './MapView';
import config from '../config';

// Create a type-safe mocked version of the config for easier manipulation
const mockedConfig = vi.mocked(config);

// Mock the config module statically.
// This allows us to manipulate the default export directly in tests because
// import { MapView } from './MapView' and import config from '../config' share the same mock object.
vi.mock('../config', () => ({
  default: {
    google: {
      mapsEmbedApiKey: undefined as string | undefined,
    },
    app: {
      version: 'test',
      commitMessage: 'test',
      commitUrl: 'test',
    },
  },
}));

describe('MapView', () => {
  const defaultProps = {
    latitude: 40.7128,
    longitude: -74.006,
  };

  beforeEach(() => {
    vi.clearAllMocks();
    // Reset config to a known state (undefined) before each test
    // By casting to unknown first, then to the desired type, we can safely
    // bypass the initial type mismatch without resorting to `any`.
    (mockedConfig.google.mapsEmbedApiKey as unknown as string | undefined) = undefined;
  });

  describe('when API key is not configured', () => {
    it('should render a disabled message', () => {
      render(<MapView {...defaultProps} />);
      expect(
        screen.getByText('Map view is disabled: API key is not configured.'),
      ).toBeInTheDocument();
    });

    it('should not render the iframe', () => {
      render(<MapView {...defaultProps} />);
      // Use queryByTitle because iframes don't have a default "iframe" role
      expect(screen.queryByTitle('Map view')).not.toBeInTheDocument();
    });
  });

  describe('when API key is configured', () => {
    const mockApiKey = 'test-api-key';

    beforeEach(() => {
      // Set a specific API key for this suite
      mockedConfig.google.mapsEmbedApiKey = mockApiKey;
    });

    it('should render the iframe with the correct src URL', () => {
      render(<MapView {...defaultProps} />);

      // Use getByTitle to access the iframe
      const iframe = screen.getByTitle('Map view');
      const expectedSrc = `https://www.google.com/maps/embed/v1/view?key=${mockApiKey}&center=${defaultProps.latitude},${defaultProps.longitude}&zoom=14`;

      expect(iframe).toBeInTheDocument();
      expect(iframe).toHaveAttribute('src', expectedSrc);
      expect(iframe).toHaveAttribute('width', '100%');
      expect(iframe).toHaveAttribute('height', '100%');
      expect(iframe).toHaveAttribute('loading', 'lazy');
      expect(iframe).toHaveAttribute('allowFullScreen');
    });
  });
});
