import React from 'react';
import { render } from '@testing-library/react';
import Tracker from './Tracker';

const TRACKER_SCRIPT_ID = 'hesychia-tianji-tracker';

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

  beforeEach(() => {
    document.body.innerHTML = '';
    process.env = {
      ...originalEnv,
      REACT_APP_DEPLOY_ENV: 'production',
      REACT_APP_TIANJI_WEBSITE_ID: 'cm7x7m52m03kbddswbswrt17y',
    };
  });

  afterEach(() => {
    process.env = { ...originalEnv };
    document.body.innerHTML = '';
  });

  it('loads Tianji tracker without analytics consent (page views always on)', () => {
    render(<Tracker />);

    const script = document.getElementById(TRACKER_SCRIPT_ID) as HTMLScriptElement | null;
    expect(script).not.toBeNull();
    expect(script?.src).toBe('https://tianji.aimloperations.com/tracker.js');
    expect(script?.getAttribute('data-website-id')).toBe('cm7x7m52m03kbddswbswrt17y');
  });

  it('loads distinct website id for beta builds', () => {
    process.env = {
      ...originalEnv,
      REACT_APP_DEPLOY_ENV: 'beta',
      REACT_APP_TIANJI_WEBSITE_ID: 'beta-website-id-test',
    };

    render(<Tracker />);

    const script = document.getElementById(TRACKER_SCRIPT_ID) as HTMLScriptElement | null;
    expect(script?.getAttribute('data-website-id')).toBe('beta-website-id-test');
  });

  it('does not load Tianji tracker outside analytics environments', () => {
    process.env = {
      ...originalEnv,
      NODE_ENV: 'development',
      REACT_APP_DEPLOY_ENV: undefined,
      REACT_APP_TIANJI_WEBSITE_ID: undefined,
    };

    render(<Tracker />);

    expect(document.getElementById(TRACKER_SCRIPT_ID)).toBeNull();
  });
});
