'use client';

import { useEffect } from 'react';
import { useErrorStore } from '@/stores/errorStore';
import { AlertTriangle, X } from 'lucide-react';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'https://api.mafiaz.world';

/**
 * Global error lightbox — mounted in GameLayout.
 * When an API error occurs:
 * 1. Shows a user-friendly modal
 * 2. Automatically reports the error to the backend + admin email
 * 3. User can dismiss and continue playing
 */
export function ErrorLightbox() {
  const { currentError, showLightbox, dismiss, markReported } = useErrorStore();

  // Auto-report error to backend when it appears
  useEffect(() => {
    if (!currentError || currentError.reported) return;

    // Fire-and-forget — don't block UI
    fetch(`${API_BASE_URL}/api/error-report`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        error_code: currentError.status,
        error_message: currentError.message,
        page: currentError.page,
        timestamp: currentError.timestamp,
        user_agent: typeof navigator !== 'undefined' ? navigator.userAgent : '',
      }),
    }).catch(() => {
      // If the report itself fails, log to console — nothing else we can do
      console.error('[ErrorReport] Failed to send error report');
    });

    markReported();
  }, [currentError, markReported]);

  if (!showLightbox || !currentError) return null;

  return (
    <div className="fixed inset-0 z-[2000] flex items-center justify-center" style={{ background: 'rgba(0,0,0,0.6)' }}>
      <div
        className="relative w-full max-w-md mx-4 rounded-xl p-6 shadow-2xl"
        style={{
          background: 'linear-gradient(180deg, #1a1a2e 0%, #0f0f1a 100%)',
          border: '1px solid var(--border-dark)',
        }}
      >
        {/* Close button */}
        <button
          onClick={dismiss}
          className="absolute top-3 right-3 p-1 rounded-full hover:bg-white/10 transition-colors"
        >
          <X size={18} style={{ color: 'var(--text-muted)' }} />
        </button>

        {/* Icon */}
        <div className="flex justify-center mb-4">
          <div
            className="w-14 h-14 rounded-full flex items-center justify-center"
            style={{ background: 'rgba(239,68,68,0.15)' }}
          >
            <AlertTriangle size={28} style={{ color: '#ef4444' }} />
          </div>
        </div>

        {/* Title */}
        <h2 className="text-center font-impact text-lg mb-2" style={{ color: '#ef4444' }}>
          Une erreur est survenue
        </h2>

        {/* Message */}
        <p className="text-center text-sm mb-4" style={{ color: 'var(--text-secondary)' }}>
          {currentError.message || `Erreur ${currentError.status}`}
        </p>

        {/* Info box */}
        <div
          className="rounded-lg p-3 mb-5 text-center"
          style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)' }}
        >
          <p className="text-xs" style={{ color: 'var(--text-muted)' }}>
            Cette erreur a été automatiquement signalée à notre équipe technique pour être résolue.
            Merci de votre compréhension.
          </p>
        </div>

        {/* Dismiss button */}
        <button
          onClick={dismiss}
          className="w-full py-2.5 rounded-lg font-bold text-sm transition-colors"
          style={{
            background: 'var(--color-gold-dark)',
            color: 'var(--color-black)',
          }}
        >
          Continuer ma partie
        </button>

        {/* Error code (small, for support reference) */}
        <p className="text-center text-[10px] mt-3" style={{ color: 'var(--text-muted)' }}>
          Réf: {currentError.status}-{currentError.id.slice(0, 8)}
        </p>
      </div>
    </div>
  );
}
