'use client';

/**
 * Phase 8.8 (2026-04-29) — Lightbox read-only "Profil joueur" pour
 * visualiser un joueur tiers (pas le sien). Utilisé par :
 *   - Phase 8.12 reveal indic Hugues : ouvre le profil du voleur après
 *     consommation d'un appel à l'indic
 *   - Toute autre source future (notif link 'player:UUID', etc.)
 *
 * Affiche :
 *   - Identité : character_name, username, tier criminel/légal/politique
 *   - Status : chaleur, gang assigné (nom), cartel admin/membre
 *   - Stats publiques : territory_hp, position approximative
 *
 * Lecture via api.player.getProfile(playerId) — endpoint retourne déjà les
 * champs publiques safe (sans password_hash, oauth_id, etc.).
 *
 * i18n via t() namespace player_profile.*.
 */
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { X, User, Shield, Flame, Crown, Briefcase } from 'lucide-react';
import { useGameStore } from '@/stores/gameStore';
import { api } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';

interface PlayerProfile {
  id: string;
  username?: string;
  character_name?: string | null;
  criminal_tier?: number;
  legal_tier?: number;
  political_tier?: number;
  territory_hp?: number;
  territory_destroyed?: boolean;
  gang_id?: string | null;
  gang_name?: string | null;
  cartel_id?: string | null;
  cartel_name?: string | null;
  imprisoned_until?: string | null;
}

interface PlayerGauges {
  chaleur?: number;
  influence?: number;
  conscience?: number;
  respect?: number;
}

export function PlayerProfileLightbox() {
  const playerProfileId = useGameStore((s) => s.playerProfileId);
  const closePlayerProfile = useGameStore((s) => s.closePlayerProfile);

  const [profile, setProfile] = useState<PlayerProfile | null>(null);
  const [gauges, setGauges] = useState<PlayerGauges | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!playerProfileId) {
      setProfile(null);
      setGauges(null);
      setError(null);
      return;
    }
    setLoading(true);
    setError(null);

    Promise.all([
      api.player.getProfile(playerProfileId).catch(() => null),
      api.player.getGauges(playerProfileId).catch(() => null),
    ]).then(([prof, g]) => {
      setProfile(prof as PlayerProfile);
      setGauges(g as PlayerGauges);
    }).catch(() => setError(t('player_profile.load_error')))
      .finally(() => setLoading(false));
  }, [playerProfileId]);

  // ESC pour fermer
  useEffect(() => {
    if (!playerProfileId) return;
    const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') closePlayerProfile(); };
    window.addEventListener('keydown', handler);
    return () => window.removeEventListener('keydown', handler);
  }, [playerProfileId, closePlayerProfile]);

  if (!playerProfileId) return null;
  if (typeof document === 'undefined') return null;

  const displayName = profile?.character_name || profile?.username || t('player_profile.unknown');
  const isImprisoned = profile?.imprisoned_until && new Date(profile.imprisoned_until) > new Date();

  return createPortal(
    <div
      className="fixed inset-0 z-[1950] flex items-center justify-center p-4"
      style={{ background: 'rgba(0,0,0,0.72)' }}
      onClick={closePlayerProfile}
    >
      <div
        className="rounded-2xl overflow-hidden w-full"
        style={{
          maxWidth: 480,
          background: 'var(--bg-panel)',
          border: '1px solid var(--border-dark)',
          boxShadow: '0 20px 80px rgba(0,0,0,0.6)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div
          className="px-4 py-3 flex items-center justify-between"
          style={{
            borderBottom: '1px solid var(--border-dark)',
            background: 'linear-gradient(180deg, rgba(212,175,55,0.05), rgba(0,0,0,0))',
          }}
        >
          <div className="flex items-center gap-2">
            <User size={16} style={{ color: 'var(--color-gold-light)' }} />
            <p
              className="text-[13px] font-bold"
              style={{ color: 'var(--color-gold-light)', fontFamily: 'var(--font-subtitle)', letterSpacing: '.15em' }}
            >
              {displayName}
            </p>
            {isImprisoned && (
              <span
                className="text-[8px] font-bold uppercase tracking-[.1em] px-1.5 py-0.5 rounded"
                style={{ background: 'rgba(239,68,68,0.18)', color: '#fca5a5', border: '1px solid rgba(239,68,68,0.4)' }}
              >
                {t('player_profile.imprisoned_badge')}
              </span>
            )}
          </div>
          <button onClick={closePlayerProfile} className="p-1 rounded hover:opacity-70">
            <X size={16} style={{ color: 'var(--text-muted)' }} />
          </button>
        </div>

        {/* Body */}
        <div className="p-5 space-y-3" style={{ color: 'var(--text-secondary)', fontSize: 12, lineHeight: 1.6 }}>
          {loading && (
            <p className="text-[11px] italic" style={{ color: 'var(--text-muted)' }}>
              {t('player_profile.loading')}
            </p>
          )}

          {error && !loading && (
            <p className="text-[11px]" style={{ color: 'var(--color-red-light)' }}>{error}</p>
          )}

          {!loading && !error && profile && (
            <>
              {/* Tier criminel/légal/politique */}
              <div className="grid grid-cols-3 gap-2 text-[10px]">
                <Stat
                  icon={<Flame size={11} style={{ color: '#fca5a5' }} />}
                  label={t('player_profile.tier_criminal')}
                  value={String(profile.criminal_tier ?? 0)}
                />
                <Stat
                  icon={<Briefcase size={11} style={{ color: '#86efac' }} />}
                  label={t('player_profile.tier_legal')}
                  value={String(profile.legal_tier ?? 0)}
                />
                <Stat
                  icon={<Crown size={11} style={{ color: '#c4b5fd' }} />}
                  label={t('player_profile.tier_political')}
                  value={String(profile.political_tier ?? 0)}
                />
              </div>

              {/* Chaleur */}
              {gauges && typeof gauges.chaleur === 'number' && (
                <div
                  className="p-2 rounded flex items-center justify-between"
                  style={{ background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.25)' }}
                >
                  <span className="text-[10px] flex items-center gap-1.5" style={{ color: '#fca5a5' }}>
                    <Flame size={11} /> {t('player_profile.chaleur')}
                  </span>
                  <span className="text-[11px] font-bold" style={{ color: '#fca5a5' }}>
                    {gauges.chaleur}/100
                  </span>
                </div>
              )}

              {/* Territoire */}
              {typeof profile.territory_hp === 'number' && (
                <Stat
                  icon={<Shield size={11} />}
                  label={t('player_profile.territory_hp')}
                  value={profile.territory_destroyed
                    ? t('player_profile.territory_destroyed')
                    : tFmt('player_profile.territory_hp_value', { hp: profile.territory_hp, max: 1000 })}
                />
              )}

              {/* Gang + Cartel */}
              {profile.gang_name && (
                <Stat icon={<Briefcase size={11} />} label={t('player_profile.gang')} value={profile.gang_name} />
              )}
              {profile.cartel_name && (
                <Stat icon={<Crown size={11} />} label={t('player_profile.cartel')} value={profile.cartel_name} />
              )}
            </>
          )}
        </div>
      </div>
    </div>,
    document.body,
  );
}

function Stat({ icon, label, value }: { icon: React.ReactNode; label: string; value: string }) {
  return (
    <div
      className="p-2 rounded flex items-center gap-2"
      style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid var(--border-subtle)' }}
    >
      <span style={{ color: 'var(--text-muted)' }}>{icon}</span>
      <div className="flex-1 min-w-0">
        <p className="text-[9px] uppercase tracking-[.08em]" style={{ color: 'var(--text-muted)' }}>{label}</p>
        <p className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{value}</p>
      </div>
    </div>
  );
}
