'use client';

import { useEffect } from 'react';
import * as Sentry from '@sentry/nextjs';

export default function SentryInit() {
    useEffect(() => {
        const dsn = process.env.NEXT_PUBLIC_GLITCHTIP_DSN;

        console.log('[Sentry Debug] NEXT_PUBLIC_GLITCHTIP_DSN:', dsn ? dsn.substring(0, 40) + '...' : 'NOT SET');

        if (!dsn) {
            console.warn('[Sentry] Client disabled - no DSN configured');
            return;
        }

        try {
            // Check if already initialized
            const existingClient = Sentry.getClient();
            if (existingClient) {
                console.log('[Sentry] Already initialized, skipping');
                return;
            }

            Sentry.init({
                dsn,
                environment: process.env.NODE_ENV || 'development',
                sampleRate: 1.0,
                tracesSampleRate: 0.1,
                tunnel: '/api/glitchtip-tunnel',
                debug: true,
                beforeSend(event) {
                    console.log('[Sentry] Sending event:', event.event_id);
                    return event;
                },
            });

            console.log('[Sentry] ✅ Client initialized successfully');

            // Test that it works
            console.log('[Sentry] Client:', Sentry.getClient() ? 'OK' : 'FAILED');
        } catch (err) {
            console.error('[Sentry] Initialization error:', err);
        }
    }, []);

    return null;
}
