import React, { useEffect } from 'react';
import { flushAnalyticsQueue } from '../../utils/analytics';
import { isAnalyticsEnvironment } from '../../utils/analyticsConsent';

const TRACKER_SCRIPT_ID = 'hesychia-tianji-tracker';

/**
 * Loads Tianji tracker.js for automatic page views on prod/beta builds.
 * Page views always run (no consent gate). Custom events use analytics.ts + consent.
 */
const Tracker: React.FC = () => {
  useEffect(() => {
    if (!isAnalyticsEnvironment()) return;

    const websiteId = process.env.REACT_APP_TIANJI_WEBSITE_ID || '';
    if (!websiteId || document.getElementById(TRACKER_SCRIPT_ID)) return;

    const script = document.createElement('script');
    script.id = TRACKER_SCRIPT_ID;
    script.src = 'https://tianji.aimloperations.com/tracker.js';
    script.async = true;
    script.defer = true;
    script.setAttribute('data-website-id', websiteId);
    script.setAttribute('data-do-not-track', 'true');
    script.onload = () => {
      flushAnalyticsQueue();
    };

    document.body.appendChild(script);

    return () => {
      const loaded = document.getElementById(TRACKER_SCRIPT_ID);
      if (loaded?.parentNode) {
        loaded.parentNode.removeChild(loaded);
      }
    };
  }, []);

  return null;
};

export default Tracker;
