import { EnviveMetricsEventName } from '../../amplitudeService/eventNames';
import { projectToGA4 } from '../ga4ProjectionService';

describe('projectToGA4', () => {
  beforeEach(() => {
    window.dataLayer = [];
  });

  afterEach(() => {
    delete (window as any).dataLayer;
  });

  describe('excluded events', () => {
    it('should not push to dataLayer for WidgetTextRequest', () => {
      projectToGA4(EnviveMetricsEventName.WidgetTextRequest, { widget_type: 'test' });
      expect(window.dataLayer).toHaveLength(0);
    });

    it('should not push to dataLayer for WidgetTextResponse', () => {
      projectToGA4(EnviveMetricsEventName.WidgetTextResponse, { widget_type: 'test' });
      expect(window.dataLayer).toHaveLength(0);
    });

    it('should not push to dataLayer for WidgetTextClicked', () => {
      projectToGA4(EnviveMetricsEventName.WidgetTextClicked, { text: 'hello' });
      expect(window.dataLayer).toHaveLength(0);
    });
  });

  describe('Widget Rendered', () => {
    it('should push renamed GA4 fields from nested input', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button' },
        context: { page_type: 'pdp', page_id: 'product-123' },
      });

      expect(window.dataLayer).toHaveLength(1);
      expect(window.dataLayer[0]).toEqual({
        event: 'envive_widget_rendered',
        page_type: 'pdp',
        page_id: 'product-123',
        widget: 'floating_button',
      });
    });

    it('should also accept flat dot-notation input', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'trigger.widget': 'floating_button',
        'trigger.interaction_id': 'abc-123',
      });

      expect(window.dataLayer[0]).toEqual({
        event: 'envive_widget_rendered',
        page_type: 'pdp',
        page_id: 'product-123',
        widget: 'floating_button',
      });
    });

    it('should exclude fields not in fieldProjections', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button', interaction_id: 'should-be-dropped' },
        context: { page_type: 'pdp', page_id: 'product-123' },
        'some.random_field': 'also-dropped',
      });

      const pushed = window.dataLayer[0];
      expect(pushed).not.toHaveProperty('interaction_id');
      expect(pushed).not.toHaveProperty('some_random_field');
    });
  });

  describe('page_id sanitization', () => {
    it('should keep page_id for pdp page type', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button' },
        context: { page_type: 'pdp', page_id: 'product-123' },
      });

      expect(window.dataLayer[0]).toHaveProperty('page_id', 'product-123');
    });

    it('should keep page_id for plp page type', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button' },
        context: { page_type: 'plp', page_id: 'category-456' },
      });

      expect(window.dataLayer[0]).toHaveProperty('page_id', 'category-456');
    });

    it('should omit page_id for search page type', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button' },
        context: { page_type: 'search', page_id: 'some search query' },
      });

      expect(window.dataLayer[0]).not.toHaveProperty('page_id');
    });

    it('should omit page_id for homepage page type', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button' },
        context: { page_type: 'homepage', page_id: 'https://example.com' },
      });

      expect(window.dataLayer[0]).not.toHaveProperty('page_id');
    });

    it('should omit page_id for other page type', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {
        trigger: { widget: 'floating_button' },
        context: { page_type: 'other', page_id: 'https://example.com/about' },
      });

      expect(window.dataLayer[0]).not.toHaveProperty('page_id');
    });
  });

  describe('Widget Interaction', () => {
    it('should push renamed GA4 fields (flat dot-notation input)', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'trigger.widget': 'chat_overlay',
        'trigger.widget_interaction': 'link_clicked',
        'trigger.interaction_class': 'intentional',
      });

      expect(window.dataLayer[0]).toEqual({
        event: 'envive_widget_interaction',
        page_type: 'pdp',
        page_id: 'product-123',
        widget: 'chat_overlay',
        interaction_type: 'link_clicked',
        interaction_class: 'intentional',
      });
    });

    it('should project from real Amplitude nested-object props', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        trigger: {
          widget: 'floating_button',
          widget_interaction: 'widget_clicked',
          interaction_id: '604a2e2c-9848-41dd-a2b1-cb5b8612ec08',
          interaction_class: 'intentional',
        },
        context: {
          page_id: 'hsa-fsa-eligible',
          page_type: 'plp',
        },
        'environment.execution_context': 'bundle',
        'org.short_name': 'dermalogica',
      });

      expect(window.dataLayer[0]).toEqual({
        event: 'envive_widget_interaction',
        page_type: 'plp',
        page_id: 'hsa-fsa-eligible',
        widget: 'floating_button',
        interaction_type: 'widget_clicked',
        interaction_class: 'intentional',
      });
    });

    it('should omit page_id for non-pdp/plp page types (nested input)', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        trigger: { widget: 'floating_button', widget_interaction: 'widget_clicked' },
        context: { page_type: 'homepage', page_id: 'https://example.com' },
      });

      expect(window.dataLayer[0]).not.toHaveProperty('page_id');
      expect(window.dataLayer[0]).toHaveProperty('page_type', 'homepage');
    });

    it('should extract interaction_collapse_source from widget_interaction_data for widget_collapsed', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'trigger.widget': 'chat_overlay',
        'trigger.widget_interaction': 'widget_collapsed',
        'trigger.widget_interaction_data': {
          widget_collapsed: { collapse_source: 'close_button' },
        },
      });

      expect(window.dataLayer[0]).toHaveProperty('interaction_collapse_source', 'close_button');
    });

    it('should extract interaction_collapse_source from nested real-data trigger object', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        trigger: {
          widget: 'floating_button',
          widget_interaction: 'widget_collapsed',
          interaction_class: 'navigational',
          widget_interaction_data: { widget_collapsed: { collapse_source: 'swipe' } },
        },
        context: { page_type: 'pdp', page_id: 'product-123' },
      });

      expect(window.dataLayer[0]).toHaveProperty('interaction_collapse_source', 'swipe');
      expect(window.dataLayer[0]).toHaveProperty('interaction_class', 'navigational');
    });

    it('should extract interaction_product_id from widget_interaction_data for product_card_clicked', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'trigger.widget': 'chat_overlay',
        'trigger.widget_interaction': 'product_card_clicked',
        'trigger.widget_interaction_data': { product_card_clicked: { product_id: 'sku-789' } },
      });

      const pushed = window.dataLayer[0];
      expect(pushed).toHaveProperty('interaction_product_id', 'sku-789');
    });

    it('should extract suggestion_id from widget_interaction_data for suggestion_scrolled', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'trigger.widget': 'chat_overlay',
        'trigger.widget_interaction': 'suggestion_scrolled',
        'trigger.widget_interaction_data': { suggestion_scrolled: { suggestion_id: 'sug-456' } },
      });

      expect(window.dataLayer[0]).toHaveProperty('interaction_suggestion_id', 'sug-456');
    });

    it('should drop widget_interaction_data for unwhitelisted interactions', () => {
      projectToGA4(EnviveMetricsEventName.WidgetInteraction, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'trigger.widget': 'chat_overlay',
        'trigger.widget_interaction': 'link_clicked',
        'trigger.widget_interaction_data': { url: 'https://example.com' },
      });

      const pushed = window.dataLayer[0];
      expect(pushed).not.toHaveProperty('url');
      expect(pushed).not.toHaveProperty('trigger_widget_interaction_data');
    });
  });

  describe('Chat Request', () => {
    it('should include only allowed fields', () => {
      projectToGA4(EnviveMetricsEventName.ChatRequest, {
        page_type: 'pdp',
        page_id: 'product-123',
        'trigger.widget': 'chat_overlay',
        'chat.request_id': 'req-001',
        'chat.request_type': 'suggestion',
        'chat.request_text': 'Tell me about this product',
        'chat.user_typed': false,
        'chat.suggestion_id': 'sug-123',
        'chat.suggestion_category': 'product_info',
      });

      const pushed = window.dataLayer[0];
      expect(pushed).toEqual({
        event: 'envive_chat_request',
        page_type: 'pdp',
        page_id: 'product-123',
        trigger_widget: 'chat_overlay',
        chat_request_type: 'suggestion',
        chat_user_typed: false,
        chat_suggestion_id: 'sug-123',
        chat_suggestion_category: 'product_info',
      });
    });
  });

  describe('Chat Response', () => {
    it('should include only allowed fields', () => {
      projectToGA4(EnviveMetricsEventName.ChatResponse, {
        page_type: 'plp',
        page_id: 'category-456',
        'trigger.widget': 'chat_overlay',
        'chat.response_time_ms': '1200',
        'chat.request_type': 'text',
        'chat.request_id': 'req-001',
        'chat.request_text': 'Show me shoes',
        'chat.user_typed': true,
        'chat.product_cards_returned': 3,
        'chat.review_cards_returned': 0,
      });

      const pushed = window.dataLayer[0];
      expect(pushed).toEqual({
        event: 'envive_chat_response',
        page_type: 'plp',
        page_id: 'category-456',
        trigger_widget: 'chat_overlay',
        chat_user_typed: true,
        chat_response_time_ms: '1200',
        chat_product_cards_returned: 3,
        chat_review_cards_returned: 0,
      });
    });
  });

  describe('Envive Initialized', () => {
    it('should include only allowed fields and drop environment details', () => {
      projectToGA4(EnviveMetricsEventName.EnviveInitialized, {
        'environment.execution_context': 'bundle',
        'environment.page_url': 'https://example.com/products/shoe',
        'environment.envive_user_id': 'user-abc',
        'environment.execution_environment': 'prod',
        'environment.context_source': 'app',
        'environment.sales_agent_enabled': true,
        'environment.search_enabled': false,
        'environment.envive_on_query_param': false,
        'environment.window_show': true,
        'environment.client_session': true,
        'environment.envive_enabled': true,
        'performance.start_time_ms': 150,
        'performance.initialize_time_ms': 320,
      });

      expect(window.dataLayer[0]).toEqual({
        event: 'envive_initialized',
        environment_sales_agent_enabled: true,
        environment_envive_enabled: true,
        performance_start_time_ms: 150,
        performance_initialize_time_ms: 320,
      });
    });
  });

  describe('Page Viewed', () => {
    it('should use envive_page_context_evaluated as event name', () => {
      projectToGA4(EnviveMetricsEventName.PageViewed, {
        'context.page_type': 'pdp',
        'context.page_id': 'product-123',
        'context.supported': true,
        'context.ready': true,
        'context.page_variant_id': 'variant-A',
        'environment.envive_enabled': true,
      });

      expect(window.dataLayer[0]).toEqual({
        event: 'envive_page_context_evaluated',
        page_type: 'pdp',
        page_id: 'product-123',
        context_supported: true,
        context_ready: true,
        context_page_variant_id: 'variant-A',
        environment_envive_enabled: true,
      });
    });

    it('should omit page_id for non-pdp/plp page types', () => {
      projectToGA4(EnviveMetricsEventName.PageViewed, {
        'context.page_type': 'search',
        'context.page_id': 'shoes',
        'context.supported': true,
        'context.ready': true,
        'environment.envive_enabled': true,
      });

      const pushed = window.dataLayer[0];
      expect(pushed).not.toHaveProperty('page_id');
      expect(pushed).toHaveProperty('page_type', 'search');
    });
  });

  describe('edge cases', () => {
    it('should handle undefined eventProps', () => {
      projectToGA4(EnviveMetricsEventName.EnviveInitialized);

      expect(window.dataLayer).toHaveLength(1);
      expect(window.dataLayer[0]).toEqual({ event: 'envive_initialized' });
    });

    it('should handle empty eventProps', () => {
      projectToGA4(EnviveMetricsEventName.WidgetRendered, {});

      expect(window.dataLayer).toHaveLength(1);
      expect(window.dataLayer[0]).toEqual({ event: 'envive_widget_rendered' });
    });

    it('should not throw when window.dataLayer is undefined', () => {
      delete (window as any).dataLayer;

      expect(() => {
        projectToGA4(EnviveMetricsEventName.WidgetRendered, {
          'context.page_type': 'pdp',
          'trigger.widget': 'floating_button',
        });
      }).not.toThrow();
    });
  });
});
