import http from './api';

interface AnalyticsPayload {
  task_no: string;
  event_name: string;
  properties: Record<string, any>;
  meta_data?: Record<string, any>;
  device_info: {
    ip: string;
    "use-agent": string;
    browser: string;
  };
}

export const trackExportEvent = (
  taskNo: string,
  selectedOption: string,
  availableOptions: string[]
) => {
  try {
    const payload: AnalyticsPayload = {
      task_no: taskNo,
      event_name: 'export_selected_event',
      properties: {
        option: availableOptions,
        selected: selectedOption
      },
      meta_data: {
        task_no: taskNo
      },
      device_info: {
        ip: '',
        "use-agent": navigator.userAgent,
        browser: getBrowserName()
      }
    };

    // Fire and forget - do not await
    http.post('/analytics/track', payload).catch(err => {
      // Silently ignore errors to not block business flow
      console.debug('Analytics tracking failed:', err);
    });
  } catch (error) {
    console.debug('Analytics error:', error);
  }
};

function getBrowserName(): string {
  const userAgent = navigator.userAgent;
  if (userAgent.match(/chrome|chromium|crios/i)) {
    return "Chrome";
  } else if (userAgent.match(/firefox|fxios/i)) {
    return "Firefox";
  } else if (userAgent.match(/safari/i)) {
    return "Safari";
  } else if (userAgent.match(/opr\//i)) {
    return "Opera";
  } else if (userAgent.match(/edg/i)) {
    return "Edge";
  } else {
    return "Unknown";
  }
}
