/**
 * TelemetryManager - Tracks framework usage across platforms
 */

import { Platform } from '../VideoPlayerFactory';

export interface TelemetryData {
    domain: string;
    platform: Platform;
    version: string;
    timestamp: number;
    status: 'init' | 'heartbeat' | 'error';
    userAgent: string;
}

export class TelemetryManager {
    private static instance: TelemetryManager;
    private readonly endpoint = 'https://videonexs-player.flicknexs.com/ping';
    private initialized = false;

    private constructor() { }

    static getInstance(): TelemetryManager {
        if (!TelemetryManager.instance) {
            TelemetryManager.instance = new TelemetryManager();
        }
        return TelemetryManager.instance;
    }

    async initialize(platform: Platform, version: string): Promise<void> {
        if (this.initialized) return;
        this.initialized = true;

        // const domain = typeof window !== 'undefined' ? window.location.hostname : 'node-server';

        // Temporary: disable filter to verify connectivity on ALL domains
        /*
        if (domain.includes('flicknexs.com')) {
            return;
        }
        */

        console.log(`[Telemetry] Initializing for ${platform} v${version}`);
        const data = this.collectData(platform, version);
        await this.sendPing(data);
    }

    private collectData(platform: Platform, version: string): TelemetryData {
        return {
            domain: typeof window !== 'undefined' ? window.location.hostname : 'node-server',
            platform,
            version,
            timestamp: Date.now(),
            status: 'init',
            userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown'
        };
    }

    private async sendPing(data: TelemetryData): Promise<void> {
        try {
            const body = JSON.stringify(data);

            console.log('[Telemetry] Sending ping...', data);

            // Use fetch for reliable delivery during init
            if (typeof fetch !== 'undefined') {
                const response = await fetch(this.endpoint, {
                    method: 'POST',
                    mode: 'cors',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body
                });

                if (response.ok) {
                    console.log('[Telemetry] Ping sent successfully');
                    return;
                } else {
                    console.warn(`[Telemetry] Ping failed with status: ${response.status}`);
                }
            }

            // Fallback to sendBeacon if fetch fails or is unavailable
            if (typeof navigator !== 'undefined' && navigator.sendBeacon) {
                const blob = new Blob([body], { type: 'application/json' });
                navigator.sendBeacon(this.endpoint, blob);
            }
        } catch (e) {
            console.error('[Telemetry] Error sending ping:', e);
        }
    }

    stop(): void {
        // No longer needed without heartbeat
    }
}
