'use client';

/**
 * Phase 8.5 (2026-04-29) — Banner status territoire affiché en HUD bottom-left.
 *
 * Affiche :
 *   - HP territoire (barre coloree degradee selon %)
 *   - Nombre de défenseurs en place
 *   - Niveau de menace GIGN (normal / high / critical)
 *   - Cooldown respawn GIGN si actif (24h après KO total)
 *
 * Auto-refresh toutes les 15s. Listen WS events :
 *   - gign:territory-destroyed → flash rouge
 *   - gign:all-units-killed → flash vert
 *
 * Strings via t()/tFmt() — namespace 'territory'.
 */
import { useEffect, useState } from 'react';
import { api, type TerritoryStatus } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import { Shield, AlertTriangle, Clock } from 'lucide-react';

export function TerritoryStatusBanner() {
  const [status, setStatus] = useState<TerritoryStatus | null>(null);
  const [flash, setFlash] = useState<'destroyed' | 'killed' | null>(null);
  // Phase 8.5d (2026-04-29) — countdown arrivée GIGN (WS gign:incoming)
  const [gignArrivalAt, setGignArrivalAt] = useState<Date | null>(null);
  const [gignCountdown, setGignCountdown] = useState<number>(0);

  const load = async () => {
    try {
      const r = await api.territory.getStatus();
      setStatus(r);
    } catch {
      setStatus(null);
    }
  };

  useEffect(() => {
    load();
    const interval = setInterval(load, 15_000);

    const onDestroyed = () => {
      setFlash('destroyed');
      setTimeout(() => setFlash(null), 5000);
      setGignArrivalAt(null);
      load();
    };
    const onKilled = () => {
      setFlash('killed');
      setTimeout(() => setFlash(null), 5000);
      setGignArrivalAt(null);
      load();
    };
    // Phase 8.5d : GIGN spawn → countdown 60s avant attaque effective
    const onIncoming = (e: Event) => {
      const detail = (e as CustomEvent).detail as { delay_seconds: number; arrival_at: string };
      setGignArrivalAt(new Date(detail.arrival_at));
      load();
    };

    window.addEventListener('gign:territory-destroyed', onDestroyed);
    window.addEventListener('gign:all-units-killed', onKilled);
    window.addEventListener('gign:incoming', onIncoming);

    return () => {
      clearInterval(interval);
      window.removeEventListener('gign:territory-destroyed', onDestroyed);
      window.removeEventListener('gign:all-units-killed', onKilled);
      window.removeEventListener('gign:incoming', onIncoming);
    };
  }, []);

  // Phase 8.5d : countdown live mis à jour chaque seconde tant que GIGN en route
  useEffect(() => {
    if (!gignArrivalAt) return;
    const tick = () => {
      const remainingMs = gignArrivalAt.getTime() - Date.now();
      if (remainingMs <= 0) {
        setGignCountdown(0);
        setGignArrivalAt(null);
      } else {
        setGignCountdown(Math.ceil(remainingMs / 1000));
      }
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [gignArrivalAt]);

  if (!status) return null;

  // N'afficher la bannière que si HP < max OU GIGN threat OU cooldown actif
  // OU GIGN incoming (Phase 8.5d countdown). Sinon état normal, on cache.
  const showBanner = status.territory_hp < status.territory_hp_max
    || status.gign_threat_level !== 'normal'
    || status.gign_cooldown_remaining_h > 0
    || status.territory_destroyed
    || gignCountdown > 0;

  if (!showBanner && !flash) return null;

  const hpPct = status.territory_hp_max > 0
    ? Math.round((status.territory_hp / status.territory_hp_max) * 100)
    : 0;
  const hpColor = status.territory_destroyed ? '#ef4444'
    : hpPct < 25 ? '#ef4444'
    : hpPct < 50 ? '#f97316'
    : hpPct < 75 ? '#eab308'
    : '#22c55e';

  const threatColor = status.gign_threat_level === 'critical' ? '#ef4444'
    : status.gign_threat_level === 'high' ? '#f97316'
    : '#9ca3af';
  const threatLabel = status.gign_threat_level === 'critical'
    ? t('territory.gign_threat_critical')
    : status.gign_threat_level === 'high'
      ? t('territory.gign_threat_high')
      : t('territory.gign_threat_normal');

  return (
    <div
      className="fixed pointer-events-none"
      style={{
        bottom: 80,
        left: 16,
        zIndex: 1000,
        maxWidth: 280,
      }}
    >
      <div
        className="rounded-lg p-2.5 shadow-lg pointer-events-auto"
        style={{
          background: flash === 'destroyed' ? 'rgba(239,68,68,0.25)'
            : flash === 'killed' ? 'rgba(34,197,94,0.25)'
            : 'rgba(14,14,22,0.92)',
          border: `1px solid ${flash === 'destroyed' ? '#ef4444' : flash === 'killed' ? '#22c55e' : 'rgba(255,255,255,0.1)'}`,
          backdropFilter: 'blur(8px)',
          transition: 'background 0.3s, border-color 0.3s',
        }}>
        {/* Header territoire */}
        <div className="flex items-center gap-1.5 mb-1.5">
          <Shield size={11} style={{ color: hpColor }} />
          <span className="text-[10px] font-bold uppercase tracking-[.1em]" style={{ color: 'var(--text-primary)' }}>
            {t('territory.title')}
          </span>
          {status.territory_destroyed && (
            <span className="ml-auto text-[9px] font-bold" style={{ color: '#ef4444' }}>
              {t('territory.destroyed')}
            </span>
          )}
        </div>

        {/* HP barre */}
        {!status.territory_destroyed && (
          <div className="mb-2">
            <div className="flex items-center justify-between text-[9px] mb-0.5" style={{ color: 'var(--text-muted)' }}>
              <span>{t('territory.hp_label')}</span>
              <span style={{ color: hpColor, fontWeight: 'bold' }}>{status.territory_hp}/{status.territory_hp_max}</span>
            </div>
            <div className="h-1.5 rounded-full overflow-hidden" style={{ background: 'rgba(255,255,255,0.08)' }}>
              <div
                className="h-full transition-all"
                style={{
                  width: `${hpPct}%`,
                  background: hpColor,
                }}
              />
            </div>
          </div>
        )}

        {/* Phase 8.5d (2026-04-29) — Countdown arrivée GIGN (60s spawn → attaque).
            Pulsation rouge pour mettre la pression. */}
        {gignCountdown > 0 && (
          <div
            className="text-[10px] flex items-center justify-between gap-1 mb-1.5 px-1.5 py-1 rounded"
            style={{
              background: 'rgba(239,68,68,0.18)',
              border: '1px solid rgba(239,68,68,0.55)',
              color: '#fca5a5',
              animation: 'pulseline 1.2s infinite',
            }}
          >
            <span style={{ fontWeight: 'bold' }}>⚠ GIGN INCOMING</span>
            <span style={{ fontFamily: 'monospace', fontWeight: 'bold' }}>
              {String(Math.floor(gignCountdown / 60)).padStart(2, '0')}:{String(gignCountdown % 60).padStart(2, '0')}
            </span>
          </div>
        )}

        {/* Défenseurs */}
        <div className="text-[9px] flex items-center gap-1" style={{ color: 'var(--text-muted)' }}>
          <Shield size={9} />
          <span>{tFmt('territory.defenders_count', { count: status.defenders_count })}</span>
          {status.player_present && (
            <span style={{ color: '#86efac' }}> · {t('territory.player_present')}</span>
          )}
        </div>

        {/* Menace GIGN */}
        {(status.gign_threat_level !== 'normal' || status.gign_units_active > 0) && (
          <div className="text-[9px] flex items-center gap-1 mt-1" style={{ color: threatColor }}>
            <AlertTriangle size={9} />
            <span style={{ fontWeight: 'bold' }}>{threatLabel}</span>
            {status.gign_units_active > 0 && (
              <span style={{ color: 'var(--text-muted)' }}>
                · {tFmt('territory.gign_units_active', { count: status.gign_units_active })}
              </span>
            )}
          </div>
        )}

        {/* Cooldown respawn GIGN */}
        {status.gign_cooldown_remaining_h > 0 && (
          <div className="text-[9px] flex items-center gap-1 mt-1" style={{ color: '#86efac' }}>
            <Clock size={9} />
            <span>{tFmt('territory.gign_cooldown', { hours: status.gign_cooldown_remaining_h })}</span>
          </div>
        )}
      </div>
    </div>
  );
}
