'use client';

import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { NavBar } from '@/components/layout/NavBar';
import { api } from '@/lib/api';
import { useAuth } from '@/lib/useAuth';
// Phase 15 Commit 6 (20-04-2026) — panneau spécialistes scope=player
import { SpecialistsPlayerPanel } from '@/components/specialists/SpecialistsPlayerPanel';
import { GarageRentalsPanel } from '@/components/garage/GarageRentalsPanel';

// ==========================================
// SVG Icons
// ==========================================
function IconUser({ 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="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>;
}
function IconMail({ 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="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>;
}
function IconBell({ 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="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9"/><path d="M10.3 21a1.94 1.94 0 0 0 3.4 0"/></svg>;
}
function IconActivity({ 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"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>;
}
function IconPackage({ 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="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>;
}
function IconBarChart({ 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"><line x1="12" x2="12" y1="20" y2="10"/><line x1="18" x2="18" y1="20" y2="4"/><line x1="6" x2="6" y1="20" y2="16"/></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 IconClock({ size = 12, 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"/><polyline points="12 6 12 12 16 14"/></svg>;
}

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

interface PlayerProfile {
  id: string;
  username: string;
  email: string;
  language: string;
  profile_image_url: string | null;
  is_admin: boolean;
  is_moderator: boolean;
  created_at: string;
}

interface GaugesData {
  fortune: number;
  pouvoir: number;
  chaleur: number;
  conscience: number;
  respect: number;
  social: number;
  popularite: number;
  instabilite: number;
  influence: number;
  ecologie: number;
  // Phase 8 v2 (2026-05-01) — physical_health vient de health.* (PlayerHealth),
  // pas de gauges.*. On garde la clé dans GaugesData pour le rendu unifié
  // (la valeur sera injectée à la lecture depuis l'objet health).
  physical_health: number;
  [key: string]: number;
}

type AccountTab = 'profile' | 'messages' | 'notifications' | 'activity' | 'orders' | 'status' | 'specialists' | 'garage';

const TABS: { id: AccountTab; label: string; icon: React.ReactNode }[] = [
  { id: 'profile', label: 'Mon Profil', icon: <IconUser /> },
  { id: 'messages', label: 'Mes Messages', icon: <IconMail /> },
  { id: 'notifications', label: 'Notifications', icon: <IconBell /> },
  { id: 'activity', label: 'Mon Activité', icon: <IconActivity /> },
  { id: 'orders', label: 'Mes Commandes', icon: <IconPackage /> },
  { id: 'status', label: 'Mes Personnages', icon: <IconBarChart /> },
  // Phase 15 Commit 6 (20-04-2026) — spécialistes personnels (scope=player)
  { id: 'specialists', label: 'Mes Spécialistes', icon: <IconUser /> },
  // Phase 17.2 finition (2026-05-06) — locations de garage actives
  { id: 'garage', label: 'Mes Garages', icon: <IconPackage /> },
];

// ==========================================
// API response types
// ==========================================

interface MessageData {
  id: string;
  sender_id: string;
  recipient_id: string;
  subject: string;
  content: string;
  is_read: boolean;
  created_at: string;
  sender?: { username: string };
  recipient?: { username: string };
}

interface NotificationData {
  id: string;
  player_id: string;
  type: string;
  text: string;
  is_read: boolean;
  created_at: string;
}

interface ActivityData {
  id: string;
  player_id: string;
  action: string;
  section: string;
  details?: string;
  created_at: string;
}

interface OrderData {
  id: string;
  player_id: string;
  items: string;
  total: number;
  status: string;
  created_at: string;
}

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

function formatMemberSince(dateStr: string): string {
  if (!dateStr) return '—';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '—';
  const months = [
    'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
    'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre',
  ];
  return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
}

function formatMemberSinceShort(dateStr: string): string {
  if (!dateStr) return '—';
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return '—';
  const months = [
    'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
    'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre',
  ];
  return `${months[date.getMonth()]} ${date.getFullYear()}`;
}

function getInitial(username: string | undefined | null): string {
  if (!username) return '?';
  return username.charAt(0).toUpperCase();
}

function formatTimeAgo(dateStr: string): string {
  try {
    const now = Date.now();
    const then = new Date(dateStr).getTime();
    const diff = now - then;
    const minutes = Math.floor(diff / 60000);
    if (minutes < 1) return "à l'instant";
    if (minutes < 60) return `il y a ${minutes}min`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `il y a ${hours}h`;
    const days = Math.floor(hours / 24);
    if (days < 7) return `il y a ${days}j`;
    return formatMemberSince(dateStr);
  } catch {
    return dateStr;
  }
}

function formatDateShort(dateStr: string): string {
  try {
    const date = new Date(dateStr);
    const months = [
      'jan', 'fév', 'mars', 'avr', 'mai', 'juin',
      'juil', 'août', 'sept', 'oct', 'nov', 'déc',
    ];
    return `${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}`;
  } catch {
    return dateStr;
  }
}

function getLanguageLabel(lang: string | undefined | null): string {
  if (!lang) return 'Non défini';
  const map: Record<string, string> = {
    fr: 'Français',
    en: 'English',
    es: 'Español',
    de: 'Deutsch',
    it: 'Italiano',
    pt: 'Português',
  };
  return map[lang.toLowerCase()] || lang;
}

// ==========================================
// Loading spinner
// ==========================================
function LoadingSpinner({ text = 'Chargement...' }: { text?: string }) {
  return (
    <div className="flex flex-col items-center justify-center py-16 gap-3">
      <div
        className="w-8 h-8 border-2 rounded-full animate-spin"
        style={{ borderColor: 'var(--border-dark)', borderTopColor: 'var(--color-gold)' }}
      />
      <span className="text-xs" style={{ color: 'var(--text-muted)' }}>{text}</span>
    </div>
  );
}

// ==========================================
// Error display
// ==========================================
function ErrorDisplay({ message, onRetry }: { message: string; onRetry?: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center py-12 gap-3">
      <div className="text-sm" style={{ color: 'var(--color-red-light)' }}>{message}</div>
      {onRetry && (
        <button onClick={onRetry} className="btn-ghost px-4 py-2 text-xs">
          Réessayer
        </button>
      )}
    </div>
  );
}

// ==========================================
// Avatar component
// ==========================================
function PlayerAvatar({ username, profileImageUrl, size = 'md' }: {
  username: string | undefined | null;
  profileImageUrl: string | undefined | null;
  size?: 'sm' | 'md' | 'lg';
}) {
  const sizeMap = { sm: 'w-9 h-9 text-[10px]', md: 'w-14 h-14 text-xl', lg: 'w-20 h-20 text-2xl' };

  if (profileImageUrl) {
    return (
      <img
        src={profileImageUrl}
        alt={username || 'Avatar'}
        className={`${sizeMap[size]} rounded-full object-cover`}
      />
    );
  }

  return (
    <div
      className={`${sizeMap[size]} rounded-full flex items-center justify-center font-bold`}
      style={{ background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))', color: 'white' }}
    >
      {getInitial(username)}
    </div>
  );
}

// ==========================================
// Main page
// ==========================================
export default function AccountPage() {
  const router = useRouter();
  const { isAuthenticated, player, loading: authLoading } = useAuth();
  const [activeTab, setActiveTab] = useState<AccountTab>('profile');

  // Redirect to login if not authenticated
  useEffect(() => {
    if (!authLoading && !isAuthenticated) {
      router.push('/auth/login');
    }
  }, [authLoading, isAuthenticated, router]);

  // Show loading while auth is being checked
  if (authLoading) {
    return (
      <div className="min-h-screen" style={{ background: 'var(--bg-primary)' }}>
        <NavBar />
        <LoadingSpinner text="Vérification de l&apos;authentification..." />
      </div>
    );
  }

  // Don't render anything while redirecting
  if (!isAuthenticated || !player) {
    return null;
  }

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

      <div className="max-w-[1200px] mx-auto px-4 py-6">
        {/* Header */}
        <div className="flex items-center gap-4 mb-6">
          <PlayerAvatar username={player.username} profileImageUrl={player.profile_image_url} size="md" />
          <div>
            <h2 className="font-gothic text-2xl text-gold-gradient">Mon Compte</h2>
            <p className="text-xs" style={{ color: 'var(--text-muted)' }}>
              {player.username} — Membre depuis {formatMemberSinceShort(player.created_at)}
            </p>
          </div>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-[220px_1fr] gap-5">
          {/* Sidebar tabs */}
          <aside className="space-y-1">
            {TABS.map((tab) => {
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => setActiveTab(tab.id)}
                  className="w-full flex items-center gap-2.5 px-3 py-2.5 rounded-lg text-left transition-all"
                  style={{
                    background: isActive ? 'rgba(196,30,30,0.1)' : 'transparent',
                    borderLeft: isActive ? '3px solid var(--color-red)' : '3px solid transparent',
                    color: isActive ? 'var(--color-gold)' : 'var(--text-secondary)',
                  }}
                >
                  <span style={{ color: isActive ? 'var(--color-gold)' : 'var(--text-muted)' }}>{tab.icon}</span>
                  <span className="text-xs font-medium flex-1">{tab.label}</span>
                </button>
              );
            })}
          </aside>

          {/* Main content */}
          <main className="min-w-0">
            {activeTab === 'profile' && <ProfileSection player={player} />}
            {activeTab === 'messages' && <MessagesSection playerId={player.id} />}
            {activeTab === 'notifications' && <NotificationsSection playerId={player.id} />}
            {activeTab === 'activity' && <ActivitySection playerId={player.id} />}
            {activeTab === 'orders' && <OrdersSection playerId={player.id} />}
            {activeTab === 'status' && <StatusSection playerId={player.id} />}
            {activeTab === 'specialists' && <SpecialistsPlayerPanel playerId={player.id} />}
            {activeTab === 'garage' && <GarageRentalsPanel />}
          </main>
        </div>
      </div>
    </div>
  );
}

// ==========================================
// PROFILE
// ==========================================
function ProfileSection({ player }: { player: PlayerProfile }) {
  const { refreshAuth } = useAuth();
  const [editMode, setEditMode] = useState(false);
  const [saving, setSaving] = useState(false);
  const [saveError, setSaveError] = useState<string | null>(null);
  const [saveSuccess, setSaveSuccess] = useState(false);

  // Editable fields
  const [editUsername, setEditUsername] = useState(player.username);
  const [editLanguage, setEditLanguage] = useState(player.language || 'fr');

  const handleSave = useCallback(async () => {
    setSaving(true);
    setSaveError(null);
    setSaveSuccess(false);
    try {
      await api.player.updateProfile(player.id, {
        username: editUsername,
        language: editLanguage,
      });
      setSaveSuccess(true);
      setEditMode(false);
      // Refresh auth to get updated player data in the store
      await refreshAuth();
      setTimeout(() => setSaveSuccess(false), 3000);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Erreur lors de la sauvegarde';
      setSaveError(message);
    } finally {
      setSaving(false);
    }
  }, [player.id, editUsername, editLanguage, refreshAuth]);

  const handleToggleEdit = () => {
    if (editMode) {
      handleSave();
    } else {
      setEditUsername(player.username);
      setEditLanguage(player.language || 'fr');
      setSaveError(null);
      setSaveSuccess(false);
      setEditMode(true);
    }
  };

  const profileFields = [
    { label: 'Pseudo', value: editMode ? editUsername : player.username, editable: true, key: 'username' },
    { label: 'Email', value: player.email, editable: false, key: 'email' },
    { label: 'Langue', value: editMode ? getLanguageLabel(editLanguage) : getLanguageLabel(player.language), editable: true, key: 'language' },
    { label: 'Inscription', value: formatMemberSince(player.created_at), editable: false, key: 'created_at' },
  ];

  return (
    <div className="space-y-4">
      <SectionHeader title="Mon Profil" />

      {/* Avatar + upload */}
      <div className="flex items-center gap-4 mb-2">
        <div className="relative group">
          <PlayerAvatar username={player.username} profileImageUrl={player.profile_image_url} size="lg" />
          <label className="absolute inset-0 rounded-full flex items-center justify-center cursor-pointer opacity-0 group-hover:opacity-100 transition-opacity" style={{ background: 'rgba(0,0,0,0.6)' }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>
            </svg>
            <input type="file" accept="image/*" className="hidden" />
          </label>
        </div>
        <div>
          <p className="text-sm font-bold" style={{ color: 'var(--text-primary)' }}>{player.username}</p>
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Survolez l&apos;avatar pour changer la photo</p>
        </div>
      </div>

      <div className="card-bright p-5 space-y-4">
        {profileFields.map((field) => (
          <div key={field.key} className="flex items-center justify-between py-2" style={{ borderBottom: '1px solid var(--border-dark)' }}>
            <div className="flex-1">
              <span className="text-[10px] uppercase tracking-wider" style={{ color: 'var(--text-muted)' }}>{field.label}</span>
              {editMode && field.editable && field.key === 'username' ? (
                <input
                  type="text"
                  value={editUsername}
                  onChange={(e) => setEditUsername(e.target.value)}
                  className="block w-full mt-1 px-2 py-1 rounded text-sm font-medium"
                  style={{ background: 'var(--bg-card)', border: '1px solid var(--border-medium)', color: 'var(--text-primary)' }}
                />
              ) : editMode && field.editable && field.key === 'language' ? (
                <select
                  value={editLanguage}
                  onChange={(e) => setEditLanguage(e.target.value)}
                  className="block w-full mt-1 px-2 py-1 rounded text-sm font-medium"
                  style={{ background: 'var(--bg-card)', border: '1px solid var(--border-medium)', color: 'var(--text-primary)' }}
                >
                  <option value="fr">Français</option>
                  <option value="en">English</option>
                  <option value="es">Español</option>
                  <option value="de">Deutsch</option>
                  <option value="it">Italiano</option>
                  <option value="pt">Português</option>
                </select>
              ) : (
                <p className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>{field.value}</p>
              )}
            </div>
            {field.editable && editMode && field.key !== 'username' && field.key !== 'language' && (
              <button className="p-1.5 rounded hover:bg-white/5" style={{ color: 'var(--text-muted)' }}>
                <IconEdit />
              </button>
            )}
          </div>
        ))}
      </div>

      {saveError && (
        <div className="text-xs px-3 py-2 rounded-lg" style={{ background: 'rgba(196,30,30,0.1)', color: 'var(--color-red-light)' }}>
          {saveError}
        </div>
      )}
      {saveSuccess && (
        <div className="text-xs px-3 py-2 rounded-lg" style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>
          Profil mis à jour avec succès.
        </div>
      )}

      <div className="flex items-center gap-3 flex-wrap">
        <button onClick={handleToggleEdit} disabled={saving} className="btn-gold px-4 py-2 text-xs" style={{ opacity: saving ? 0.6 : 1 }}>
          {saving ? 'Sauvegarde...' : editMode ? 'Sauvegarder' : 'Modifier mon profil'}
        </button>
        <button className="btn-ghost px-4 py-2 text-xs">Changer le mot de passe</button>
        <button
          className="px-4 py-2 text-xs font-bold rounded-lg transition-all hover:scale-105"
          style={{ background: 'rgba(196,30,30,0.1)', border: '1px solid rgba(196,30,30,0.3)', color: 'var(--color-red-light)' }}
        >
          Supprimer mon compte
        </button>
      </div>
      <p className="text-[10px]" style={{ color: 'var(--text-faint)' }}>
        La suppression de compte nécessite une confirmation par e-mail.
      </p>
    </div>
  );
}

// ==========================================
// MESSAGES
// ==========================================
function MessagesSection({ playerId }: { playerId: string }) {
  const [messages, setMessages] = useState<MessageData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [openMsg, setOpenMsg] = useState<string | null>(null);
  const [replyText, setReplyText] = useState('');
  const [sending, setSending] = useState(false);

  const fetchMessages = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await api.player.getMessages(playerId) as MessageData[];
      setMessages(Array.isArray(data) ? data : []);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Impossible de charger les messages';
      setError(message);
    } finally {
      setLoading(false);
    }
  }, [playerId]);

  useEffect(() => { fetchMessages(); }, [fetchMessages]);

  const handleMarkRead = useCallback(async (msgId: string) => {
    try {
      await api.player.markMessageRead(playerId, msgId);
      setMessages(prev => prev.map(m => m.id === msgId ? { ...m, is_read: true } : m));
    } catch { /* silent */ }
  }, [playerId]);

  const selectedMsg = messages.find(m => m.id === openMsg);

  const handleSendReply = async () => {
    if (!replyText.trim() || !selectedMsg) return;
    setSending(true);
    try {
      await api.player.sendMessage(playerId, {
        recipient_id: selectedMsg.sender_id,
        subject: `Re: ${selectedMsg.subject}`,
        content: replyText.trim(),
      });
      setReplyText('');
      await fetchMessages();
    } catch { /* silent */ }
    setSending(false);
  };

  if (loading) return <LoadingSpinner text="Chargement des messages..." />;
  if (error) return <ErrorDisplay message={error} onRetry={fetchMessages} />;

  const unreadCount = messages.filter(m => !m.is_read).length;

  if (selectedMsg) {
    // Mark as read on open
    if (!selectedMsg.is_read) handleMarkRead(selectedMsg.id);

    return (
      <div className="space-y-3">
        <button
          onClick={() => { setOpenMsg(null); setReplyText(''); }}
          className="flex items-center gap-1.5 text-xs transition-colors hover:opacity-80"
          style={{ color: 'var(--color-gold)' }}
        >
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 19-7-7 7-7"/><path d="M19 12H5"/></svg>
          Retour aux messages
        </button>

        <div className="card-bright p-5">
          <div className="flex items-center gap-3 mb-4">
            <div className="w-10 h-10 rounded-full flex items-center justify-center text-xs font-bold" style={{ background: 'rgba(196,30,30,0.15)', color: 'var(--color-red-light)' }}>
              {(selectedMsg.sender?.username || '?')[0]}
            </div>
            <div>
              <span className="text-sm font-bold" style={{ color: 'var(--color-gold)' }}>{selectedMsg.sender?.username || 'Inconnu'}</span>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{formatTimeAgo(selectedMsg.created_at)}</p>
            </div>
          </div>
          <h4 className="text-sm font-bold mb-3" style={{ color: 'var(--text-primary)' }}>{selectedMsg.subject}</h4>
          <div className="text-xs leading-relaxed whitespace-pre-wrap" style={{ color: 'var(--text-secondary)' }}>
            {selectedMsg.content}
          </div>

          {/* Reply box */}
          <div className="mt-4 pt-4" style={{ borderTop: '1px solid var(--border-dark)' }}>
            <textarea
              value={replyText}
              onChange={(e) => setReplyText(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSendReply(); } }}
              placeholder="Écrire une réponse..."
              rows={3}
              className="w-full p-3 rounded-lg text-xs resize-none"
              style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
            />
            <div className="flex items-center justify-between mt-2">
              <span className="text-[10px]" style={{ color: 'var(--text-faint)' }}>Entrée pour envoyer, Shift+Entrée pour sauter une ligne</span>
              <button
                onClick={handleSendReply}
                disabled={!replyText.trim() || sending}
                className="btn-primary px-4 py-2 text-xs transition-opacity"
                style={{ opacity: !replyText.trim() || sending ? 0.5 : 1 }}
              >
                {sending ? 'Envoi...' : 'Envoyer'}
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <SectionHeader title="Mes Messages" count={unreadCount} />
      {messages.length === 0 && (
        <p className="text-xs text-center py-8" style={{ color: 'var(--text-muted)' }}>Aucun message pour le moment.</p>
      )}
      {messages.map((msg) => (
        <button
          key={msg.id}
          onClick={() => setOpenMsg(msg.id)}
          className="w-full text-left flex items-center gap-3 p-3 rounded-lg cursor-pointer transition-all hover:translate-x-1"
          style={{
            background: msg.is_read ? 'var(--bg-card)' : 'var(--bg-elevated)',
            border: msg.is_read ? '1px solid var(--border-dark)' : '1px solid var(--border-medium)',
          }}
        >
          <div className="w-9 h-9 rounded-full flex items-center justify-center text-[10px] font-bold flex-shrink-0" style={{ background: 'rgba(196,30,30,0.15)', color: 'var(--color-red-light)' }}>
            {(msg.sender?.username || '?')[0]}
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2">
              {!msg.is_read && <span className="w-2 h-2 rounded-full flex-shrink-0" style={{ background: 'var(--color-red)' }} />}
              <span className="text-xs font-bold truncate" style={{ color: 'var(--color-gold)' }}>{msg.sender?.username || 'Inconnu'}</span>
            </div>
            <p className="text-xs truncate" style={{ color: 'var(--text-secondary)' }}>{msg.subject}</p>
          </div>
          <span className="text-[10px] flex-shrink-0 flex items-center gap-1" style={{ color: 'var(--text-muted)' }}>
            <IconClock />{formatTimeAgo(msg.created_at)}
          </span>
        </button>
      ))}
    </div>
  );
}

// ==========================================
// NOTIFICATIONS
// ==========================================
function NotificationsSection({ playerId }: { playerId: string }) {
  const [notifications, setNotifications] = useState<NotificationData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchNotifications = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await api.player.getNotifications(playerId) as NotificationData[];
      setNotifications(Array.isArray(data) ? data : []);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Impossible de charger les notifications';
      setError(message);
    } finally {
      setLoading(false);
    }
  }, [playerId]);

  useEffect(() => { fetchNotifications(); }, [fetchNotifications]);

  const handleMarkAllRead = useCallback(async () => {
    try {
      await api.player.markAllNotificationsRead(playerId);
      setNotifications(prev => prev.map(n => ({ ...n, is_read: true })));
    } catch { /* silent */ }
  }, [playerId]);

  const handleMarkRead = useCallback(async (nid: string) => {
    try {
      await api.player.markNotificationRead(playerId, nid);
      setNotifications(prev => prev.map(n => n.id === nid ? { ...n, is_read: true } : n));
    } catch { /* silent */ }
  }, [playerId]);

  const typeColors: Record<string, string> = {
    deal: 'var(--color-gold)', forum: '#60a5fa', marketplace: '#22c55e',
    shop: 'var(--color-red-light)', message: '#a78bfa', system: 'var(--text-muted)',
  };

  if (loading) return <LoadingSpinner text="Chargement des notifications..." />;
  if (error) return <ErrorDisplay message={error} onRetry={fetchNotifications} />;

  const unreadCount = notifications.filter(n => !n.is_read).length;

  return (
    <div className="space-y-2">
      <div className="flex items-center justify-between">
        <SectionHeader title="Notifications" count={unreadCount} />
        {unreadCount > 0 && (
          <button onClick={handleMarkAllRead} className="text-[10px] hover:underline" style={{ color: 'var(--color-gold)' }}>
            Tout marquer comme lu
          </button>
        )}
      </div>
      {notifications.length === 0 && (
        <p className="text-xs text-center py-8" style={{ color: 'var(--text-muted)' }}>Aucune notification.</p>
      )}
      {notifications.map((n) => (
        <div
          key={n.id}
          onClick={() => !n.is_read && handleMarkRead(n.id)}
          className="flex items-start gap-3 p-3 rounded-lg cursor-pointer transition-all hover:translate-x-0.5"
          style={{
            background: n.is_read ? 'var(--bg-card)' : 'var(--bg-elevated)',
            border: n.is_read ? '1px solid var(--border-dark)' : '1px solid var(--border-medium)',
          }}
        >
          <span className="w-2 h-2 rounded-full mt-1.5 flex-shrink-0" style={{ background: typeColors[n.type] || 'var(--text-muted)' }} />
          <div className="flex-1 min-w-0">
            <p className="text-xs" style={{ color: n.is_read ? 'var(--text-muted)' : 'var(--text-secondary)' }}>{n.text}</p>
            <span className="text-[10px] flex items-center gap-1 mt-1" style={{ color: 'var(--text-muted)' }}>
              <IconClock />{formatTimeAgo(n.created_at)}
            </span>
          </div>
        </div>
      ))}
    </div>
  );
}

// ==========================================
// ACTIVITY
// ==========================================
function ActivitySection({ playerId }: { playerId: string }) {
  const [activity, setActivity] = useState<ActivityData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAll, setShowAll] = useState(false);
  const INITIAL_COUNT = 5;

  const fetchActivity = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await api.player.getActivity(playerId) as ActivityData[];
      setActivity(Array.isArray(data) ? data : []);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Impossible de charger l\'activité';
      setError(message);
    } finally {
      setLoading(false);
    }
  }, [playerId]);

  useEffect(() => { fetchActivity(); }, [fetchActivity]);

  if (loading) return <LoadingSpinner text="Chargement de l'activité..." />;
  if (error) return <ErrorDisplay message={error} onRetry={fetchActivity} />;

  const sectionColors: Record<string, { bg: string; text: string }> = {
    forum: { bg: 'rgba(96,165,250,0.12)', text: '#60a5fa' },
    marketplace: { bg: 'rgba(34,197,94,0.12)', text: '#22c55e' },
    shop: { bg: 'rgba(196,30,30,0.12)', text: 'var(--color-red-light)' },
    game: { bg: 'rgba(167,139,250,0.12)', text: '#a78bfa' },
  };

  const visibleItems = showAll ? activity : activity.slice(0, INITIAL_COUNT);
  const hasMore = activity.length > INITIAL_COUNT;

  return (
    <div className="space-y-2">
      <SectionHeader title="Mon Activité" />
      {activity.length === 0 && (
        <p className="text-xs text-center py-8" style={{ color: 'var(--text-muted)' }}>Aucune activité récente.</p>
      )}
      {visibleItems.map((a) => {
        const sectionKey = (a.section || 'game').toLowerCase();
        const colors = sectionColors[sectionKey] || sectionColors.game;
        return (
          <div key={a.id} className="flex items-center gap-3 p-3 rounded-lg" style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}>
            <span className="px-2 py-0.5 rounded text-[9px] font-bold" style={{ background: colors.bg, color: colors.text }}>
              {a.section || 'Jeu'}
            </span>
            <p className="text-xs flex-1 truncate" style={{ color: 'var(--text-secondary)' }}>{a.action}{a.details ? ` — ${a.details}` : ''}</p>
            <span className="text-[10px] flex-shrink-0" style={{ color: 'var(--text-muted)' }}>{formatTimeAgo(a.created_at)}</span>
          </div>
        );
      })}
      {hasMore && (
        <button
          onClick={() => setShowAll(!showAll)}
          className="btn-ghost px-4 py-2 text-xs w-full mt-2"
        >
          {showAll ? 'Voir moins' : `Voir plus (${activity.length - INITIAL_COUNT} restants)`}
        </button>
      )}
    </div>
  );
}

// ==========================================
// ORDERS
// ==========================================
function OrdersSection({ playerId }: { playerId: string }) {
  const [orders, setOrders] = useState<OrderData[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAll, setShowAll] = useState(false);
  const INITIAL_COUNT = 3;

  const fetchOrders = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const data = await api.player.getOrders(playerId) as OrderData[];
      setOrders(Array.isArray(data) ? data : []);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Impossible de charger les commandes';
      setError(message);
    } finally {
      setLoading(false);
    }
  }, [playerId]);

  useEffect(() => { fetchOrders(); }, [fetchOrders]);

  if (loading) return <LoadingSpinner text="Chargement des commandes..." />;
  if (error) return <ErrorDisplay message={error} onRetry={fetchOrders} />;

  const statusColors: Record<string, string> = {
    'delivered': '#22c55e', 'livré': '#22c55e',
    'processing': 'var(--color-gold)', 'en_cours': 'var(--color-gold)',
    'pending': '#60a5fa', 'en_preparation': '#60a5fa',
    'cancelled': 'var(--color-red-light)', 'annulé': 'var(--color-red-light)',
  };

  const statusLabels: Record<string, string> = {
    'delivered': 'Livré', 'livré': 'Livré',
    'processing': 'En cours', 'en_cours': 'En cours',
    'pending': 'En préparation', 'en_preparation': 'En préparation',
    'cancelled': 'Annulé', 'annulé': 'Annulé',
  };

  const visibleOrders = showAll ? orders : orders.slice(0, INITIAL_COUNT);
  const hasMore = orders.length > INITIAL_COUNT;

  return (
    <div className="space-y-3">
      <SectionHeader title="Mes Commandes" />
      {orders.length === 0 && (
        <p className="text-xs text-center py-8" style={{ color: 'var(--text-muted)' }}>Aucune commande pour le moment.</p>
      )}
      {visibleOrders.map((o) => {
        const statusKey = o.status.toLowerCase();
        const color = statusColors[statusKey] || '#666';
        const label = statusLabels[statusKey] || o.status;
        return (
          <div key={o.id} className="p-4 rounded-lg" style={{ background: 'var(--bg-card)', border: '1px solid var(--border-dark)' }}>
            <div className="flex items-center justify-between mb-2">
              <span className="text-[10px] font-mono" style={{ color: 'var(--text-muted)' }}>{o.id.substring(0, 8)}</span>
              <span className="px-2 py-0.5 rounded text-[9px] font-bold" style={{ background: color + '15', color }}>
                {label}
              </span>
            </div>
            <p className="text-sm font-medium" style={{ color: 'var(--text-primary)' }}>{o.items}</p>
            <div className="flex items-center justify-between mt-2">
              <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{formatDateShort(o.created_at)}</span>
              <span className="text-sm font-bold" style={{ color: 'var(--color-gold)' }}>{o.total}&euro;</span>
            </div>
          </div>
        );
      })}
      {hasMore && (
        <button
          onClick={() => setShowAll(!showAll)}
          className="btn-ghost px-4 py-2 text-xs w-full mt-2"
        >
          {showAll ? 'Voir moins' : `Voir plus (${orders.length - INITIAL_COUNT} restantes)`}
        </button>
      )}
    </div>
  );
}

// ==========================================
// STATUS (Gauges) — fetched from API
// ==========================================

const GAUGE_CONFIG: Record<string, { label: string; color: string }> = {
  fortune: { label: 'Fortune', color: 'var(--color-gold)' },
  pouvoir: { label: 'Pouvoir', color: 'var(--color-red-light)' },
  chaleur: { label: 'Chaleur', color: '#ef4444' },
  conscience: { label: 'Conscience', color: '#60a5fa' },
  respect: { label: 'Respect', color: 'var(--color-gold)' },
  social: { label: 'Social', color: '#22c55e' },
  popularite: { label: 'Popularité', color: '#a78bfa' },
  instabilite: { label: 'Instabilité', color: '#f59e0b' },
  influence: { label: 'Influence', color: '#ec4899' },
  ecologie: { label: 'Écologie', color: '#22c55e' },
  physical_health: { label: 'Santé Physique', color: '#4ade80' },
};

function StatusSection({ playerId }: { playerId: string }) {
  const [gauges, setGauges] = useState<GaugesData | null>(null);
  const [loadingGauges, setLoadingGauges] = useState(true);
  const [gaugesError, setGaugesError] = useState<string | null>(null);

  const fetchGauges = useCallback(async () => {
    setLoadingGauges(true);
    setGaugesError(null);
    try {
      // Phase 8 v2 (2026-05-01) — Fetch parallèle gauges + health pour
      // injecter physical_health dans le data unifié rendu côté UI.
      const [data, healthData] = await Promise.all([
        api.player.getGauges(playerId) as Promise<GaugesData>,
        api.player.getHealth(playerId).catch(() => null) as Promise<{ physical_health?: number } | null>,
      ]);
      // Injecte physical_health depuis PlayerHealth (single source)
      // au lieu de gauges.sante_physique (legacy).
      const merged: GaugesData = {
        ...data,
        physical_health: Number(healthData?.physical_health ?? 100),
      };
      setGauges(merged);
    } catch (err: unknown) {
      const message = err instanceof Error ? err.message : 'Impossible de charger les jauges';
      setGaugesError(message);
    } finally {
      setLoadingGauges(false);
    }
  }, [playerId]);

  useEffect(() => {
    fetchGauges();
  }, [fetchGauges]);

  if (loadingGauges) {
    return <LoadingSpinner text="Chargement des jauges..." />;
  }

  if (gaugesError) {
    return <ErrorDisplay message={gaugesError} onRetry={fetchGauges} />;
  }

  // Build gauge items from the fetched data
  const gaugeItems = gauges
    ? Object.entries(GAUGE_CONFIG)
        .filter(([key]) => gauges[key] !== undefined)
        .map(([key, config]) => ({
          name: config.label,
          value: gauges[key],
          color: config.color,
        }))
    : [];

  return (
    <div className="space-y-4">
      <SectionHeader title="Mes Personnages" />
      <div className="card-bright p-5">
        <div className="grid gap-3">
          {gaugeItems.length === 0 && (
            <p className="text-xs text-center py-4" style={{ color: 'var(--text-muted)' }}>
              Aucune jauge disponible pour le moment.
            </p>
          )}
          {gaugeItems.map((g) => (
            <div key={g.name}>
              <div className="flex justify-between items-center mb-1">
                <span className="text-xs font-medium" style={{ color: 'var(--text-secondary)' }}>{g.name}</span>
                <span className="text-[10px] font-mono font-bold" style={{ color: g.color }}>{g.value}/100</span>
              </div>
              <div className="h-2 rounded-full overflow-hidden" style={{ background: 'var(--bg-card)' }}>
                <div
                  className="h-full rounded-full transition-all duration-700"
                  style={{ width: `${g.value}%`, background: `linear-gradient(90deg, ${g.color}80, ${g.color})` }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Stats summary */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: 'Tier Crime', value: '2', color: 'var(--color-red-light)' },
          { label: 'Tier Politique', value: '0', color: 'var(--color-gold)' },
          { label: 'Tier Légal', value: '1', color: '#22c55e' },
          { label: 'XP Total', value: '1,240', color: '#a78bfa' },
        ].map(s => (
          <div key={s.label} className="card-dark p-3 text-center">
            <div className="text-lg font-bold font-mono" style={{ color: s.color }}>{s.value}</div>
            <div className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{s.label}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ==========================================
// Shared
// ==========================================
function SectionHeader({ title, count }: { title: string; count?: number }) {
  return (
    <div className="flex items-center gap-2 mb-2">
      <h3 className="font-impact text-sm" style={{ color: 'var(--color-gold)' }}>{title}</h3>
      {count !== undefined && count > 0 && (
        <span className="px-1.5 py-0.5 rounded-full text-[9px] font-bold" style={{ background: 'var(--color-red)', color: 'white' }}>{count}</span>
      )}
    </div>
  );
}
