'use client';

import { useState, useEffect, useCallback } from 'react';
import { NavBar } from '@/components/layout/NavBar';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/useAuth';

// ==========================================
// SVG Icon Components
// ==========================================

function IconChat({ size = 18, 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="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
    </svg>
  );
}

function IconUsers({ size = 18, 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 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
    </svg>
  );
}

function IconMap({ size = 18, 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="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
    </svg>
  );
}

function IconTarget({ size = 18, 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">
      <circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>
    </svg>
  );
}

function IconBuilding({ size = 18, 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">
      <rect x="4" y="2" width="16" height="20" rx="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01"/><path d="M16 6h.01"/><path d="M12 6h.01"/><path d="M12 10h.01"/><path d="M12 14h.01"/><path d="M16 10h.01"/><path d="M16 14h.01"/><path d="M8 10h.01"/><path d="M8 14h.01"/>
    </svg>
  );
}

function IconLeaf({ size = 18, 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="M11 20A7 7 0 0 1 9.8 6.9C15.5 4.9 17 3.5 19 2c1 2 2 4.5 2 8 0 5.5-4.78 10-10 10z"/><path d="M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12"/>
    </svg>
  );
}

function IconHandshake({ size = 18, 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="M11 17a1 1 0 0 1-1-1v0a1 1 0 0 1 1-1h0a1 1 0 0 1 1 1v0a1 1 0 0 1-1 1z"/><path d="M14 14a1 1 0 0 1-1-1v0a1 1 0 0 1 1-1h0a1 1 0 0 1 1 1v0a1 1 0 0 1-1 1z"/><path d="M17 11a1 1 0 0 1-1-1v0a1 1 0 0 1 1-1h0a1 1 0 0 1 1 1v0a1 1 0 0 1-1 1z"/><path d="m2 11 4.5-4.5"/><path d="m22 11-4.5-4.5"/><path d="m5.5 12.5 1-1 2 2 3-3 2 2 3-3 1 1"/><path d="M2 11v5l4-2"/><path d="M22 11v5l-4-2"/>
    </svg>
  );
}

function IconBug({ size = 18, 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="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/>
    </svg>
  );
}

function IconCalendar({ size = 18, 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">
      <rect width="18" height="18" x="3" y="4" rx="2"/><path d="M16 2v4"/><path d="M8 2v4"/><path d="M3 10h18"/><path d="m9 16 2 2 4-4"/>
    </svg>
  );
}

function IconDice({ size = 18, 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">
      <rect width="12" height="12" x="2" y="10" rx="2"/><path d="m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6.08"/><path d="M6 18h.01"/><path d="M10 14h.01"/><path d="M15 6h.01"/><path d="M18 9h.01"/>
    </svg>
  );
}

function IconBook({ size = 18, 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="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/>
    </svg>
  );
}

function IconEye({ 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="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/>
    </svg>
  );
}

function IconReply({ 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="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/>
    </svg>
  );
}

function IconPin({ 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">
      <line x1="12" x2="12" y1="17" y2="22"/><path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24z"/>
    </svg>
  );
}

function IconLock({ 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">
      <rect width="18" height="11" x="3" y="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
    </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="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
    </svg>
  );
}

function IconPlus({ 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">
      <path d="M12 5v14"/><path d="M5 12h14"/>
    </svg>
  );
}

function IconX({ 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">
      <path d="M18 6 6 18"/><path d="M6 6l12 12"/>
    </svg>
  );
}

function IconArrowLeft({ 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">
      <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>
    </svg>
  );
}

function IconLoader({ size = 18, 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 & Data
// ==========================================

interface ForumCategory {
  id: string;
  name: string;
  description: string;
  slug?: string;
  icon: React.ReactNode;
  color: string;
  discussion_count: number;
  members_only: boolean;
  display_order?: number;
  is_active?: boolean;
  /** Phase 17.2 finition Gap 4 (2026-05-06) — Type ACL côté backend */
  kind?: 'public' | 'gang' | 'cartel' | 'cartel_diplomacy';
}

interface ForumDiscussion {
  id: string;
  title: string;
  author: string;
  replies: number;
  views: number;
  pinned: boolean;
  locked: boolean;
  time: string;
}

// API category shape (what comes from the backend)
interface ApiCategory {
  id: string;
  name: string;
  description: string;
  slug?: string;
  display_order?: number;
  is_active?: boolean;
  members_only?: boolean;
  discussion_count?: number;
  color?: string;
  kind?: 'public' | 'gang' | 'cartel' | 'cartel_diplomacy';
  sort_order?: number;
}

// API discussion shape
interface ApiDiscussion {
  id: string;
  title: string;
  author?: string;
  author_username?: string;
  user?: { username: string };
  reply_count?: number;
  replies_count?: number;
  replies?: number;
  view_count?: number;
  views_count?: number;
  views?: number;
  is_pinned?: boolean;
  pinned?: boolean;
  is_locked?: boolean;
  locked?: boolean;
  created_at?: string;
  updated_at?: string;
}

// Icon mapping from slug/name to SVG icon component
const ICON_MAP: Record<string, React.ReactNode> = {
  'general': <IconChat />,
  'discussions-generales': <IconChat />,
  'presentations': <IconUsers />,
  'strategies': <IconBook />,
  'strategies-guides': <IconBook />,
  'crime': <IconTarget />,
  'voie-criminelle': <IconTarget />,
  'politique': <IconBuilding />,
  'voie-politique': <IconBuilding />,
  'redemption': <IconLeaf />,
  'voie-redemption': <IconLeaf />,
  'marketplace': <IconHandshake />,
  'marketplace-echanges': <IconHandshake />,
  'bugs': <IconBug />,
  'bugs-suggestions': <IconBug />,
  'events': <IconCalendar />,
  'evenements': <IconCalendar />,
  'hors-sujet': <IconDice />,
  'map': <IconMap />,
};

const COLOR_MAP: Record<string, string> = {
  'general': 'var(--color-gold)',
  'discussions-generales': 'var(--color-gold)',
  'presentations': '#60a5fa',
  'strategies': '#a78bfa',
  'strategies-guides': '#a78bfa',
  'crime': 'var(--color-red-light)',
  'voie-criminelle': 'var(--color-red-light)',
  'politique': 'var(--color-gold)',
  'voie-politique': 'var(--color-gold)',
  'redemption': '#22c55e',
  'voie-redemption': '#22c55e',
  'marketplace': '#f59e0b',
  'marketplace-echanges': '#f59e0b',
  'bugs': '#ef4444',
  'bugs-suggestions': '#ef4444',
  'events': '#ec4899',
  'evenements': '#ec4899',
  'hors-sujet': '#94a3b8',
};

const DEFAULT_ICON = <IconChat />;
const DEFAULT_COLOR = 'var(--color-gold)';

// Fallback mock data when API is unavailable
const FALLBACK_CATEGORIES: ForumCategory[] = [
  { id: 'general', name: 'Discussions Générales', description: 'Échangez librement sur tous les sujets liés au jeu.', icon: <IconChat />, color: 'var(--color-gold)', discussion_count: 42, members_only: false },
  { id: 'presentations', name: 'Présentations', description: 'Nouveau joueur ? Présentez-vous à la communauté.', icon: <IconUsers />, color: '#60a5fa', discussion_count: 18, members_only: false },
  { id: 'strategies', name: 'Stratégies & Guides', description: 'Partagez vos stratégies, guides et astuces.', icon: <IconBook />, color: '#a78bfa', discussion_count: 7, members_only: true },
  { id: 'crime', name: 'Voie Criminelle', description: 'Empires, gangs, territoires. Le côté sombre.', icon: <IconTarget />, color: 'var(--color-red-light)', discussion_count: 31, members_only: true },
  { id: 'politique', name: 'Voie Politique', description: 'Élections, corruption, pouvoir.', icon: <IconBuilding />, color: 'var(--color-gold)', discussion_count: 12, members_only: true },
  { id: 'redemption', name: 'Voie Rédemption', description: 'Écologie, associations, légalité.', icon: <IconLeaf />, color: '#22c55e', discussion_count: 9, members_only: true },
  { id: 'marketplace', name: 'Marketplace & Échanges', description: 'Annonces, recherches, négociations.', icon: <IconHandshake />, color: '#f59e0b', discussion_count: 24, members_only: true },
  { id: 'bugs', name: 'Bugs & Suggestions', description: 'Signalez des bugs ou proposez des améliorations.', icon: <IconBug />, color: '#ef4444', discussion_count: 15, members_only: false },
  { id: 'events', name: 'Événements', description: 'Tournois, rassemblements, événements communautaires.', icon: <IconCalendar />, color: '#ec4899', discussion_count: 3, members_only: false },
  { id: 'hors-sujet', name: 'Hors-Sujet', description: 'Tout ce qui ne rentre pas ailleurs.', icon: <IconDice />, color: '#94a3b8', discussion_count: 56, members_only: false },
];

const FALLBACK_DISCUSSIONS: ForumDiscussion[] = [
  { id: '1', title: 'Bienvenue sur le forum ! Lisez ceci en premier', author: 'Admin', replies: 34, views: 892, pinned: true, locked: false, time: 'il y a 2h' },
  { id: '2', title: 'Guide complet du débutant — Saison 1', author: 'DarkLord42', replies: 12, views: 341, pinned: true, locked: false, time: 'il y a 5h' },
  { id: '3', title: 'Quelqu\'un pour former un gang sur Lyon ?', author: 'ShadowK', replies: 8, views: 124, pinned: false, locked: false, time: 'il y a 1h' },
  { id: '4', title: 'Le nouveau système de marketplace est top', author: 'LeMarchand', replies: 21, views: 267, pinned: false, locked: false, time: 'il y a 3h' },
  { id: '5', title: 'Bug : impossible de se connecter depuis mobile', author: 'MobileUser', replies: 3, views: 45, pinned: false, locked: false, time: 'il y a 30min' },
  { id: '6', title: '[RÉSOLU] Perte de dagaz après transaction', author: 'CryptoMafia', replies: 7, views: 89, pinned: false, locked: true, time: 'hier' },
];

const FORUM_RULES = [
  'Respectez tous les membres de la communauté.',
  'Pas de contenu discriminatoire, haineux ou illégal.',
  'Pas de spam, publicité ou liens malveillants.',
  'Utilisez les catégories appropriées pour vos sujets.',
  'Le français est la langue principale. L\'anglais est accepté.',
  'Les spoilers doivent être clairement signalés.',
  'Les modérateurs ont le dernier mot.',
  'Un seul compte par joueur.',
];

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

function mapApiCategory(cat: ApiCategory): ForumCategory {
  const slug = cat.slug || cat.name.toLowerCase().replace(/\s+/g, '-').normalize('NFD').replace(/[\u0300-\u036f]/g, '');
  return {
    id: cat.id,
    name: cat.name,
    description: cat.description || '',
    slug,
    icon: ICON_MAP[slug] || ICON_MAP[cat.id] || DEFAULT_ICON,
    color: cat.color || COLOR_MAP[slug] || COLOR_MAP[cat.id] || DEFAULT_COLOR,
    discussion_count: cat.discussion_count ?? 0,
    members_only: cat.members_only ?? false,
    display_order: cat.display_order ?? cat.sort_order,
    is_active: cat.is_active,
    kind: cat.kind ?? 'public',
  };
}

function mapApiDiscussion(d: ApiDiscussion): ForumDiscussion {
  const author = d.author || d.author_username || d.user?.username || 'Anonyme';
  const replies = d.reply_count ?? d.replies_count ?? d.replies ?? 0;
  const views = d.view_count ?? d.views_count ?? d.views ?? 0;
  const pinned = d.is_pinned ?? d.pinned ?? false;
  const locked = d.is_locked ?? d.locked ?? false;

  let time = '';
  if (d.created_at) {
    const date = new Date(d.created_at);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMin = Math.floor(diffMs / 60000);
    const diffH = Math.floor(diffMin / 60);
    const diffD = Math.floor(diffH / 24);
    if (diffMin < 1) time = 'à l\'instant';
    else if (diffMin < 60) time = `il y a ${diffMin}min`;
    else if (diffH < 24) time = `il y a ${diffH}h`;
    else if (diffD === 1) time = 'hier';
    else if (diffD < 7) time = `il y a ${diffD}j`;
    else time = date.toLocaleDateString('fr-FR');
  }

  return { id: d.id, title: d.title, author, replies, views, pinned, locked, time };
}

// ==========================================
// Page Component
// ==========================================

interface ForumStats {
  discussions: string;
  replies: string;
  activeMembers: string;
  online: string;
}

const FALLBACK_STATS: ForumStats = {
  discussions: '0',
  replies: '0',
  activeMembers: '0',
  online: '0',
};

export default function ForumPage() {
  const { isAuthenticated } = useAuth();

  const [selectedCategory, setSelectedCategory] = useState<string | null>(null);
  const [showNewDiscussion, setShowNewDiscussion] = useState(false);

  // Data states
  const [categories, setCategories] = useState<ForumCategory[]>([]);
  const [discussions, setDiscussions] = useState<ForumDiscussion[]>([]);
  const [stats, setStats] = useState<ForumStats>(FALLBACK_STATS);

  // Loading states
  const [loadingCategories, setLoadingCategories] = useState(true);
  const [loadingDiscussions, setLoadingDiscussions] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  // Error states
  const [categoriesError, setCategoriesError] = useState<string | null>(null);
  const [discussionsError, setDiscussionsError] = useState<string | null>(null);
  const [submitError, setSubmitError] = useState<string | null>(null);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [authError, setAuthError] = useState<string | null>(null);

  // New discussion form state
  const [newCategoryId, setNewCategoryId] = useState('');
  const [newTitle, setNewTitle] = useState('');
  const [newContent, setNewContent] = useState('');

  // Fetch categories on mount
  useEffect(() => {
    let cancelled = false;
    async function fetchCategories() {
      setLoadingCategories(true);
      setCategoriesError(null);
      try {
        const data = await api.forum.getCategories();
        if (cancelled) return;
        // Handle various response shapes
        const raw: ApiCategory[] = Array.isArray(data)
          ? data
          : (data as { categories?: ApiCategory[] })?.categories || [];
        const mapped = raw
          .filter((c) => c.is_active !== false)
          .sort((a, b) => (a.display_order ?? 999) - (b.display_order ?? 999))
          .map(mapApiCategory);
        setCategories(mapped.length > 0 ? mapped : FALLBACK_CATEGORIES);
      } catch {
        if (cancelled) return;
        setCategoriesError('Impossible de charger les catégories. Données de secours affichées.');
        setCategories(FALLBACK_CATEGORIES);
      } finally {
        if (!cancelled) setLoadingCategories(false);
      }
    }
    fetchCategories();
    return () => { cancelled = true; };
  }, []);

  // Fetch real forum stats from backend
  useEffect(() => {
    let cancelled = false;
    async function fetchStats() {
      try {
        const token = localStorage.getItem('ol_token');
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'https://api.mafiaz.world';
        const res = await fetch(`${apiUrl}/api/forum/stats`, {
          headers: token ? { Authorization: `Bearer ${token}` } : {},
        });
        if (!res.ok) throw new Error('Stats fetch failed');
        const data = await res.json();
        if (cancelled) return;
        setStats({
          discussions: (data.discussions ?? 0).toLocaleString('fr-FR'),
          replies: (data.replies ?? 0).toLocaleString('fr-FR'),
          activeMembers: (data.activeMembers ?? 0).toLocaleString('fr-FR'),
          online: (data.online ?? 0).toLocaleString('fr-FR'),
        });
      } catch {
        // Keep fallback zeros
      }
    }
    fetchStats();
    return () => { cancelled = true; };
  }, []);

  // Fetch discussions when a category is selected
  const fetchDiscussions = useCallback(async (categoryId: string) => {
    setLoadingDiscussions(true);
    setDiscussionsError(null);
    try {
      const data = await api.forum.getDiscussions({ category: categoryId });
      // Handle various response shapes
      const raw: ApiDiscussion[] = Array.isArray(data)
        ? data
        : (data as { discussions?: ApiDiscussion[] })?.discussions || [];
      const mapped = raw.map(mapApiDiscussion);
      // Sort: pinned first, then by time
      mapped.sort((a, b) => {
        if (a.pinned && !b.pinned) return -1;
        if (!a.pinned && b.pinned) return 1;
        return 0;
      });
      setDiscussions(mapped.length > 0 ? mapped : FALLBACK_DISCUSSIONS);
    } catch {
      setDiscussionsError('Impossible de charger les discussions. Données de secours affichées.');
      setDiscussions(FALLBACK_DISCUSSIONS);
    } finally {
      setLoadingDiscussions(false);
    }
  }, []);

  useEffect(() => {
    if (selectedCategory) {
      fetchDiscussions(selectedCategory);
    } else {
      setDiscussions([]);
      setDiscussionsError(null);
    }
  }, [selectedCategory, fetchDiscussions]);

  // Handle new discussion submission
  async function handleCreateDiscussion(e: React.FormEvent) {
    e.preventDefault();
    if (!newTitle.trim() || !newContent.trim()) return;

    if (!isAuthenticated) {
      setAuthError('Vous devez être connecté pour créer une discussion.');
      return;
    }

    setAuthError(null);
    setSubmitting(true);
    setSubmitError(null);
    setSubmitSuccess(false);
    try {
      await api.forum.createDiscussion({
        title: newTitle.trim(),
        content: newContent.trim(),
        category_id: newCategoryId || undefined,
      });
      setSubmitSuccess(true);
      setNewTitle('');
      setNewContent('');
      setNewCategoryId('');
      // Refresh discussions if we're viewing the same category
      if (selectedCategory && (newCategoryId === selectedCategory || !newCategoryId)) {
        fetchDiscussions(selectedCategory);
      }
      // Close modal after short delay so the user sees the success
      setTimeout(() => {
        setShowNewDiscussion(false);
        setSubmitSuccess(false);
      }, 1200);
    } catch {
      setSubmitError('Erreur lors de la publication. Veuillez réessayer.');
    } finally {
      setSubmitting(false);
    }
  }

  const activeCategory = categories.find(c => c.id === selectedCategory);

  return (
    <div className="min-h-screen" style={{ background: 'var(--bg-primary)' }}>
      <NavBar />

      <div className="max-w-[1400px] mx-auto px-4 py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            {selectedCategory && (
              <button
                onClick={() => setSelectedCategory(null)}
                className="p-2 rounded-lg transition-all hover:scale-105"
                style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)' }}
              >
                <IconArrowLeft color="var(--text-secondary)" />
              </button>
            )}
            <div>
              <h1 className="font-gothic text-2xl text-gold-gradient">
                {activeCategory ? activeCategory.name : 'Forum'}
              </h1>
              <p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
                {activeCategory ? activeCategory.description : 'Communauté Ombres & Lumières'}
              </p>
            </div>
          </div>
          <button
            onClick={() => setShowNewDiscussion(true)}
            className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-bold transition-all hover:scale-105"
            style={{
              background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
              color: 'white',
              boxShadow: '0 0 20px rgba(196,30,30,0.3)',
            }}
          >
            <IconPlus size={14} />
            Nouvelle discussion
          </button>
        </div>

        {/* Error banner for categories */}
        {categoriesError && (
          <div
            className="mb-4 px-4 py-2 rounded-lg text-xs"
            style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#fca5a5' }}
          >
            {categoriesError}
          </div>
        )}

        {/* Main Layout: Sidebar Left (categories) | Main (discussions) | Sidebar Right (info) */}
        <div className="grid grid-cols-1 lg:grid-cols-[240px_1fr_280px] gap-5">

          {/* ===== SIDEBAR LEFT — Catégories ===== */}
          <aside className="hidden lg:block space-y-1">
            <h2 className="text-[10px] uppercase tracking-widest font-bold mb-3 px-2" style={{ color: 'var(--text-muted)' }}>
              Catégories
            </h2>
            {loadingCategories ? (
              <div className="flex items-center justify-center py-8">
                <IconLoader size={20} color="var(--text-muted)" />
              </div>
            ) : (
              categories.map((cat) => {
                const isActive = selectedCategory === cat.id;
                return (
                  <button
                    key={cat.id}
                    onClick={() => setSelectedCategory(isActive ? null : cat.id)}
                    className="w-full text-left px-3 py-2.5 rounded-lg transition-all group"
                    style={{
                      background: isActive ? 'rgba(196,30,30,0.12)' : 'transparent',
                      borderLeft: isActive ? '3px solid var(--color-red)' : '3px solid transparent',
                    }}
                  >
                    <div className="flex items-center gap-2.5">
                      <div
                        className="w-7 h-7 rounded flex items-center justify-center flex-shrink-0"
                        style={{ background: `${cat.color}15`, color: cat.color }}
                      >
                        {cat.icon}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="text-xs font-medium truncate flex items-center gap-1" style={{
                          color: isActive ? 'var(--color-gold)' : 'var(--text-primary)',
                        }}>
                          {cat.kind === 'cartel_diplomacy' && <span title="Diplomatie cartel">🤝</span>}
                          {cat.name}
                        </div>
                      </div>
                      <span className="text-[10px] font-mono" style={{ color: 'var(--text-muted)' }}>
                        {cat.discussion_count}
                      </span>
                    </div>
                  </button>
                );
              })
            )}
          </aside>

          {/* ===== MAIN — Discussions ===== */}
          <main className="min-w-0">
            {/* Mobile category chips */}
            <div className="lg:hidden flex gap-2 overflow-x-auto pb-3 mb-4 scrollbar-hide">
              {loadingCategories ? (
                <div className="flex items-center justify-center w-full py-2">
                  <IconLoader size={16} color="var(--text-muted)" />
                </div>
              ) : (
                categories.map((cat) => (
                  <button
                    key={cat.id}
                    onClick={() => setSelectedCategory(selectedCategory === cat.id ? null : cat.id)}
                    className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs whitespace-nowrap"
                    style={{
                      background: selectedCategory === cat.id ? 'rgba(196,30,30,0.2)' : 'rgba(255,255,255,0.05)',
                      border: selectedCategory === cat.id ? '1px solid var(--color-red)' : '1px solid var(--border-dark)',
                      color: selectedCategory === cat.id ? 'var(--color-gold)' : 'var(--text-secondary)',
                    }}
                  >
                    <span style={{ color: cat.color }}>{cat.icon}</span>
                    {cat.name.split(' ')[0]}
                  </button>
                ))
              )}
            </div>

            {/* Category overview or Discussion list */}
            {!selectedCategory ? (
              loadingCategories ? (
                <div className="flex items-center justify-center py-16">
                  <IconLoader size={24} color="var(--text-muted)" />
                </div>
              ) : (
                <div className="space-y-2">
                  {categories.map((cat) => (
                    <button
                      key={cat.id}
                      onClick={() => setSelectedCategory(cat.id)}
                      className="w-full text-left p-4 rounded-lg transition-all hover:translate-x-1 group"
                      style={{
                        background: 'rgba(255,255,255,0.02)',
                        border: '1px solid var(--border-dark)',
                      }}
                    >
                      <div className="flex items-center gap-4">
                        <div
                          className="w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0 transition-transform group-hover:scale-110"
                          style={{ background: `${cat.color}12`, color: cat.color }}
                        >
                          {cat.icon}
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <h3 className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>
                              {cat.name}
                            </h3>
                            {cat.members_only && (
                              <IconLock size={11} color="var(--color-red-light)" />
                            )}
                          </div>
                          <p className="text-xs mt-0.5 truncate" style={{ color: 'var(--text-muted)' }}>
                            {cat.description}
                          </p>
                        </div>
                        <div className="text-right flex-shrink-0">
                          <div className="text-sm font-bold" style={{ color: cat.color }}>
                            {cat.discussion_count}
                          </div>
                          <div className="text-[10px]" style={{ color: 'var(--text-muted)' }}>sujets</div>
                        </div>
                      </div>
                    </button>
                  ))}
                </div>
              )
            ) : (
              <>
                {/* Error banner for discussions */}
                {discussionsError && (
                  <div
                    className="mb-3 px-4 py-2 rounded-lg text-xs"
                    style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#fca5a5' }}
                  >
                    {discussionsError}
                  </div>
                )}

                {loadingDiscussions ? (
                  <div className="flex items-center justify-center py-16">
                    <IconLoader size={24} color="var(--text-muted)" />
                  </div>
                ) : (
                  <div className="space-y-1.5">
                    {discussions.length === 0 ? (
                      <div className="text-center py-12">
                        <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
                          Aucune discussion dans cette catégorie pour le moment.
                        </p>
                        <button
                          onClick={() => setShowNewDiscussion(true)}
                          className="mt-3 text-xs font-medium underline"
                          style={{ color: 'var(--color-gold)' }}
                        >
                          Créer la première discussion
                        </button>
                      </div>
                    ) : (
                      discussions.map((d) => (
                        <div
                          key={d.id}
                          className="flex items-center gap-3 p-3 rounded-lg transition-all hover:translate-x-1 cursor-pointer"
                          style={{
                            background: d.pinned ? 'rgba(196,30,30,0.06)' : 'rgba(255,255,255,0.02)',
                            border: d.pinned ? '1px solid rgba(196,30,30,0.2)' : '1px solid var(--border-dark)',
                          }}
                        >
                          {/* Avatar placeholder */}
                          <div
                            className="w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-xs font-bold"
                            style={{
                              background: 'linear-gradient(135deg, rgba(196,30,30,0.3), rgba(196,30,30,0.1))',
                              color: 'var(--color-red-light)',
                            }}
                          >
                            {d.author[0].toUpperCase()}
                          </div>

                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-1.5">
                              {d.pinned && <IconPin size={11} color="var(--color-gold)" />}
                              {d.locked && <IconLock size={11} color="var(--text-muted)" />}
                              <h4 className="text-sm font-medium truncate" style={{ color: 'var(--text-primary)' }}>
                                {d.title}
                              </h4>
                            </div>
                            <div className="flex items-center gap-3 mt-1 text-[11px]" style={{ color: 'var(--text-muted)' }}>
                              <span style={{ color: 'var(--color-gold)' }}>{d.author}</span>
                              <span className="flex items-center gap-1"><IconReply size={10} />{d.replies}</span>
                              <span className="flex items-center gap-1"><IconEye size={10} />{d.views}</span>
                              <span>{d.time}</span>
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                )}
              </>
            )}
          </main>

          {/* ===== SIDEBAR RIGHT — Infos ===== */}
          <aside className="hidden lg:block space-y-4">

            {/* Règles */}
            <div
              className="rounded-lg p-4"
              style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}
            >
              <div className="flex items-center gap-2 mb-3">
                <IconShield size={14} color="var(--color-gold)" />
                <h3 className="text-xs font-bold uppercase tracking-wider" style={{ color: 'var(--color-gold)' }}>
                  Règles
                </h3>
              </div>
              <ol className="space-y-1.5">
                {FORUM_RULES.map((rule, i) => (
                  <li key={i} className="flex gap-2 text-[11px] leading-relaxed" style={{ color: 'var(--text-muted)' }}>
                    <span className="font-mono flex-shrink-0" style={{ color: 'var(--color-red)' }}>{i + 1}.</span>
                    {rule}
                  </li>
                ))}
              </ol>
            </div>

            {/* Statistiques */}
            <div
              className="rounded-lg p-4"
              style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}
            >
              <h3 className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: 'var(--color-gold)' }}>
                Statistiques
              </h3>
              <div className="space-y-2">
                {[
                  { label: 'Discussions', value: stats.discussions },
                  { label: 'Réponses', value: stats.replies },
                  { label: 'Membres actifs', value: stats.activeMembers },
                  { label: 'En ligne', value: stats.online },
                ].map(s => (
                  <div key={s.label} className="flex justify-between items-center text-xs">
                    <span style={{ color: 'var(--text-muted)' }}>{s.label}</span>
                    <span className="font-mono font-bold" style={{ color: 'var(--text-primary)' }}>{s.value}</span>
                  </div>
                ))}
              </div>
            </div>

            {/* Derniers actifs */}
            <div
              className="rounded-lg p-4"
              style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}
            >
              <h3 className="text-xs font-bold uppercase tracking-wider mb-3" style={{ color: 'var(--color-gold)' }}>
                Récemment actifs
              </h3>
              <div className="flex flex-wrap gap-1.5">
                {['DarkLord42', 'ShadowK', 'LeMarchand', 'Admin', 'CryptoMafia', 'MobileUser'].map(name => (
                  <span
                    key={name}
                    className="px-2 py-1 rounded text-[10px] font-medium"
                    style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--text-secondary)' }}
                  >
                    {name}
                  </span>
                ))}
              </div>
            </div>
          </aside>
        </div>
      </div>

      {/* ===== New Discussion Modal ===== */}
      {showNewDiscussion && (
        <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) setShowNewDiscussion(false); }}
        >
          <div
            className="w-full max-w-lg rounded-xl overflow-hidden"
            style={{ background: 'var(--bg-secondary)', border: '1px solid var(--border-dark)' }}
          >
            {/* Modal header */}
            <div
              className="flex items-center justify-between px-5 py-4"
              style={{ borderBottom: '1px solid var(--border-dark)' }}
            >
              <h2 className="font-impact text-base" style={{ color: 'var(--color-gold)' }}>
                Nouvelle Discussion
              </h2>
              <button
                onClick={() => { setShowNewDiscussion(false); setSubmitError(null); setSubmitSuccess(false); setAuthError(null); }}
                className="p-1 rounded hover:bg-white/5 transition-colors"
              >
                <IconX color="var(--text-muted)" />
              </button>
            </div>

            {/* Modal body */}
            <form onSubmit={handleCreateDiscussion}>
              <div className="p-5 space-y-4">
                {/* Auth error */}
                {authError && (
                  <div
                    className="px-4 py-2 rounded-lg text-xs"
                    style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#fca5a5' }}
                  >
                    {authError}{' '}
                    <a href="/auth/login" className="underline font-bold" style={{ color: '#fca5a5' }}>
                      Se connecter
                    </a>
                  </div>
                )}

                {/* Success message */}
                {submitSuccess && (
                  <div
                    className="px-4 py-2 rounded-lg text-xs"
                    style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.3)', color: '#86efac' }}
                  >
                    Discussion publiée avec succès !
                  </div>
                )}

                {/* Error message */}
                {submitError && (
                  <div
                    className="px-4 py-2 rounded-lg text-xs"
                    style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.3)', color: '#fca5a5' }}
                  >
                    {submitError}
                  </div>
                )}

                <div>
                  <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                    Catégorie
                  </label>
                  <select
                    value={newCategoryId}
                    onChange={(e) => setNewCategoryId(e.target.value)}
                    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)' }}
                  >
                    <option value="">Choisir une catégorie...</option>
                    {categories.map(c => (
                      <option key={c.id} value={c.id}>
                        {c.kind === 'cartel_diplomacy' ? '🤝 ' : ''}{c.name}
                        {c.kind === 'cartel_diplomacy' ? ' (admins cartel uniquement)' : ''}
                      </option>
                    ))}
                  </select>
                  {/* Phase 17.2 finition Gap 4 (2026-05-06) — Hint Diplomatie */}
                  {(() => {
                    const sel = categories.find(c => c.id === newCategoryId);
                    if (sel?.kind === 'cartel_diplomacy') {
                      return (
                        <p className="text-[10px] mt-1.5 italic" style={{ color: 'var(--color-gold-light)' }}>
                          🤝 Section Diplomatie : seuls les admins de cartel (fondateurs ou underbosses) peuvent publier ici. Les non-admins peuvent lire.
                        </p>
                      );
                    }
                    return null;
                  })()}
                </div>

                <div>
                  <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                    Titre
                  </label>
                  <input
                    type="text"
                    value={newTitle}
                    onChange={(e) => setNewTitle(e.target.value)}
                    placeholder="Titre de votre discussion..."
                    required
                    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)' }}
                  />
                </div>

                <div>
                  <label className="text-[11px] uppercase tracking-wider font-bold block mb-1.5" style={{ color: 'var(--text-muted)' }}>
                    Message
                  </label>
                  <textarea
                    value={newContent}
                    onChange={(e) => setNewContent(e.target.value)}
                    placeholder="Rédigez votre message..."
                    required
                    rows={6}
                    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)' }}
                  />
                </div>
              </div>

              {/* Modal footer */}
              <div
                className="flex gap-3 justify-end px-5 py-4"
                style={{ borderTop: '1px solid var(--border-dark)' }}
              >
                <button
                  type="button"
                  onClick={() => { setShowNewDiscussion(false); setSubmitError(null); setSubmitSuccess(false); setAuthError(null); }}
                  className="px-4 py-2 rounded-lg text-sm"
                  style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--text-secondary)' }}
                  disabled={submitting}
                >
                  Annuler
                </button>
                <button
                  type="submit"
                  disabled={submitting || !newTitle.trim() || !newContent.trim()}
                  className="px-5 py-2 rounded-lg text-sm font-bold transition-all hover:scale-105 flex items-center gap-2"
                  style={{
                    background: submitting
                      ? 'rgba(196,30,30,0.5)'
                      : 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
                    color: 'white',
                    boxShadow: submitting ? 'none' : '0 0 15px rgba(196,30,30,0.3)',
                    opacity: (!newTitle.trim() || !newContent.trim()) ? 0.5 : 1,
                    cursor: submitting ? 'wait' : (!newTitle.trim() || !newContent.trim()) ? 'not-allowed' : 'pointer',
                  }}
                >
                  {submitting && <IconLoader size={14} color="white" />}
                  {submitting ? 'Publication...' : 'Publier'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
