'use client';

import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';

// ==========================================
// SVG Icons
// ==========================================
function IconFlag({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z"/><line x1="4" x2="4" y1="22" y2="15"/></svg>;
}
function IconShield({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>;
}
function IconList({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="8" x2="21" y1="6" y2="6"/><line x1="8" x2="21" y1="12" y2="12"/><line x1="8" x2="21" y1="18" y2="18"/><line x1="3" x2="3.01" y1="6" y2="6"/><line x1="3" x2="3.01" y1="12" y2="12"/><line x1="3" x2="3.01" y1="18" y2="18"/></svg>;
}
function IconCheck({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>;
}
function IconX({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18"/><path d="M6 6l12 12"/></svg>;
}
function IconTrash({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>;
}
function IconBan({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="m4.9 4.9 14.2 14.2"/></svg>;
}
function IconClock({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>;
}
function IconUser({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
}
function IconEdit({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/></svg>;
}
function IconFilter({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>;
}
function IconMessage({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>;
}
function IconMegaphone({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m3 11 18-5v12L3 13v-2z"/><path d="M11.6 16.8a3 3 0 1 1-5.8-1.6"/></svg>;
}
function IconVolumeMute({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"/><line x1="23" x2="17" y1="9" y2="15"/><line x1="17" x2="23" y1="9" y2="15"/></svg>;
}
function IconLoader({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="animate-spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>;
}

// ==========================================
// Types
// ==========================================

type ReportStatus = 'en_attente' | 'traite' | 'rejete';
type ReportType = 'message' | 'joueur' | 'annonce';
type SanctionType = 'ban' | 'suspension' | 'mute';

interface Report {
  id: string;
  type: ReportType;
  reporter: string;
  reportedUser: string;
  reportedContent: string;
  reason: string;
  date: string;
  status: ReportStatus;
}

interface Sanction {
  id: string;
  player: string;
  type: SanctionType;
  reason: string;
  duration: string;
  imposedBy: string;
  date: string;
  remainingTime: string;
  active: boolean;
}

interface ModerationLog {
  id: string;
  date: string;
  moderator: string;
  action: string;
  targetPlayer: string;
  details: string;
}

// ==========================================
// Helpers
// ==========================================

const STATUS_CONFIG: Record<ReportStatus, { label: string; color: string; bg: string }> = {
  en_attente: { label: 'En attente', color: '#f59e0b', bg: 'rgba(245,158,11,0.15)' },
  traite: { label: 'Traité', color: '#22c55e', bg: 'rgba(34,197,94,0.15)' },
  rejete: { label: 'Rejeté', color: '#ef4444', bg: 'rgba(239,68,68,0.15)' },
};

const REPORT_TYPE_CONFIG: Record<ReportType, { label: string; icon: React.ReactNode }> = {
  message: { label: 'Message', icon: <IconMessage size={12} /> },
  joueur: { label: 'Joueur', icon: <IconUser size={12} /> },
  annonce: { label: 'Annonce', icon: <IconMegaphone size={12} /> },
};

const SANCTION_TYPE_CONFIG: Record<SanctionType, { label: string; color: string; bg: string; icon: React.ReactNode }> = {
  ban: { label: 'Bannissement', color: '#ef4444', bg: 'rgba(239,68,68,0.15)', icon: <IconBan size={12} /> },
  suspension: { label: 'Suspension', color: '#f59e0b', bg: 'rgba(245,158,11,0.15)', icon: <IconClock size={12} /> },
  mute: { label: 'Mute', color: '#a78bfa', bg: 'rgba(167,139,250,0.15)', icon: <IconVolumeMute size={12} /> },
};

// ==========================================
// Component
// ==========================================
export default function AdminModeration() {
  const [activeTab, setActiveTab] = useState<'signalements' | 'sanctions' | 'journal'>('signalements');
  const [reports, setReports] = useState<Report[]>([]);
  const [sanctions, setSanctions] = useState<Sanction[]>([]);
  const [logs, setLogs] = useState<ModerationLog[]>([]);

  // Loading states
  const [loadingReports, setLoadingReports] = useState(true);
  const [loadingSanctions, setLoadingSanctions] = useState(true);
  const [loadingLogs, setLoadingLogs] = useState(true);

  // Feedback
  const [error, setError] = useState<string | null>(null);
  const [actionFeedback, setActionFeedback] = useState<string | null>(null);

  // Filters for journal tab
  const [logFilterAction, setLogFilterAction] = useState('');
  const [logFilterModerator, setLogFilterModerator] = useState('');
  const [logFilterDateFrom, setLogFilterDateFrom] = useState('');
  const [logFilterDateTo, setLogFilterDateTo] = useState('');

  // Sanction modal (replaces prompt())
  const [showDurationModal, setShowDurationModal] = useState(false);
  const [durationModalId, setDurationModalId] = useState<string | null>(null);
  const [durationInput, setDurationInput] = useState('');
  const [savingDuration, setSavingDuration] = useState(false);

  // Sanction modal (for sanctioning a report)
  const [showSanctionModal, setShowSanctionModal] = useState(false);
  const [sanctionReportId, setSanctionReportId] = useState<string | null>(null);
  const [sanctionType, setSanctionType] = useState<SanctionType>('suspension');
  const [sanctionReason, setSanctionReason] = useState('');
  const [sanctionDuration, setSanctionDuration] = useState('');
  const [savingSanction, setSavingSanction] = useState(false);

  // ---- Feedback helper ----
  const showFeedback = (msg: string) => {
    setActionFeedback(msg);
    setTimeout(() => setActionFeedback(null), 3000);
  };

  // ---- Data fetching ----
  const fetchReports = useCallback(async () => {
    setLoadingReports(true);
    try {
      const data = await api.admin.moderation.getReports() as Report[] | { reports?: Report[]; items?: Report[] };
      if (Array.isArray(data)) {
        setReports(data);
      } else if (data.reports && Array.isArray(data.reports)) {
        setReports(data.reports);
      } else if (data.items && Array.isArray(data.items)) {
        setReports(data.items);
      } else {
        setReports([]);
      }
    } catch {
      setReports([]);
    } finally {
      setLoadingReports(false);
    }
  }, []);

  const fetchSanctions = useCallback(async () => {
    setLoadingSanctions(true);
    try {
      const data = await api.admin.moderation.getSanctions() as Sanction[] | { sanctions?: Sanction[]; items?: Sanction[] };
      if (Array.isArray(data)) {
        setSanctions(data);
      } else if (data.sanctions && Array.isArray(data.sanctions)) {
        setSanctions(data.sanctions);
      } else if (data.items && Array.isArray(data.items)) {
        setSanctions(data.items);
      } else {
        setSanctions([]);
      }
    } catch {
      setSanctions([]);
    } finally {
      setLoadingSanctions(false);
    }
  }, []);

  const fetchLogs = useCallback(async (params?: Record<string, string | undefined>) => {
    setLoadingLogs(true);
    try {
      const data = await api.admin.moderation.getLogs(params) as ModerationLog[] | { logs?: ModerationLog[]; items?: ModerationLog[] };
      if (Array.isArray(data)) {
        setLogs(data);
      } else if (data.logs && Array.isArray(data.logs)) {
        setLogs(data.logs);
      } else if (data.items && Array.isArray(data.items)) {
        setLogs(data.items);
      } else {
        setLogs([]);
      }
    } catch {
      setLogs([]);
    } finally {
      setLoadingLogs(false);
    }
  }, []);

  useEffect(() => {
    fetchReports();
    fetchSanctions();
    fetchLogs();
  }, [fetchReports, fetchSanctions, fetchLogs]);

  // Re-fetch logs whenever filters change
  useEffect(() => {
    const params: Record<string, string | undefined> = {};
    if (logFilterAction) params.action = logFilterAction;
    if (logFilterModerator) params.moderator = logFilterModerator;
    if (logFilterDateFrom) params.dateFrom = logFilterDateFrom;
    if (logFilterDateTo) params.dateTo = logFilterDateTo;
    fetchLogs(params);
  }, [logFilterAction, logFilterModerator, logFilterDateFrom, logFilterDateTo, fetchLogs]);

  const pendingCount = reports.filter(r => r.status === 'en_attente').length;
  const activeSanctionsCount = sanctions.filter(s => s.active).length;

  const tabs = [
    { id: 'signalements' as const, label: 'Signalements', count: pendingCount, icon: <IconFlag size={14} /> },
    { id: 'sanctions' as const, label: 'Sanctions', count: activeSanctionsCount, icon: <IconShield size={14} /> },
    { id: 'journal' as const, label: 'Journal de modération', icon: <IconList size={14} /> },
  ];

  // ---- Report Actions ----
  const handleDismissReport = async (id: string) => {
    try {
      await api.admin.moderation.dismissReport(id);
      setReports(prev => prev.map(r => r.id === id ? { ...r, status: 'rejete' as ReportStatus } : r));
      showFeedback('Signalement rejeté');
    } catch (err: unknown) {
      setError(`Erreur lors du rejet : ${err instanceof Error ? err.message : 'Erreur inconnue'}`);
    }
  };

  const openSanctionModal = (id: string) => {
    setSanctionReportId(id);
    setSanctionType('suspension');
    setSanctionReason('');
    setSanctionDuration('');
    setShowSanctionModal(true);
  };

  const handleConfirmSanction = async () => {
    if (!sanctionReportId || !sanctionReason.trim() || !sanctionDuration.trim()) return;
    setSavingSanction(true);
    try {
      await api.admin.moderation.sanctionReport(sanctionReportId, {
        type: sanctionType,
        reason: sanctionReason,
        duration: sanctionDuration,
      });
      setReports(prev => prev.map(r => r.id === sanctionReportId ? { ...r, status: 'traite' as ReportStatus } : r));
      setShowSanctionModal(false);
      showFeedback('Sanction appliquée avec succès');
    } catch (err: unknown) {
      setError(`Erreur lors de la sanction : ${err instanceof Error ? err.message : 'Erreur inconnue'}`);
    } finally {
      setSavingSanction(false);
    }
  };

  const handleDeleteContent = async (id: string) => {
    try {
      await api.admin.moderation.deleteReportContent(id);
      setReports(prev => prev.map(r => r.id === id ? { ...r, status: 'traite' as ReportStatus } : r));
      showFeedback('Contenu supprimé');
    } catch (err: unknown) {
      setError(`Erreur lors de la suppression : ${err instanceof Error ? err.message : 'Erreur inconnue'}`);
    }
  };

  // ---- Sanction Actions ----
  const handleLiftSanction = async (id: string) => {
    try {
      await api.admin.moderation.liftSanction(id);
      setSanctions(prev => prev.map(s => s.id === id ? { ...s, active: false, remainingTime: 'Levée' } : s));
      showFeedback('Sanction levée');
    } catch (err: unknown) {
      setError(`Erreur lors de la levée de sanction : ${err instanceof Error ? err.message : 'Erreur inconnue'}`);
    }
  };

  const openDurationModal = (id: string) => {
    const sanction = sanctions.find(s => s.id === id);
    setDurationModalId(id);
    setDurationInput(sanction?.duration || '');
    setShowDurationModal(true);
  };

  const handleConfirmDuration = async () => {
    if (!durationModalId || !durationInput.trim()) return;
    setSavingDuration(true);
    try {
      await api.admin.moderation.updateSanctionDuration(durationModalId, { duration: durationInput });
      setSanctions(prev => prev.map(s => s.id === durationModalId ? { ...s, duration: durationInput, remainingTime: durationInput } : s));
      setShowDurationModal(false);
      showFeedback('Durée de la sanction modifiée');
    } catch (err: unknown) {
      setError(`Erreur lors de la modification : ${err instanceof Error ? err.message : 'Erreur inconnue'}`);
    } finally {
      setSavingDuration(false);
    }
  };

  // ---- Journal unique values (derived from current logs for filter dropdowns) ----
  const uniqueActions = [...new Set(logs.map(l => l.action))];
  const uniqueModerators = [...new Set(logs.map(l => l.moderator))];

  // ---- Styles ----
  const cardStyle: React.CSSProperties = {
    background: 'var(--bg-card)',
    border: '1px solid var(--border-dark)',
    borderRadius: '12px',
  };

  const btnPrimary: React.CSSProperties = {
    background: 'linear-gradient(135deg, var(--color-red) 0%, var(--color-red-dark) 100%)',
    color: 'white',
    border: 'none',
    borderRadius: '8px',
    padding: '6px 12px',
    fontSize: '12px',
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    gap: '4px',
    fontWeight: 600,
  };

  const btnOutline: React.CSSProperties = {
    background: 'transparent',
    color: 'var(--text-secondary)',
    border: '1px solid var(--border-dark)',
    borderRadius: '8px',
    padding: '6px 12px',
    fontSize: '12px',
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    gap: '4px',
  };

  const btnGold: React.CSSProperties = {
    background: 'transparent',
    color: 'var(--color-gold)',
    border: '1px solid var(--color-gold)',
    borderRadius: '8px',
    padding: '6px 12px',
    fontSize: '12px',
    cursor: 'pointer',
    display: 'inline-flex',
    alignItems: 'center',
    gap: '4px',
    fontWeight: 600,
  };

  return (
    <div className="space-y-4">
      {/* Title */}
      <h2
        className="text-xl"
        style={{ fontFamily: 'var(--font-impact, Impact, sans-serif)', color: 'var(--text-primary)', letterSpacing: '0.5px' }}
      >
        Panneau de Modération
      </h2>

      {/* Error banner */}
      {error && (
        <div
          className="p-3 rounded-lg text-sm flex items-center justify-between"
          style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#f87171' }}
        >
          <span>{error}</span>
          <button onClick={() => setError(null)} className="ml-2 hover:opacity-70"><IconX size={14} /></button>
        </div>
      )}

      {/* Action feedback */}
      {actionFeedback && (
        <div
          className="p-3 rounded-lg text-sm"
          style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.3)', color: '#22c55e' }}
        >
          {actionFeedback}
        </div>
      )}

      {/* Tabs */}
      <div className="flex gap-1 border-b" style={{ borderColor: 'var(--border-dark)' }}>
        {tabs.map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className="flex items-center gap-2 px-4 py-3 text-sm transition-colors relative"
            style={{ color: activeTab === tab.id ? 'var(--color-gold)' : 'var(--text-muted)', background: 'transparent', border: 'none', cursor: 'pointer' }}
          >
            {tab.icon}
            {tab.label}
            {tab.count !== undefined && tab.count > 0 && (
              <span
                className="px-1.5 py-0.5 rounded-full text-[9px] font-bold"
                style={{ background: 'var(--color-red)', color: 'white' }}
              >
                {tab.count}
              </span>
            )}
            {activeTab === tab.id && (
              <div className="absolute bottom-0 left-0 right-0 h-[2px]" style={{ background: 'var(--color-gold)' }} />
            )}
          </button>
        ))}
      </div>

      {/* ============================================ */}
      {/* SIGNALEMENTS TAB                             */}
      {/* ============================================ */}
      {activeTab === 'signalements' && (
        <div className="space-y-3">
          {loadingReports ? (
            <div className="p-8 rounded-xl text-center" style={cardStyle}>
              <IconLoader size={20} color="var(--color-gold)" />
              <p className="text-sm mt-2" style={{ color: 'var(--text-muted)' }}>Chargement des signalements...</p>
            </div>
          ) : reports.length === 0 ? (
            <div className="p-8 rounded-xl text-center" style={cardStyle}>
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Aucun signalement à traiter.</p>
            </div>
          ) : (
            reports.map((report) => {
              const statusCfg = STATUS_CONFIG[report.status];
              const typeCfg = REPORT_TYPE_CONFIG[report.type];
              return (
                <div key={report.id} className="p-4 rounded-xl" style={cardStyle}>
                  {/* Header row */}
                  <div className="flex items-center justify-between mb-3">
                    <div className="flex items-center gap-3">
                      {/* Type badge */}
                      <span
                        className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-semibold"
                        style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--color-gold)', border: '1px solid var(--border-dark)' }}
                      >
                        {typeCfg.icon}
                        {typeCfg.label}
                      </span>
                      {/* Status badge */}
                      <span
                        className="inline-flex items-center gap-1 px-2 py-1 rounded-md text-[11px] font-semibold"
                        style={{ background: statusCfg.bg, color: statusCfg.color }}
                      >
                        {statusCfg.label}
                      </span>
                    </div>
                    <span className="inline-flex items-center gap-1 text-[11px]" style={{ color: 'var(--text-muted)' }}>
                      <IconClock size={11} /> {report.date}
                    </span>
                  </div>

                  {/* Content */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-3">
                    <div>
                      <p className="text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Signalé par</p>
                      <p className="text-sm font-medium" style={{ color: 'var(--color-gold)' }}>{report.reporter}</p>
                    </div>
                    <div>
                      <p className="text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Utilisateur signalé</p>
                      <p className="text-sm font-medium" style={{ color: 'var(--color-red-light, #f87171)' }}>{report.reportedUser}</p>
                    </div>
                  </div>

                  <div className="mb-3">
                    <p className="text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Contenu signalé</p>
                    <p className="text-sm" style={{ color: 'var(--text-secondary)' }}>{report.reportedContent}</p>
                  </div>

                  <div className="mb-3 p-3 rounded-lg" style={{ background: 'var(--bg-secondary)', border: '1px solid var(--border-dark)' }}>
                    <p className="text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Raison du signalement</p>
                    <p className="text-sm" style={{ color: 'var(--text-primary)' }}>{report.reason}</p>
                  </div>

                  {/* Actions — only for pending reports */}
                  {report.status === 'en_attente' && (
                    <div className="flex items-center gap-2 pt-2" style={{ borderTop: '1px solid var(--border-dark)' }}>
                      <button style={btnOutline} onClick={() => handleDismissReport(report.id)}>
                        <IconCheck size={12} color="#22c55e" />
                        Approuver (rejeter)
                      </button>
                      <button style={btnPrimary} onClick={() => openSanctionModal(report.id)}>
                        <IconBan size={12} />
                        Sanctionner
                      </button>
                      <button style={{ ...btnPrimary, background: 'linear-gradient(135deg, #dc2626 0%, #991b1b 100%)' }} onClick={() => handleDeleteContent(report.id)}>
                        <IconTrash size={12} />
                        Supprimer contenu
                      </button>
                    </div>
                  )}
                </div>
              );
            })
          )}
        </div>
      )}

      {/* ============================================ */}
      {/* SANCTIONS TAB                                */}
      {/* ============================================ */}
      {activeTab === 'sanctions' && (
        <div className="space-y-3">
          {loadingSanctions ? (
            <div className="p-8 rounded-xl text-center" style={cardStyle}>
              <IconLoader size={20} color="var(--color-gold)" />
              <p className="text-sm mt-2" style={{ color: 'var(--text-muted)' }}>Chargement des sanctions...</p>
            </div>
          ) : sanctions.length === 0 ? (
            <div className="p-8 rounded-xl text-center" style={cardStyle}>
              <p className="text-sm" style={{ color: 'var(--text-muted)' }}>Aucune sanction active.</p>
            </div>
          ) : (
            <>
              {/* Summary bar */}
              <div className="flex gap-4 mb-2 flex-wrap">
                <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs" style={{ background: 'rgba(239,68,68,0.1)', color: '#ef4444' }}>
                  <IconBan size={12} />
                  {sanctions.filter(s => s.type === 'ban' && s.active).length} ban(s) actif(s)
                </div>
                <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs" style={{ background: 'rgba(245,158,11,0.1)', color: '#f59e0b' }}>
                  <IconClock size={12} />
                  {sanctions.filter(s => s.type === 'suspension' && s.active).length} suspension(s) active(s)
                </div>
                <div className="flex items-center gap-2 px-3 py-2 rounded-lg text-xs" style={{ background: 'rgba(167,139,250,0.1)', color: '#a78bfa' }}>
                  <IconVolumeMute size={12} />
                  {sanctions.filter(s => s.type === 'mute' && s.active).length} mute(s) actif(s)
                </div>
              </div>

              {/* Sanctions table */}
              <div className="rounded-xl overflow-hidden" style={cardStyle}>
                <div className="overflow-x-auto">
                  <table className="w-full text-sm" style={{ borderCollapse: 'collapse' }}>
                    <thead>
                      <tr style={{ background: 'var(--bg-secondary)', borderBottom: '1px solid var(--border-dark)' }}>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Joueur</th>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Type</th>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Raison</th>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Durée</th>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Imposée par</th>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Date</th>
                        <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Temps restant</th>
                        <th className="text-right px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      {sanctions.map((sanction) => {
                        const typeCfg = SANCTION_TYPE_CONFIG[sanction.type];
                        return (
                          <tr
                            key={sanction.id}
                            style={{
                              borderBottom: '1px solid var(--border-dark)',
                              opacity: sanction.active ? 1 : 0.5,
                            }}
                          >
                            <td className="px-4 py-3">
                              <span className="font-medium" style={{ color: 'var(--text-primary)' }}>{sanction.player}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span
                                className="inline-flex items-center gap-1 px-2 py-0.5 rounded-md text-[11px] font-semibold"
                                style={{ background: typeCfg.bg, color: typeCfg.color }}
                              >
                                {typeCfg.icon}
                                {typeCfg.label}
                              </span>
                            </td>
                            <td className="px-4 py-3 max-w-[200px]">
                              <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>{sanction.reason}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs" style={{ color: 'var(--text-primary)' }}>{sanction.duration}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs" style={{ color: 'var(--color-gold)' }}>{sanction.imposedBy}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs" style={{ color: 'var(--text-muted)' }}>{sanction.date}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span
                                className="text-xs font-semibold"
                                style={{
                                  color: sanction.active
                                    ? (sanction.type === 'ban' ? '#ef4444' : '#f59e0b')
                                    : '#22c55e',
                                }}
                              >
                                {sanction.remainingTime}
                              </span>
                            </td>
                            <td className="px-4 py-3 text-right">
                              {sanction.active && (
                                <div className="flex items-center justify-end gap-2">
                                  <button style={btnGold} onClick={() => openDurationModal(sanction.id)}>
                                    <IconEdit size={11} />
                                    Modifier durée
                                  </button>
                                  <button style={btnOutline} onClick={() => handleLiftSanction(sanction.id)}>
                                    <IconX size={11} color="#22c55e" />
                                    Lever la sanction
                                  </button>
                                </div>
                              )}
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              </div>
            </>
          )}
        </div>
      )}

      {/* ============================================ */}
      {/* JOURNAL DE MODÉRATION TAB                    */}
      {/* ============================================ */}
      {activeTab === 'journal' && (
        <div className="space-y-3">
          {/* Filters */}
          <div className="p-4 rounded-xl" style={cardStyle}>
            <div className="flex items-center gap-2 mb-3">
              <IconFilter size={14} color="var(--color-gold)" />
              <span className="text-sm font-semibold" style={{ color: 'var(--text-primary)' }}>Filtres</span>
            </div>
            <div className="grid grid-cols-1 md:grid-cols-4 gap-3">
              {/* Action type filter */}
              <div>
                <label className="block text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Type d&apos;action</label>
                <select
                  value={logFilterAction}
                  onChange={(e) => setLogFilterAction(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--bg-secondary)',
                    border: '1px solid var(--border-dark)',
                    color: 'var(--text-primary)',
                    outline: 'none',
                  }}
                >
                  <option value="">Toutes les actions</option>
                  {uniqueActions.map(action => (
                    <option key={action} value={action}>{action}</option>
                  ))}
                </select>
              </div>

              {/* Moderator filter */}
              <div>
                <label className="block text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Modérateur</label>
                <select
                  value={logFilterModerator}
                  onChange={(e) => setLogFilterModerator(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--bg-secondary)',
                    border: '1px solid var(--border-dark)',
                    color: 'var(--text-primary)',
                    outline: 'none',
                  }}
                >
                  <option value="">Tous les modérateurs</option>
                  {uniqueModerators.map(mod => (
                    <option key={mod} value={mod}>{mod}</option>
                  ))}
                </select>
              </div>

              {/* Date from */}
              <div>
                <label className="block text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Date début</label>
                <input
                  type="date"
                  value={logFilterDateFrom}
                  onChange={(e) => setLogFilterDateFrom(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--bg-secondary)',
                    border: '1px solid var(--border-dark)',
                    color: 'var(--text-primary)',
                    outline: 'none',
                  }}
                />
              </div>

              {/* Date to */}
              <div>
                <label className="block text-[11px] mb-1" style={{ color: 'var(--text-muted)' }}>Date fin</label>
                <input
                  type="date"
                  value={logFilterDateTo}
                  onChange={(e) => setLogFilterDateTo(e.target.value)}
                  className="w-full px-3 py-2 rounded-lg text-sm"
                  style={{
                    background: 'var(--bg-secondary)',
                    border: '1px solid var(--border-dark)',
                    color: 'var(--text-primary)',
                    outline: 'none',
                  }}
                />
              </div>
            </div>
          </div>

          {/* Log entries table */}
          <div className="rounded-xl overflow-hidden" style={cardStyle}>
            {loadingLogs ? (
              <div className="p-8 text-center">
                <IconLoader size={20} color="var(--color-gold)" />
                <p className="text-sm mt-2" style={{ color: 'var(--text-muted)' }}>Chargement du journal...</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full text-sm" style={{ borderCollapse: 'collapse' }}>
                  <thead>
                    <tr style={{ background: 'var(--bg-secondary)', borderBottom: '1px solid var(--border-dark)' }}>
                      <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Date</th>
                      <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Modérateur</th>
                      <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Action</th>
                      <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Joueur ciblé</th>
                      <th className="text-left px-4 py-3 text-[11px] font-semibold uppercase" style={{ color: 'var(--text-muted)' }}>Détails</th>
                    </tr>
                  </thead>
                  <tbody>
                    {logs.length === 0 ? (
                      <tr>
                        <td colSpan={5} className="px-4 py-8 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
                          Aucune entrée ne correspond aux filtres sélectionnés.
                        </td>
                      </tr>
                    ) : (
                      logs.map((log) => {
                        const actionColor = log.action.includes('Ban') || log.action.includes('Contenu supprimé')
                          ? '#ef4444'
                          : log.action.includes('Suspension') || log.action.includes('Mute')
                            ? '#f59e0b'
                            : log.action.includes('rejeté')
                              ? 'var(--text-muted)'
                              : log.action.includes('Avertissement')
                                ? '#a78bfa'
                                : 'var(--text-secondary)';

                        return (
                          <tr
                            key={log.id}
                            style={{ borderBottom: '1px solid var(--border-dark)' }}
                          >
                            <td className="px-4 py-3 whitespace-nowrap">
                              <span className="text-xs" style={{ color: 'var(--text-muted)' }}>{log.date}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs font-medium" style={{ color: 'var(--color-gold)' }}>{log.moderator}</span>
                            </td>
                            <td className="px-4 py-3">
                              <span
                                className="inline-flex items-center px-2 py-0.5 rounded-md text-[11px] font-semibold"
                                style={{ background: `${actionColor}20`, color: actionColor }}
                              >
                                {log.action}
                              </span>
                            </td>
                            <td className="px-4 py-3">
                              <span className="text-xs font-medium" style={{ color: 'var(--text-primary)' }}>{log.targetPlayer}</span>
                            </td>
                            <td className="px-4 py-3 max-w-[300px]">
                              <span className="text-xs" style={{ color: 'var(--text-secondary)' }}>{log.details}</span>
                            </td>
                          </tr>
                        );
                      })
                    )}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {/* ============================================ */}
      {/* MODAL — Modifier la durée d'une sanction     */}
      {/* ============================================ */}
      {showDurationModal && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          style={{ background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(4px)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowDurationModal(false); }}
        >
          <div
            className="w-full max-w-sm rounded-xl overflow-hidden"
            style={{ background: 'var(--bg-secondary)', border: '1px solid var(--border-dark)' }}
          >
            <div
              className="flex items-center justify-between px-5 py-4"
              style={{ borderBottom: '1px solid var(--border-dark)' }}
            >
              <h2 className="text-base font-semibold" style={{ color: 'var(--color-gold)' }}>
                Modifier la durée
              </h2>
              <button onClick={() => setShowDurationModal(false)} className="p-1 rounded hover:bg-white/5 transition-colors">
                <IconX size={16} color="var(--text-muted)" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div>
                <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                  Nouvelle durée
                </label>
                <input
                  type="text"
                  value={durationInput}
                  onChange={(e) => setDurationInput(e.target.value)}
                  placeholder="ex : 3 jours, 24 heures, Permanent"
                  className="w-full p-2.5 rounded-lg text-sm"
                  style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)', outline: 'none' }}
                />
              </div>
            </div>
            <div className="flex gap-3 justify-end px-5 py-4" style={{ borderTop: '1px solid var(--border-dark)' }}>
              <button
                onClick={() => setShowDurationModal(false)}
                className="px-4 py-2 rounded-lg text-sm"
                style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--text-secondary)' }}
              >
                Annuler
              </button>
              <button
                onClick={handleConfirmDuration}
                disabled={savingDuration || !durationInput.trim()}
                className="px-5 py-2 rounded-lg text-sm font-bold transition-all hover:scale-105 disabled:opacity-50"
                style={{ background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))', color: 'white', boxShadow: '0 0 15px rgba(196,30,30,0.3)' }}
              >
                {savingDuration ? <IconLoader size={14} /> : 'Confirmer'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ============================================ */}
      {/* MODAL — Sanctionner un signalement           */}
      {/* ============================================ */}
      {showSanctionModal && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center p-4"
          style={{ background: 'rgba(0,0,0,0.85)', backdropFilter: 'blur(4px)' }}
          onClick={(e) => { if (e.target === e.currentTarget) setShowSanctionModal(false); }}
        >
          <div
            className="w-full max-w-md rounded-xl overflow-hidden"
            style={{ background: 'var(--bg-secondary)', border: '1px solid var(--border-dark)' }}
          >
            <div
              className="flex items-center justify-between px-5 py-4"
              style={{ borderBottom: '1px solid var(--border-dark)' }}
            >
              <h2 className="text-base font-semibold" style={{ color: 'var(--color-gold)' }}>
                Appliquer une sanction
              </h2>
              <button onClick={() => setShowSanctionModal(false)} className="p-1 rounded hover:bg-white/5 transition-colors">
                <IconX size={16} color="var(--text-muted)" />
              </button>
            </div>
            <div className="p-5 space-y-4">
              <div>
                <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                  Type de sanction
                </label>
                <select
                  value={sanctionType}
                  onChange={(e) => setSanctionType(e.target.value as SanctionType)}
                  className="w-full p-2.5 rounded-lg text-sm"
                  style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)', outline: 'none' }}
                >
                  <option value="suspension">Suspension</option>
                  <option value="ban">Bannissement</option>
                  <option value="mute">Mute</option>
                </select>
              </div>
              <div>
                <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                  Raison
                </label>
                <textarea
                  value={sanctionReason}
                  onChange={(e) => setSanctionReason(e.target.value)}
                  placeholder="Raison de la sanction..."
                  rows={3}
                  className="w-full p-2.5 rounded-lg text-sm resize-none"
                  style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)', outline: 'none' }}
                />
              </div>
              <div>
                <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                  Durée
                </label>
                <input
                  type="text"
                  value={sanctionDuration}
                  onChange={(e) => setSanctionDuration(e.target.value)}
                  placeholder="ex : 7 jours, 48 heures, Permanent"
                  className="w-full p-2.5 rounded-lg text-sm"
                  style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)', outline: 'none' }}
                />
              </div>
            </div>
            <div className="flex gap-3 justify-end px-5 py-4" style={{ borderTop: '1px solid var(--border-dark)' }}>
              <button
                onClick={() => setShowSanctionModal(false)}
                className="px-4 py-2 rounded-lg text-sm"
                style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--text-secondary)' }}
              >
                Annuler
              </button>
              <button
                onClick={handleConfirmSanction}
                disabled={savingSanction || !sanctionReason.trim() || !sanctionDuration.trim()}
                className="px-5 py-2 rounded-lg text-sm font-bold transition-all hover:scale-105 disabled:opacity-50"
                style={{ background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))', color: 'white', boxShadow: '0 0 15px rgba(196,30,30,0.3)' }}
              >
                {savingSanction ? <IconLoader size={14} /> : 'Appliquer la sanction'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
