<?php 
session_start();
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once 'config.php';
require_once 'functions.php';

// --- 1. LOGIQUE DE CONNEXION ---
if (isset($_POST['join_by_code'])) {
    $code = strtoupper(trim(htmlspecialchars($_POST['circle_code'])));
    $stmtCode = $pdo->prepare("SELECT id, name, oracle_id, creator_id FROM circles WHERE invite_code = ?");
    $stmtCode->execute([$code]);
    $foundCircle = $stmtCode->fetch();
    if ($foundCircle) {
        $newCircleId = (int)$foundCircle['id'];
        if (!empty($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0) {
            $reqUserId = (int)$_SESSION['user_id'];
            // Créer la table si besoin
            try { $pdo->exec("CREATE TABLE IF NOT EXISTS circle_join_requests (
                id INT AUTO_INCREMENT PRIMARY KEY,
                circle_id INT NOT NULL,
                user_id INT NOT NULL,
                status ENUM('pending','approved','refused') DEFAULT 'pending',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                reviewed_at TIMESTAMP NULL,
                UNIQUE KEY uniq_req (circle_id, user_id)
            )"); } catch(Exception $e) {}
            // Déjà membre?
            try {
                $alreadyMember = $pdo->prepare("SELECT COUNT(*) FROM circle_members WHERE circle_id=? AND user_id=?");
                $alreadyMember->execute([$newCircleId, $reqUserId]);
                if ((int)$alreadyMember->fetchColumn() > 0) {
                    $success = "Tu es déjà membre du cercle <strong>" . htmlspecialchars($foundCircle['name']) . "</strong>.";
                } else {
                    // Demande déjà en attente?
                    $alreadyReq = $pdo->prepare("SELECT status FROM circle_join_requests WHERE circle_id=? AND user_id=?");
                    $alreadyReq->execute([$newCircleId, $reqUserId]);
                    $existingReq = $alreadyReq->fetch();
                    if ($existingReq && $existingReq['status'] === 'pending') {
                        $success = "⏳ Ta demande pour <strong>" . htmlspecialchars($foundCircle['name']) . "</strong> est déjà en attente d'approbation.";
                    } elseif ($existingReq && $existingReq['status'] === 'refused') {
                        $error = "Ta demande pour ce cercle a été refusée.";
                    } else {
                        // Créer la demande
                        $pdo->prepare("INSERT INTO circle_join_requests (circle_id, user_id, status) VALUES (?,?,'pending') ON DUPLICATE KEY UPDATE status='pending', created_at=NOW()")
                            ->execute([$newCircleId, $reqUserId]);
                        // Notifier l'Oracle ou le créateur
                        $notifyId = (int)($foundCircle['oracle_id'] ?: $foundCircle['creator_id']);
                        if ($notifyId) {
                            $reqUser = $pdo->prepare("SELECT username FROM users WHERE id=?");
                            $reqUser->execute([$reqUserId]);
                            $reqName = $reqUser->fetchColumn() ?: 'Un membre';
                            addNotification($pdo, $notifyId,
                                "$reqName demande à rejoindre le cercle " . htmlspecialchars($foundCircle['name']),
                                "gestion_cercle.php?circle_id=$newCircleId"
                            );
                        }
                        $success = "✓ Demande envoyée ! L'Oracle du cercle <strong>" . htmlspecialchars($foundCircle['name']) . "</strong> doit approuver ta demande.";
                    }
                }
            } catch(Exception $e) { $error = "Erreur: " . $e->getMessage(); }
        } else {
            // Visiteur non connecté: accès lecture seule
            $_SESSION['user_id']     = 0;
            $_SESSION['auth_method'] = 'code';
            $_SESSION['circle_id']   = $newCircleId;
            $_SESSION['visitor_circle_name'] = $foundCircle['name'];
            header("Location: index.php"); exit;
        }
    } else {
        $error = "Code invalide. Vérifie avec l'Oracle de ton cercle.";
    }
}

// Vérifier cookie remember me (sauf si l'user est en train de se déconnecter)
if (!isset($_GET['logout']) && !isset($_SESSION['user_id']) && !empty($_COOKIE['jg_remember'])) {
    try {
        $rStmt = $pdo->query("SELECT config_key,config_value FROM admin_config WHERE config_key LIKE 'remember_%'");
        foreach ($rStmt->fetchAll() as $row) {
            if ($row['config_value'] === $_COOKIE['jg_remember']) {
                $email = str_replace('remember_', '', $row['config_key']);
                $autoUser = $pdo->prepare("SELECT * FROM users WHERE email=?");
                $autoUser->execute([$email]);
                $autoRow = $autoUser->fetch();
                if ($autoRow) {
                    $_SESSION['user_id']     = $autoRow['id'];
                    $_SESSION['logged_in']   = true;
                    $_SESSION['circle_id']   = 1;
                    $_SESSION['auth_method'] = 'password'; // remember_me = full member
                }
                break;
            }
        }
    } catch(Exception $e) {}
}

if (isset($_POST['login_user'])) {
    $email    = htmlspecialchars($_POST['email']);
    $password = $_POST['password'];

    // Vérifier blocage IP brute force
    $clientIp = getClientIp();
    $blockMsg = checkLoginAttempts($pdo, $clientIp);
    if ($blockMsg) { $error = $blockMsg; }
    else {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $db_user = $stmt->fetch();

    if ($db_user && ($password === $db_user['password'] || password_verify($password, $db_user['password']))) {
        clearLoginAttempts($pdo, $clientIp);
        // Remember me - cookie 30 jours
        if (!empty($_POST['remember_me'])) {
            $token = bin2hex(random_bytes(32));
            setcookie('jg_remember', $token, time() + 86400*30, '/', '', false, true);
            try {
                $pdo->prepare("INSERT INTO admin_config (config_key,config_value) VALUES (?,?) ON DUPLICATE KEY UPDATE config_value=?")
                    ->execute(['remember_'.$_POST['email'], $token, $token]);
            } catch(Exception $e) {}
        }
        // Vérifier si code admin requis
        $isAdminLogin = (int)($db_user['admin'] ?? 0) === 1;
        if ($isAdminLogin) {
            try {
                $codeStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='admin_login_code'");
                $codeStmt->execute();
                $storedHash = $codeStmt->fetchColumn();
            } catch (Exception $e) { $storedHash = null; }

            if ($storedHash && strlen($storedHash) > 10) {
                // Code requis — stocker les infos temporairement et demander le code
                $_SESSION['pending_admin_id'] = $db_user['id'];
                $needAdminCode = true;
            } else {
                // Pas de code configuré — connexion directe
                $_SESSION['user_id']     = $db_user['id'];
                $_SESSION['auth_method'] = 'password';
                $_SESSION['circle_id']   = 1;
                header("Location: index.php"); exit;
            }
        } else {
            $_SESSION['user_id']     = $db_user['id'];
            $_SESSION['auth_method'] = 'password';
            header("Location: index.php"); exit;
        }
    } else { recordFailedLogin($pdo, $clientIp); $error = "Identifiants incorrects."; }
    } // fin else blockMsg
}

// Vérification du code admin
if (isset($_POST['verify_admin_code']) && isset($_SESSION['pending_admin_id'])) {
    $inputCode = $_POST['admin_code'] ?? '';
    try {
        $codeStmt = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='admin_login_code'");
        $codeStmt->execute();
        $storedHash = $codeStmt->fetchColumn();
    } catch (Exception $e) { $storedHash = null; }

    if ($storedHash && password_verify($inputCode, $storedHash)) {
        $_SESSION['user_id']     = $_SESSION['pending_admin_id'];
        $_SESSION['auth_method'] = 'password';
        unset($_SESSION['pending_admin_id']);
        header("Location: index.php"); exit;
    } else {
        $error = "Code admin incorrect.";
        $needAdminCode = true;
    }
}

$needAdminCode = $needAdminCode ?? false;
$success = $success ?? '';

if (isset($_GET['logout'])) {
    // Effacer le cookie remember_me
    if (!empty($_COOKIE['jg_remember'])) {
        try {
            // Supprimer toutes les clés remember_* liées à ce token
            $pdo->exec("DELETE FROM admin_config WHERE config_key LIKE 'remember_%' AND config_value='"
                .addslashes($_COOKIE['jg_remember'])."'");
        } catch(Exception $e) {}
        setcookie('jg_remember', '', time()-3600, '/', '', false, true);
    }
    session_unset();
    session_destroy();
    header("Location: index.php"); exit;
}

$isLoggedIn   = isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0;
$isVisitor    = isset($_SESSION['auth_method']) && $_SESSION['auth_method'] === 'code';
// Un membre connecté voit tous ses gages (pas juste mot de passe)
$isFullMember = $isLoggedIn;

// --- 2. ACTION : CRÉER UN DÉFI ---
if ($isLoggedIn && isset($_POST['action']) && $_POST['action'] === 'create_bet') {
    $desc       = trim($_POST['description'] ?? '');
    $amt        = max(1, min(50, (int)($_POST['amount'] ?? 1)));
    $isGlobal   = isset($_POST['is_global']) ? 1 : 0;
    $p2         = (!empty($_POST['parieur2_id']) && !$isGlobal) ? (int)$_POST['parieur2_id'] : null;
    $echeance   = !empty($_POST['echeance']) ? $_POST['echeance'] : null;
    $circleId   = $isGlobal ? null : ((int)($_SESSION['circle_id'] ?? 0) ?: null);
    $isFriendBet = isset($_POST['is_friend_bet']) ? 1 : 0;
    $honorPledge = isset($_POST['honor_pledge']) ? 1 : 0;

    // Gestion mise de jetons
    $walletStake = 0;
    if (!empty($_POST['use_wallet']) && !empty($_POST['wallet_stake'])) {
        try {
            $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS wallet_stake INT(11) DEFAULT 0");
            $walletStake = max(0, (int)$_POST['wallet_stake']);
            $myWalletNow = (int)$pdo->query("SELECT wallet_points FROM users WHERE id=" . (int)$_SESSION['user_id'])->fetchColumn();
            // Appliquer la limite max configurée
            $betMaxStake = (int)getWalletConfig($pdo, 'wallet_bet_max', 500);
            if ($walletStake > $betMaxStake) $walletStake = $betMaxStake;
            if ($walletStake > $myWalletNow) $walletStake = $myWalletNow;
        } catch (Exception $e) { $walletStake = 0; }
    }

    // Validation stricte
    $isGlobalBet = $isGlobal === 1;
    $p2Required  = !$isGlobalBet;

    // Vérifier limite gages actifs selon le grade
    $tierKey = match($user['tier']??'free') {'premium_plus'=>'premplus','premium'=>'premium','admin'=>'admin',default=>'free'};
    $maxBets = (int)getWalletConfig($pdo, 'limit_bets_'.$tierKey, match($tierKey){'admin'=>999,'premplus'=>200,'premium'=>50,default=>10});
    if (!isAdmin($user) && $maxBets < 999) {
        $activeBets = (int)$pdo->query("SELECT COUNT(*) FROM bets WHERE user_id=".(int)$_SESSION['user_id']." AND status IN ('pending','accepted')")->fetchColumn();
        if ($activeBets >= $maxBets) { $betError = "Limite de {$maxBets} gage(s) actif(s) atteinte pour votre forfait."; }
    }

    if (!$desc) {
        // Rien - ignore silencieux
    } elseif (!$echeance && !$isGlobalBet) {
        $betError = "La date d'échéance est obligatoire.";
    } elseif ($p2Required && !$p2) {
        $betError = "Le " . tr('terme_gageur') . ' 2 est obligatoire (ou cochez \'Gage ouvert\').";
    } elseif (isset($betError)) {
        // Erreur déjà définie
    }

    if ($desc && !isset($betError)) {
        // Ajouter colonne is_global si manquante
        if (!(bool)$pdo->query("SHOW COLUMNS FROM bets LIKE 'is_global'")->fetch()) {
            $pdo->exec("ALTER TABLE bets ADD COLUMN is_global TINYINT(1) DEFAULT 0");
        }
        try {
            $pdo->prepare("INSERT INTO bets (user_id, owner_id, circle_id, description, amount, status, parieur2_id, echeance, acceptance_status, is_global)
                           VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?)")
                ->execute([$_SESSION['user_id'], $_SESSION['user_id'], $circleId, $desc, $amt, $p2, $echeance, $p2 ? 'pending_p2' : null, $isGlobal]);
        } catch (Exception $e) {
            $pdo->prepare("INSERT INTO bets (user_id, owner_id, circle_id, description, amount, status, parieur2_id, echeance)
                           VALUES (?, ?, ?, ?, ?, 'pending', ?, ?)")
                ->execute([$_SESSION['user_id'], $_SESSION['user_id'], $circleId, $desc, $amt, $p2, $echeance]);
        }

        $newBetId = (int)$pdo->lastInsertId();

        // v1.7 — Sauvegarder reward_text pour les cercles privés
        if ($newBetId > 0 && !empty($_POST['reward_text'])) {
            try {
                $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS reward_text VARCHAR(255) DEFAULT NULL");
                $pdo->prepare("UPDATE bets SET reward_text=? WHERE id=?")->execute([trim($_POST['reward_text']), $newBetId]);
            } catch(Exception $e){}
        }
        if ($newBetId > 0) {
            try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS is_friend_bet TINYINT(1) DEFAULT 0"); } catch(Exception $e){}
            try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS honor_pledge TINYINT(1) DEFAULT 0"); } catch(Exception $e){}
            if ($isFriendBet || $honorPledge) {
                $pdo->prepare("UPDATE bets SET is_friend_bet=?, honor_pledge=? WHERE id=?")
                    ->execute([$isFriendBet, $honorPledge, $newBetId]);
            }
        }

        // Classifier le gage selon les mots-clés
        if ($newBetId > 0) classifyBet($newBetId, $desc, $pdo);

        // Débiter les jetons si mise
        if ($walletStake > 0 && $newBetId > 0) {
            try {
                $pdo->prepare("UPDATE bets SET wallet_stake=? WHERE id=?")->execute([$walletStake, $newBetId]);
                $pdo->prepare("UPDATE users SET wallet_points=wallet_points-? WHERE id=?")->execute([$walletStake, $_SESSION['user_id']]);
                $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description,ref_id) VALUES (?,?,?,?,?)")
                    ->execute([$_SESSION['user_id'], -$walletStake, 'bet_stake', "Mise sur gage #{$newBetId}", $newBetId]);
                // Notifier le parieur2 qu'il y a une mise
                if ($p2) addNotification($pdo, $p2, "Un gage avec {$walletStake} jetons en jeu t'attend !", "index.php");
            } catch (Exception $e) {}
        }

        if ($p2) {
            $uN = $pdo->prepare("SELECT username FROM users WHERE id=?");
            $uN->execute([$_SESSION['user_id']]);
            $uName = $uN->fetchColumn() ?: 'Quelqu\'un';
            addNotification($pdo, $p2, "{$uName} t'a lance un gage : \"{$desc}\" - Acceptes-tu ?", "index.php");

            // Envoyer email au parieur2
            require_once 'send_bet_email.php';
            sendBetEmail($pdo, $newBetId, $_SESSION['user_id'], $p2);
        }
    }
    header("Location: index.php"); exit;
}

$user = ['username' => 'Invité', 'points' => 0, 'tier' => 'standard', 'admin' => 0];
$isMinor = false;
if ($isLoggedIn) {
    $stmtUser = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmtUser->execute([$_SESSION['user_id']]);
    $userData = $stmtUser->fetch();
    if ($userData) { 
        $user = $userData; 
        $pdo->prepare("UPDATE users SET last_activity = NOW() WHERE id = ?")->execute([$_SESSION['user_id']]);
    }
}

if (!function_exists('getWalletConfig')) {
    function getWalletConfig($pdo, $key, $default = 0) {
        try {
            $s = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
            $s->execute([$key]);
            $v = $s->fetchColumn();
            return $v !== false ? $v : $default;
        } catch (Exception $e) { return $default; }
    }
}

$isAdmin = ($isLoggedIn && (int)($user['admin'] ?? 0) === 1);

// v1.7 — Détection mode cercle privé isolé
$activeCircleId  = (int)($_SESSION['circle_id'] ?? 0);
$privateCircle   = null;
$isIsolated      = false;   // membre d'un cercle privé isolé
$isOrganizer     = false;   // oracle/créateur du cercle privé
$groupType       = null;    // 'famille', 'ecole', 'entreprise'

// v1.7 — Flag utilisateur privé (inscrit comme famille/école/entreprise)
$isPrivateUser   = $isLoggedIn && !empty($user['is_private_user']);

if ($isLoggedIn && $activeCircleId) {
    $privateCircle = getPrivateCircleInfo($pdo, $activeCircleId);
    if ($privateCircle && !empty($privateCircle['is_isolated']) && !empty($privateCircle['group_type'])) {
        $isIsolated  = true;
        $groupType   = $privateCircle['group_type'];
        $isOrganizer = ((int)($privateCircle['oracle_id'] ?? 0) === (int)$_SESSION['user_id'])
                    || ((int)($privateCircle['creator_id'] ?? 0) === (int)$_SESSION['user_id'])
                    || $isAdmin;
    }
}
// Un utilisateur privé est toujours en mode isolé même sans cercle actif
if ($isPrivateUser) $isIsolated = true;

// v1.7 — Appliquer les termes fixes pour les comptes privés
if ($isIsolated && function_exists('applyPrivateTerms')) applyPrivateTerms();

// Définir les niveaux de forfait tôt pour tout le fichier
$userTierN  = match($user['tier'] ?? 'free') {
    'premium'      => 1,
    'premium_plus' => 2,
    'admin'        => 3,
    default        => 0
};
$isPremium  = $userTierN >= 1 || $isAdmin;
$isPremPlus = $userTierN >= 2 || $isAdmin;
$userTierStr = $user['tier'] ?? 'free';

// Droits dynamiques depuis admin_config (override possible par l'admin)
$canCreateBet   = $isLoggedIn && checkDroit($pdo, $userTierStr, 'create_bet');
$canWalletBet   = $isLoggedIn && !($isMinor??false) && checkDroit($pdo, $userTierStr, 'wallet_bet');
$canChatSend    = $isLoggedIn && checkDroit($pdo, $userTierStr, 'chat_send');
$canChatColor   = $isLoggedIn && checkDroit($pdo, $userTierStr, 'chat_color');
$canChatPhoto   = $isLoggedIn && checkDroit($pdo, $userTierStr, 'chat_photo');
$canUploadProof = $isLoggedIn && checkDroit($pdo, $userTierStr, 'upload_proof');
$canVoteBet     = checkDroit($pdo, $userTierStr, 'vote_bet');
$canPastilles   = $isLoggedIn && ($isPremium || checkDroit($pdo, $userTierStr, 'pastilles'));

// Mode interface: 'pastilles' ou 'complet'
// Les users avec droit pastilles peuvent choisir dans leur config
// Si ui_mode = 'complet' → afficher COL1+COL3+COL4 comme un Free (mode bureau complet)
try { $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS ui_mode ENUM('pastilles','complet') DEFAULT 'pastilles'"); } catch(Exception $e){}
$uiMode = $user['ui_mode'] ?? 'pastilles';
// Si l'user n'a pas le droit pastilles, il est toujours en mode complet
if (!$canPastilles) $uiMode = 'complet';
// Recalculer les variables de layout selon le mode choisi
$useOverlay  = ($canPastilles && $uiMode === 'pastilles'); // true = pastilles, false = colonnes complètes
$showCol1Full = !$useOverlay; // Afficher COL1 classements+events
// v1.7 — En mode isolé, masquer événements publics (garder classements du cercle)
$showEvents    = !$isIsolated;
$showPublicBets = !$isIsolated;
$showCol3    = !$useOverlay;  // Afficher COL3 chat
$showCol4    = !$useOverlay;  // Afficher COL4 amis

// Bonus journalier automatique à la connexion
if ($isLoggedIn && (int)($_SESSION['user_id'] ?? 0) > 0) {
    $today = date('Y-m-d');
    if (($user['last_daily_bonus'] ?? '') !== $today) {
        try {
            // Vérifier colonnes wallet
            $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS wallet_points INT(11) DEFAULT 0");
            $pdo->exec("ALTER TABLE users ADD COLUMN IF NOT EXISTS last_daily_bonus DATE DEFAULT NULL");
            $pdo->exec("CREATE TABLE IF NOT EXISTS wallet_transactions (
                id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                user_id INT(11) NOT NULL,
                amount INT(11) NOT NULL,
                type ENUM('daily_bonus','daily_roll','bet_win','bet_lose','purchase','admin_grant','bet_stake') NOT NULL,
                description VARCHAR(255) DEFAULT NULL,
                ref_id INT(11) DEFAULT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )");

            // Montant selon forfait
            $dailyAmt = match(true) {
                $isAdmin || ($user['tier'] ?? '') === 'premium_plus' => (int)getWalletConfig($pdo, 'wallet_daily_premplus', 200),
                ($user['tier'] ?? '') === 'premium'                  => (int)getWalletConfig($pdo, 'wallet_daily_premium', 150),
                default                                              => (int)getWalletConfig($pdo, 'wallet_daily_free', 100),
            };

            $pdo->prepare("UPDATE users SET wallet_points=wallet_points+?, last_daily_bonus=? WHERE id=?")
                ->execute([$dailyAmt, $today, (int)$_SESSION['user_id']]);
            $pdo->prepare("INSERT INTO wallet_transactions (user_id,amount,type,description) VALUES (?,?,?,?)")
                ->execute([(int)$_SESSION['user_id'], $dailyAmt, 'daily_bonus', "Bonus connexion du {$today}"]);

            $user['wallet_points']    = ($user['wallet_points'] ?? 0) + $dailyAmt;
            $user['last_daily_bonus'] = $today;
            $_SESSION['daily_bonus_today'] = $dailyAmt;
        } catch (Exception $e) {}
    }
}

// Vérification et attribution automatique des trophées
if ($isLoggedIn && (int)($_SESSION['user_id'] ?? 0) > 0) {
    try {
        $trophyLevels = $pdo->query("SELECT * FROM trophy_levels ORDER BY requirement_value ASC")->fetchAll();
        if (!empty($trophyLevels)) {
            $wonBetsT = (int)$pdo->query("SELECT COUNT(*) FROM bets WHERE user_id={$_SESSION['user_id']} AND status='won'")->fetchColumn();
            $totBetsT = (int)$pdo->query("SELECT COUNT(*) FROM bets WHERE user_id={$_SESSION['user_id']} AND status IN('won','lost')")->fetchColumn();
            $ratioT   = $totBetsT > 0 ? round($wonBetsT / $totBetsT * 100) : 0;
            $intPtsT  = (int)($user['interaction_points'] ?? 0);

            $pdo->exec("CREATE TABLE IF NOT EXISTS user_trophies (
                id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                user_id INT(11) NOT NULL,
                trophy_id INT(11) NOT NULL,
                awarded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                UNIQUE KEY unique_trophy (user_id, trophy_id)
            )");

            foreach ($trophyLevels as $t) {
                $ok = match($t['requirement_type'] ?? '') {
                    'win_count'   => $wonBetsT >= (int)$t['requirement_value'],
                    'win_percent' => $ratioT   >= (int)$t['requirement_value'],
                    'interaction' => $intPtsT  >= (int)$t['requirement_value'],
                    default       => false
                };
                if ($ok) {
                    $chk = $pdo->prepare("SELECT id FROM user_trophies WHERE user_id=? AND trophy_id=?");
                    $chk->execute([$_SESSION['user_id'], $t['id']]);
                    if (!$chk->fetch()) {
                        $pdo->prepare("INSERT IGNORE INTO user_trophies (user_id,trophy_id) VALUES (?,?)")
                            ->execute([$_SESSION['user_id'], $t['id']]);
                        addNotification($pdo, (int)$_SESSION['user_id'],
                            "Nouveau trophee debloque : " . ($t['title'] ?? 'Trophee'), "trophees.php");
                    }
                }
            }
        }
    } catch (Exception $e) {}
}

include 'header.php'; 
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/l10n/fr.js"></script>

<style>
.badge-gold { background: linear-gradient(45deg, #d4af37, #f1d592); color: #000; font-weight: bold; border: 1px solid #b8860b; }
.badge-silver { background: linear-gradient(45deg, #a9a9a9, #e0e0e0); color: #000; font-weight: bold; border: 1px solid #808080; }
.input-group-text { border-left: none !important; background-color: #000 !important; border-color: #6c757d !important; cursor: pointer; }
#loginPassword { border-right: none !important; }
.input-group-text:hover i { color: #fff !important; }

/* Flatpickr thème sombre */
.flatpickr-calendar { background:#1a1a2e !important; border:1px solid #0dcaf0 !important; border-radius:8px !important; }
.flatpickr-day { color:#ddd !important; }
.flatpickr-day:hover { background:#0dcaf0 !important; color:#000 !important; }
.flatpickr-day.selected { background:#0d6efd !important; border-color:#0d6efd !important; color:#fff !important; }
.flatpickr-day.today { border-color:#0dcaf0 !important; }
.flatpickr-months { background:#111 !important; border-radius:8px 8px 0 0 !important; }
.flatpickr-month, .flatpickr-weekday, .flatpickr-current-month { color:#fff !important; fill:#fff !important; }
.flatpickr-prev-month svg, .flatpickr-next-month svg { fill:#0dcaf0 !important; }
.flatpickr-day.disabled { color:#555 !important; }

/* Styles Classements Dynamiques */
.user-link { cursor: pointer; transition: 0.2s; text-decoration: none; }
.user-link:hover { color: #0d6efd !important; text-decoration: underline; }
.rank-select { background: #000; color: #fff; border: none; font-size: 0.70rem; padding: 2px; cursor: pointer; font-weight: bold; text-transform: uppercase; }

/* Section Amis */
.friends-col { width: 180px; min-width: 180px; flex-shrink: 0; transition: width 0.25s, min-width 0.25s; position:relative; display:flex; flex-direction:column; }

/* Alignement parfait des colonnes */
#col1Wrap, #col3Chat, .friends-col { padding-top: 0 !important; margin-top: 0 !important; }
#col1Wrap > .card, #col3Chat > .card, .friends-col > .card { margin-top: 0 !important; }
#col1Wrap > .card:first-of-type .card-header,
#col3Chat > .card:first-of-type .card-header,
.friends-col > .card:first-of-type .card-header { 
    height: 36px; 
    min-height: 36px;
    max-height: 36px;
    padding-top: 0;
    padding-bottom: 0;
    box-sizing: border-box;
}

/* Contenu caché quand colonne réduite */
.col-is-collapsed > *:not(.col-collapse-btn) { visibility: hidden; opacity: 0; }
.col-is-collapsed { overflow: hidden !important; }
.friend-item { border-bottom: 1px solid #222; transition: background 0.2s; cursor: pointer; }
.friend-item:hover { background: #1a1a1a; }
.status-indicator { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 5px; }
.online { background-color: #28a745; box-shadow: 0 0 5px #28a745; }
.offline { background-color: #6c757d; }

/* ── COLONNES COLLAPSIBLES (desktop) ──────────────────────────── */
.col-collapsed-left  { flex: 0 0 18px !important; min-width: 18px !important; width: 18px !important; overflow: hidden !important; }
.col-collapsed-right { flex: 0 0 18px !important; min-width: 18px !important; width: 18px !important; overflow: hidden !important; }
.col-collapse-btn {
    position: fixed; z-index: 100; top: 120px;
    background: rgba(13,202,240,0.15); border: 1px solid #0dcaf0; color: #0dcaf0;
    width: 18px; height: 48px; cursor: pointer; font-size: 0.6rem; line-height: 1;
    display: flex; align-items: center; justify-content: center;
    transition: background 0.2s; writing-mode: vertical-rl;
}
.col-collapse-btn:hover { background: rgba(13,202,240,0.3); }
.col1-collapse-btn { left: 0; border-radius: 0 6px 6px 0; }
.col3-collapse-btn { border-radius: 6px 0 0 6px; }
.col4-collapse-btn { right: 0; border-radius: 6px 0 0 6px; }

/* ── PASTILLE RETOUR EN HAUT (mobile) ───────────────────────── */
#scrollTopBtn {
    display: none;
    position: fixed;
    bottom: 20px;
    right: 16px;
    z-index: 8888;
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: #0dcaf0;
    color: #000;
    border: none;
    font-size: 1.2rem;
    cursor: pointer;
    box-shadow: 0 2px 12px rgba(13,202,240,0.5);
    align-items: center;
    justify-content: center;
}

/* ── MODE MOBILE ────────────────────────────────────────────── */
<?php
$mobileSep = 8;
try {
    $ms = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key='mobile_separation'");
    $ms->execute(); $msv = $ms->fetchColumn();
    if ($msv !== false) $mobileSep = (int)$msv;
} catch(Exception $e) {}
?>
@media (max-width: 767px) {
    /* Bloquer le scroll horizontal */
    html, body { overflow-x: hidden !important; max-width: 100vw !important; }

    /* Layout: empiler les colonnes au lieu de flex-nowrap */
    .d-flex.flex-nowrap { flex-wrap: wrap !important; gap: 0 !important; }

    /* Sur mobile: cacher les colonnes latérales */
    .desktop-only-col { display: none !important; }

    /* COL2 (gages) : pleine largeur */
    .flex-grow-1 {
        min-width: 100% !important;
        max-width: 100% !important;
        width: 100% !important;
        padding: 0 4px !important;
    }

    /* Container principal sans padding latéral */
    .container-fluid { padding-left: 4px !important; padding-right: 4px !important; }

    /* Cartes de gage: pleine largeur + séparation configurable */
    .gage-card { margin-left: 0 !important; margin-right: 0 !important; margin-bottom: <?= $mobileSep ?>px !important; }

    /* Formulaire de gage: adapté mobile */
    .col-5, .col-4, .col-3 { flex: 0 0 100% !important; max-width: 100% !important; }

    /* Barre profil compacte */
    #profilBar { flex-wrap: wrap; font-size: 0.65rem !important; }

    /* Fonts plus grandes sur mobile */
    .gage-card { font-size: 0.9rem !important; }
    .gage-card .text-white.mb-1.fw-bold { font-size: 1rem !important; line-height: 1.4 !important; }
    .gage-card .text-info.fw-bold { font-size: 0.82rem !important; }
    .gage-card .badge { font-size: 0.68rem !important; }
    .gage-card .btn-xs { font-size: 0.72rem !important; padding: 3px 7px !important; }

    /* Modale détail plein écran sur mobile */
    #betDetailCard {
        width: 100vw !important;
        max-width: 100vw !important;
        height: 100dvh !important;
        max-height: 100dvh !important;
        border-radius: 0 !important;
        position: fixed !important;
        top: 0 !important;
        left: 0 !important;
        right: 0 !important;
        bottom: 0 !important;
    }
    #betDetailOverlay { align-items: flex-start !important; padding: 0 !important; }
    #betDetailPanel { align-items: flex-start !important; padding: 0 !important; }
    #bdDesc { font-size: 1.05rem !important; }
    /* Indicateur swipe visible sur mobile */
    #betDetailCard .swipe-hint {
        display: flex !important;
        justify-content: center;
        padding: 12px 0 4px;
        color: #555;
        font-size: 0.72rem;
    }

    /* Panels pastilles : plein écran sur mobile */
    #dashPanelCard {
        width: 100vw !important;
        max-width: 100vw !important;
        height: 100dvh !important;
        max-height: 100dvh !important;
        margin: 0 !important;
        border-radius: 0 !important;
        border-left: none !important;
        border-right: none !important;
    }
    #dashPanelOverlay { background: #0a0a0a !important; }
    /* Chat dans le panel mobile - prendre toute la hauteur */
    #dashPanelBody { flex: 1 1 0; overflow-y: auto; min-height: 0; }
    #dashPanelBody #chatCardClone { height: 100% !important; min-height: 0 !important; flex: 1 !important; }
}
</style>

<div class="container-fluid mt-4">
    <?php if (!$isLoggedIn): ?>
        <!-- SECTION CONNEXION -->
        <div class="row justify-content-center mt-5">
            <div class="col-md-10 col-lg-8">
                <div class="row g-4 text-center">
                    <div class="col-md-6">
                        <div class="card bg-dark border-info shadow p-4 h-100">
                            <h3 class="oracle-text text-info mb-3">CODE CERCLE</h3>
                            <form method="POST">
                                <?php if (!empty($success)): ?>
                                <div class="alert alert-success py-2 mb-2 small"><?= $success ?></div>
                                <?php endif; ?>
                                <?php if (!empty($error)): ?>
                                <div class="alert alert-danger py-2 mb-2 small"><?= htmlspecialchars($error) ?></div>
                                <?php endif; ?>
                                <input type="text" name="circle_code" class="form-control bg-black text-white border-secondary mb-3 text-center" placeholder="EX: ORACLE2026">
                                <button type="submit" name="join_by_code" class="btn btn-info w-100 fw-bold">REJOINDRE</button>
                            </form>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card bg-dark border-primary shadow p-4 h-100">
                            <h3 class="oracle-text text-primary mb-3">MEMBRE</h3>

                            <?php if ($needAdminCode): ?>
                            <!-- Formulaire double vérification admin -->
                            <div class="alert alert-warning small py-2 mb-3">Verification admin requise</div>
                            <form method="POST">
                                <input type="password" name="admin_code" class="form-control bg-black text-white border-warning mb-3"
                                       placeholder="Code admin..." autofocus>
                                <button type="submit" name="verify_admin_code" class="btn btn-warning w-100 fw-bold">CONFIRMER</button>
                            </form>
                            <?php else: ?>
                            <form method="POST">
                                <input type="email" name="email" class="form-control bg-black text-white border-secondary mb-2" placeholder="Courriel">
                                <div class="input-group mb-3">
                                    <input type="password" name="password" id="loginPassword" class="form-control bg-black text-white border-secondary" placeholder="Mot de passe">
                                    <span class="input-group-text" id="togglePassword" style="cursor:pointer;" onclick="(function(){var f=document.getElementById('loginPassword'),i=document.getElementById('eyeIcon');if(f.type==='password'){f.type='text';i.classList.replace('fa-eye','fa-eye-slash');}else{f.type='password';i.classList.replace('fa-eye-slash','fa-eye');}})()"><i class="fa-solid fa-eye text-primary" id="eyeIcon"></i></span>
                                </div>
                                <div class="form-check mb-2" style="font-size:0.72rem;">
                                    <input class="form-check-input" type="checkbox" name="remember_me" id="rememberMe" value="1">
                                    <label class="form-check-label text-muted" for="rememberMe">Se souvenir de moi</label>
                                </div>
                                <button type="submit" name="login_user" class="btn btn-primary w-100 fw-bold mb-3">SE CONNECTER</button>
                                <div class="d-flex justify-content-between">
                                    <a href="register.php" class="text-info small fw-bold text-decoration-none">S'INSCRIRE</a>
                                    <a href="forgot_password.php" class="text-muted small text-decoration-none">MOT DE PASSE OUBLIÉ ?</a>
                                </div>
                            </form>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php else: ?>
        <div class="d-flex flex-nowrap gap-2" style="width:100%;overflow-x:hidden;align-items:stretch;">
            <!-- COL 1 : PROFIL & CLASSEMENTS -->
            <div id="col1Wrap" style="flex: 0 0 <?= $useOverlay ? "auto" : "280px" ?>; min-width: <?= $useOverlay ? "0" : "280px" ?>; position:relative; transition: flex 0.25s, width 0.25s, min-width 0.25s; overflow:hidden; display:flex; flex-direction:column; padding-top:0; margin-top:0;">
                <?php if (!$useOverlay): ?>
                <button class="col-collapse-btn col1-collapse-btn" id="col1CollapseBtn" onclick="toggleColCollapse('col1')" title="Réduire">◀</button>
                <?php endif; ?>

                <!-- PASTILLES: déplacées dans COL2 (Premium/Admin seulement) -->
                <?php if ($useOverlay): ?>
                <?php else: ?>
                <!-- Classements et Événements pour Free -->

                <div id="col1Classements" class="card bg-dark border-secondary shadow-sm" style="display:<?= $showCol1Full ? '' : 'none' ?>;">
                    <div class="card-header bg-primary text-white fw-bold small py-1 d-flex justify-content-between align-items-center" style="min-height:34px;">
                        <span style="font-size: 0.7rem;">CLASSEMENTS</span>
                        <div class="d-flex align-items-center gap-2">
                            <select id="rankType" class="rank-select">
                                <option value="points">Honneur</option>
                                <option value="gain_perte">Gain/Perte</option>
                                <option value="gages">Gages</option>
                                <?php if ($isIsolated): // v1.7 — engagements honorés pour cercles privés ?>
                                <option value="honores">Honorés</option>
                                <?php endif; ?>
                                <option value="interaction">Interactions</option>
                                <option value="fiable">Fiables</option>
                                <?php if (!$isMinor && !$isPrivateUser): ?>
                                <option value="wallet">Jetons</option>
                                <?php endif; ?>
                            </select>
                            <?php if ($isPremium || $isPremPlus || isAdmin($user)): ?>
                            <button onclick="toggleSection('classements')" id="toggle-classements"
                                    class="btn btn-xs py-0 btn-outline-light" style="font-size:0.55rem;line-height:1;">&#9660;</button>
                            <?php endif; ?>
                        </div>
                        <!-- v1.7 — Filtre période -->
                        <div class="d-flex gap-1 px-2 pb-1 pt-0">
                            <?php foreach (['all'=>'Tout','week'=>'Sem.','month'=>'Mois','year'=>'An'] as $pv => $pl): ?>
                            <button class="rank-period-btn" data-period="<?= $pv ?>" onclick="setRankPeriod('<?= $pv ?>')"
                                    style="background:none;border:1px solid #333;color:#aaa;border-radius:4px;padding:1px 6px;font-size:0.55rem;cursor:pointer;font-weight:<?= $pv==='all'?'700':'400' ?>;opacity:<?= $pv==='all'?'1':'0.45' ?>;">
                                <?= $pl ?>
                            </button>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <div id="section-classements">
                    <table class="table table-dark table-sm mb-0 small">
                        <tbody id="rankingTable"></tbody>
                    </table>
                    </div>
                </div>

                <!-- ÉVÉNEMENTS À VENIR -->
                <?php
                try {
                    $userLang = $user['language'] ?? 'CA-FR';
                    $stmtEv = $pdo->prepare("
                        SELECT * FROM events
                        WHERE is_active = 1
                          AND event_date >= NOW()
                          AND language = ?
                        ORDER BY importance DESC, event_date ASC
                        LIMIT 20
                    ");
                    $stmtEv->execute([$userLang]);
                    $events = $stmtEv->fetchAll();

                    // Grouper par date pour le calendrier
                    $eventsByDate = [];
                    foreach ($events as $ev) {
                        $dateKey = date('Y-m-d', strtotime($ev['event_date']));
                        $eventsByDate[$dateKey][] = $ev;
                    }
                    if (!empty($events)):
                ?>
                <div id="col1Evenements" class="card bg-dark border-secondary shadow-sm" style="display:<?= ($showCol1Full && $showEvents) ? '' : 'none' ?>;">
                    <div class="card-header py-1 d-flex align-items-center justify-content-between gap-1" style="background:#0d0d0d;">
                        <span class="small fw-bold text-warning" style="font-size:0.68rem;">EVENEMENTS</span>
                        <div class="d-flex gap-1">
                            <button onclick="setEvView('list')" id="evBtnList" class="btn btn-xs py-0 btn-warning" style="font-size:0.55rem;">Liste</button>
                            <button onclick="setEvView('cal')" id="evBtnCal" class="btn btn-xs py-0 btn-outline-warning" style="font-size:0.55rem;">Calendrier</button>
                        </div>
                    </div>

                    <!-- VUE LISTE -->
                    <div id="evViewList" class="p-1">
                    <?php foreach ($events as $ev):
                        $typeIcon = match($ev['type']) {
                            'sport'      => '🏒',
                            'artistique' => '🎭',
                            default      => '📍',
                        };
                        $impColor = match((int)$ev['importance']) {
                            3 => 'border-warning',
                            2 => 'border-info',
                            default => 'border-secondary',
                        };
                        $impBg = match((int)$ev['importance']) {
                            3 => 'background:#1a1500;',
                            2 => 'background:#001a20;',
                            default => 'background:#111;',
                        };
                        $dateStr  = date('d M', strtotime($ev['event_date']));
                        $heureStr = date('H:i', strtotime($ev['event_date']));
                    ?>
                    <div class="mb-1 p-2 rounded border <?= $impColor ?>" style="<?= $impBg ?>">
                        <div class="d-flex align-items-start gap-1">
                            <span style="font-size:0.85rem;line-height:1;"><?= $typeIcon ?></span>
                            <div style="min-width:0;flex:1;">
                                <div class="fw-bold" style="font-size:0.72rem;line-height:1.3;word-break:break-word;color:#fff;">
                                    <?php if (!empty($ev['url'])): ?>
                                        <a href="<?= htmlspecialchars($ev['url']) ?>" target="_blank" class="text-white text-decoration-none"><?= htmlspecialchars($ev['title']) ?></a>
                                    <?php else: ?>
                                        <?= htmlspecialchars($ev['title']) ?>
                                    <?php endif; ?>
                                    <?php if ((int)$ev['importance'] === 3): ?>
                                        <span class="badge bg-warning text-dark ms-1" style="font-size:0.5rem;vertical-align:middle;">★</span>
                                    <?php endif; ?>
                                </div>
                                <div style="font-size:0.65rem;color:#aaa;margin-top:2px;">
                                    <?= $dateStr ?> a <?= $heureStr ?>
                                    <?php if (!empty($ev['location'])): ?>
                                        · <?= htmlspecialchars(mb_substr($ev['location'], 0, 28)) ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <!-- Bouton Gage rapide -->
                            <?php if ($isFullMember): ?>
                            <button onclick="gageRapide('<?= htmlspecialchars(addslashes($ev['title'])) ?>')"
                                    class="btn btn-outline-warning btn-sm py-0 flex-shrink-0"
                                    style="font-size:0.6rem;white-space:nowrap;" title="Lancer un gage sur cet événement">
                                + Gage
                            </button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    </div><!-- end evViewList -->

                    <!-- VUE CALENDRIER -->
                    <div id="evViewCal" style="display:none;padding:6px;">
                        <?php
                        $now     = new DateTime();
                        $year    = (int)$now->format('Y');
                        $month   = (int)$now->format('m');
                        $firstDay= (int)(new DateTime("{$year}-{$month}-01"))->format('N'); // 1=Lun
                        $daysInMonth = (int)(new DateTime("{$year}-{$month}-01"))->format('t');
                        $moisFr = [1=>'Janvier',2=>'Février',3=>'Mars',4=>'Avril',5=>'Mai',6=>'Juin',
                                7=>'Juillet',8=>'Août',9=>'Septembre',10=>'Octobre',11=>'Novembre',12=>'Décembre'];
                        $monthName = ($moisFr[$month] ?? '') . ' ' . $year;
                        ?>
                        <div class="text-center text-warning fw-bold mb-1" style="font-size:0.72rem;">
                            <?= date('F Y', mktime(0,0,0,$month,1,$year)) ?>
                        </div>
                        <div style="display:grid;grid-template-columns:repeat(7,1fr);gap:2px;">
                            <?php foreach(['L','M','M','J','V','S','D'] as $d): ?>
                            <div class="text-center text-muted" style="font-size:0.55rem;font-weight:bold;"><?= $d ?></div>
                            <?php endforeach; ?>

                            <?php for($i = 1; $i < $firstDay; $i++): ?>
                            <div></div>
                            <?php endfor; ?>

                            <?php for($day = 1; $day <= $daysInMonth; $day++):
                                $dateKey = sprintf('%04d-%02d-%02d', $year, $month, $day);
                                $hasEvents = isset($eventsByDate[$dateKey]);
                                $isToday   = $dateKey === date('Y-m-d');
                            ?>
                            <div style="background:<?= $isToday ? '#1a3a1a' : ($hasEvents ? '#1a2a3a' : '#111') ?>;
                                        border:1px solid <?= $isToday ? '#28a745' : ($hasEvents ? '#0dcaf0' : '#222') ?>;
                                        border-radius:3px;padding:2px;cursor:<?= $hasEvents ? 'pointer' : 'default' ?>;
                                        min-height:28px;text-align:center;"
                                 <?php if ($hasEvents): ?>
                                 onclick="toggleCalDay('day_<?= $dateKey ?>')"
                                 title="<?= count($eventsByDate[$dateKey]) ?> événement(s)"
                                 <?php endif; ?>>
                                <div style="font-size:0.62rem;color:<?= $isToday ? '#28a745' : ($hasEvents ? '#0dcaf0' : '#888') ?>;font-weight:<?= $isToday||$hasEvents?'bold':'normal' ?>;">
                                    <?= $day ?>
                                </div>
                                <?php if ($hasEvents): ?>
                                <div style="width:4px;height:4px;background:#0dcaf0;border-radius:50%;margin:0 auto;"></div>
                                <?php endif; ?>
                            </div>
                            <?php endfor; ?>
                        </div>

                        <!-- Détails des jours avec événements -->
                        <?php foreach($eventsByDate as $dateKey => $evs): ?>
                        <div id="day_<?= $dateKey ?>" style="display:none;margin-top:6px;background:#0a1a2a;border-radius:4px;padding:6px;">
                            <div class="text-info fw-bold mb-1" style="font-size:0.65rem;">
                                <?= date('d M Y', strtotime($dateKey)) ?>
                            </div>
                            <?php foreach($evs as $cev):
                                $typeIcon = match($cev['type']) { 'sport'=>'🏒','artistique'=>'🎭',default=>'📍' };
                            ?>
                            <div class="d-flex align-items-center gap-1 mb-1">
                                <span style="font-size:0.8rem;"><?= $typeIcon ?></span>
                                <span class="text-white" style="font-size:0.65rem;"><?= htmlspecialchars($cev['title']) ?></span>
                                <span class="text-muted ms-auto" style="font-size:0.6rem;"><?= date('H:i', strtotime($cev['event_date'])) ?></span>
                                <?php if ($isFullMember): ?>
                                <button onclick="gageRapide('<?= htmlspecialchars(addslashes($cev['title'])) ?>')"
                                        class="btn btn-xs btn-outline-warning py-0" style="font-size:0.55rem;">+Gage</button>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endforeach; ?>
                    </div><!-- end evViewCal -->

                </div><!-- end card -->
                <?php endif; } catch (Exception $e) { /* table pas encore créée */ } ?>

                <?php endif; // else Free — fin de la section classements/events pour Free ?>

            </div><!-- fin COL1 -->

            <!-- COL 2 : GAGES -->
            <div class="flex-grow-1" style="flex: 1 1 0; min-width: 0; overflow:visible; position:relative; <?= $useOverlay ? "padding: 0 clamp(24px, 12vw, 288px);" : "padding: 0 48px;" ?>">

                <!-- PANNEAU OVERLAY — disponible pour tous les membres connectés -->
                <?php if ($isLoggedIn): ?>
                <div id="dashPanelOverlay" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;z-index:1050;background:rgba(0,0,0,0.78);" onclick="if(event.target===this)closeDashPanel()">
                    <div id="dashPanelCard" style="margin:8px auto;width:min(900px,88vw);max-height:calc(100vh - 24px);background:#0d0d1a;border:1px solid #0dcaf0;border-radius:10px;display:flex;flex-direction:column;overflow:hidden;box-shadow:0 0 40px rgba(13,202,240,0.2);">
                        <div style="background:#050520;padding:6px 12px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #1a1a3a;flex-shrink:0;">
                            <span id="dashPanelTitle" class="fw-bold" style="font-size:0.72rem;color:#0dcaf0;letter-spacing:1px;">SECTION</span>
                            <div style="display:flex;gap:6px;align-items:center;">
                                <button id="dashPanelFullscreenBtn" onclick="wallOpenFullscreen()" title="Ouvrir en plein écran" style="display:none;background:none;border:1px solid #333;color:#888;border-radius:4px;padding:0 6px;font-size:0.6rem;height:22px;cursor:pointer;">⛶</button>
                                <button onclick="closeDashPanel()" class="btn btn-xs btn-outline-secondary py-0" style="font-size:0.6rem;">&#10005; Fermer</button>
                            </div>
                        </div>
                        <!-- Toolbar sticky (recherche, onglets, etc.) -->
                        <div id="dashPanelToolbar" style="flex-shrink:0;display:none;"></div>
                        <div id="dashPanelBody" style="flex:1;overflow-y:auto;padding:8px;"></div>
                    </div>
                </div>
                <?php endif; // isLoggedIn overlay ?>

                <!-- PASTILLES STICKY -->
                <?php if ($isLoggedIn):
                    // Cercles du membre pour la pastille
                    $myUserId   = (int)($_SESSION['user_id'] ?? 0);
                    // Gérer le changement de cercle via ?fc=
                    if (isset($_GET['fc']) && (int)$_GET['fc'] > 0) {
                        $_SESSION['circle_id'] = (int)$_GET['fc'];
                    }
                    $myCircleId = (int)($_SESSION['circle_id'] ?? 0);
                    $activeCircleId = $myCircleId;

                    $userCircles = [];
                    try {
                        $ucStmt = $pdo->prepare("
                            SELECT c.id, c.name, c.oracle_id
                            FROM circles c
                            JOIN circle_members cm ON cm.circle_id = c.id
                            WHERE cm.user_id = ?
                            ORDER BY c.name ASC
                        ");
                        $ucStmt->execute([$myUserId]);
                        $userCircles = $ucStmt->fetchAll();
                    } catch (Exception $e) {}

                    // Valider que le cercle actif appartient bien à l'user
                    if ($myCircleId > 0) {
                        $validCircle = false;
                        foreach ($userCircles as $uc) {
                            if ((int)$uc['id'] === $myCircleId) { $validCircle = true; break; }
                        }
                        if (!$validCircle && count($userCircles) > 0) {
                            $myCircleId = (int)$userCircles[0]['id'];
                            $_SESSION['circle_id'] = $myCircleId;
                        }
                    }
                ?>
                <div id="pastillesBar" style="display:flex;flex-wrap:wrap;gap:5px;padding:5px 0;margin-bottom:4px;position:sticky;top:4px;z-index:100;background:#0a0a0a;border-bottom:1px solid #1a1a1a;padding-bottom:6px;border-radius:0 0 6px 6px;">

                    <!-- Pastille CERCLES — visible pour tous -->
                    <div class="pastille-btn" id="pastille-cercles"
                         onclick="openDashPanel('cercles')"
                         style="background:rgba(253,126,20,0.12);border:1px solid rgba(253,126,20,0.4);border-radius:6px;padding:5px 10px;cursor:pointer;color:#fd7e14;font-size:0.6rem;font-weight:700;letter-spacing:0.5px;transition:all 0.15s;flex-shrink:0;"
                         onmouseover="this.style.background='rgba(253,126,20,0.35)'"
                         onmouseout="if(!this.classList.contains('p-active'))this.style.background='rgba(253,126,20,0.12)'">
                        🔵 MES CERCLES
                        <?php if (!empty($userCircles)): ?>
                        <span style="background:rgba(253,126,20,0.3);border-radius:8px;padding:0 5px;margin-left:3px;font-size:0.55rem;"><?= count($userCircles) ?></span>
                        <?php endif; ?>
                    </div>

                    <?php if ($isPremium || $isPremPlus || isAdmin($user)): ?>
                    <?php foreach([
                        <?php if (!$isMinor): ?>['classements','CLASSEMENTS','rgba(255,193,7,0.15)','rgba(255,193,7,0.45)','#ffc107'],<?php endif; ?>
                        ['chat','CHAT / MUR','rgba(13,110,253,0.15)','rgba(13,110,253,0.45)','#4d90fe'],
                        ['evenements','EVENEMENTS','rgba(40,167,69,0.15)','rgba(40,167,69,0.45)','#28a745'],
                        ['medias','MEDIAS','rgba(111,66,193,0.15)','rgba(111,66,193,0.45)','#a78bfa'],
                        ['amis','AMIS','rgba(13,202,240,0.12)','rgba(13,202,240,0.40)','#0dcaf0'],
                    ] as [$pid,$plbl,$pbg,$pbgh,$pcol]): ?>
                    <div class="pastille-btn" id="pastille-<?= $pid ?>"
                         onclick="openDashPanel('<?= $pid ?>')"
                         style="background:<?= $pbg ?>;border:1px solid <?= str_replace('0.15','0.4',$pbg) ?>;border-radius:6px;padding:5px 10px;cursor:pointer;color:<?= $pcol ?>;font-size:0.6rem;font-weight:700;letter-spacing:0.5px;transition:all 0.15s;flex-shrink:0;"
                         onmouseover="this.style.background='<?= $pbgh ?>'"
                         onmouseout="if(!this.classList.contains('p-active'))this.style.background='<?= $pbg ?>'">
                        <?= $plbl ?>
                    </div>
                    <?php endforeach; ?>
                    <?php endif; ?>

                </div>
                <?php endif; ?>

                <!-- BARRE PROFIL COMPACTE -->
                <?php if ($isLoggedIn): ?>
                <div style="display:flex;align-items:center;gap:8px;padding:5px 8px;background:#0d0d0d;border:1px solid #222;border-radius:6px;margin-bottom:6px;flex-wrap:wrap;">
                    <!-- Badge tier -->
                    <?php $tier = strtolower($user['tier'] ?? 'standard');
                    if ($tier === 'premium'): ?>
                        <span class="badge badge-gold px-1" style="font-size:0.5rem;">PREMIUM</span>
                    <?php elseif ($tier === 'premium_plus'): ?>
                        <span class="badge badge-silver px-1" style="font-size:0.5rem;">PREMIUM+</span>
                    <?php endif; ?>
                    <!-- Avatar -->
                    <div style="width:26px;height:26px;border-radius:50%;background:#0d6efd;display:flex;align-items:center;justify-content:center;color:#fff;font-size:11px;font-weight:700;flex-shrink:0;"><?= strtoupper(mb_substr($user['username']??'?',0,1)) ?></div>
                    <!-- Username -->
                    <span class="text-white fw-bold" style="font-size:0.78rem;"><?= htmlspecialchars($user['username'] ?? '') ?></span>
                    <!-- Points -->
                    <span class="text-success fw-bold" style="font-size:0.78rem;"><?= (int)$user['points'] ?> pts</span>
                    <!-- Jetons -->
                    <?php $myWalletDash = $isMinor ? 0 : (int)($user['wallet_points'] ?? 0);
                    if (!$isMinor && ($myWalletDash > 0 || (int)getWalletConfig($pdo,'wallet_enabled',1))): ?>
                    <?php
    $jColor = $myWalletDash >= 1000 ? '#d4af37' : ($myWalletDash >= 500 ? '#aaa' : ($myWalletDash >= 100 ? '#cd7f32' : '#888'));
    $jTitle = $myWalletDash >= 1000 ? 'Or' : ($myWalletDash >= 500 ? 'Argent' : ($myWalletDash >= 100 ? 'Bronze' : ''));
?>
<a href="wallet.php" class="text-decoration-none" style="font-size:0.7rem;color:<?= $jColor ?>;" title="<?= $jTitle ?>">&#9670; <?= number_format($myWalletDash) ?> jetons</a>
                    <?php endif; ?>
                    <!-- Trophées -->
                    <?php try {
                        $rtStmt = $pdo->prepare("SELECT tl.title, tl.icon_path FROM user_trophies ut JOIN trophy_levels tl ON tl.id=ut.trophy_id WHERE ut.user_id=? ORDER BY ut.awarded_at DESC LIMIT 3");
                        $rtStmt->execute([(int)$_SESSION['user_id']]);
                        $rtList = $rtStmt->fetchAll();
                        if (!empty($rtList)):
                    ?><span class="d-flex gap-1 align-items-center">
                        <?php foreach ($rtList as $rt): $ip=$rt['icon_path']??''; ?>
                        <span class="badge bg-warning text-dark" style="font-size:0.5rem;" title="<?= htmlspecialchars($rt['title']) ?>"><?= (!empty($ip)&&strpos($ip,'emoji:')===0)?htmlspecialchars(substr($ip,6)):'&#9733;' ?></span>
                        <?php endforeach; ?>
                    </span><?php endif; } catch(Exception $e) {} ?>
                    <!-- Quitter (poussé à droite) -->
                    <a href="index.php?logout=1" class="btn btn-outline-danger ms-auto" style="font-size:0.58rem;padding:2px 8px;line-height:1.4;">QUITTER</a>
                </div>
                <?php endif; ?>

                <?php if ($isFullMember): ?>

                <!-- GAGES GLOBAUX (tout le site) — 5 aléatoires parmi les 50 plus récents -->
                <?php if ($showPublicBets): // v1.7 — caché en mode isolé ?>
                <?php
                try {
                    $globalBetsPool = $pdo->query("
                        SELECT b.*, u.username
                        FROM bets b
                        JOIN users u ON u.id = b.user_id
                        WHERE b.is_global = 1 AND b.status = 'pending' AND (b.parieur2_id IS NULL OR b.parieur2_id = 0)
                        ORDER BY b.id DESC LIMIT 50
                    ")->fetchAll();
                    shuffle($globalBetsPool);
                    $globalBets = array_slice($globalBetsPool, 0, 5);
                    $globalTotal = $pdo->query("SELECT COUNT(*) FROM bets WHERE is_global=1 AND status='pending' AND (parieur2_id IS NULL OR parieur2_id=0)")->fetchColumn();
                } catch (Exception $e) { $globalBets = []; $globalTotal = 0; }

                if (!empty($globalBets)): ?>
                <div class="mb-3" id="globalBetsSection">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="text-warning fw-bold" style="font-size:0.7rem;">
                            🌍 GAGES OUVERTS <span class="text-muted" style="font-size:0.6rem;font-weight:normal;">(<?= (int)$globalTotal ?> au total)</span>
                        </div>
                        <div class="d-flex gap-1">
                            <button onclick="shuffleGlobalBets()" class="btn btn-xs py-0" style="font-size:0.6rem;background:rgba(255,193,7,0.1);border:1px solid rgba(255,193,7,0.3);color:#ffc107;">🔀 Mélanger</button>
                            <button onclick="openGlobalBetsPanel()" class="btn btn-xs py-0" style="font-size:0.6rem;background:rgba(255,140,0,0.1);border:1px solid rgba(255,140,0,0.35);color:#ff8c00;">Voir tout →</button>
                        </div>
                    </div>
                    <div id="globalBetsList">
                    <?php foreach ($globalBets as $gb):
                        $isMyGlobal = (int)$gb['user_id'] === (int)($_SESSION['user_id'] ?? 0);
                        $gbDesc = filterBadWords($gb['description'], $pdo);
                    ?>
                    <div class="card p-2 mb-2 bg-dark shadow global-bet-card" style="border:1px solid rgba(255,140,0,0.4);border-left:3px solid #ff8c00;">
                        <div class="d-flex justify-content-between align-items-start gap-2">
                            <div style="min-width:0;">
                                <span class="text-warning fw-bold" style="font-size:0.65rem;"><?= htmlspecialchars($gb['username']) ?></span>
                                <span class="text-muted mx-1" style="font-size:0.6rem;">·</span>
                                <span class="text-success" style="font-size:0.6rem;"><?= (int)$gb['amount'] ?> pts</span>
                                <?php if (!empty($gb['bet_category'])): ?>
                                <span style="font-size:0.5rem;padding:0 4px;border-radius:8px;background:rgba(255,193,7,0.1);border:1px solid rgba(255,193,7,0.25);color:#ffc107;margin-left:3px;"><?= htmlspecialchars($gb['bet_category']) ?></span>
                                <?php endif; ?>
                                <div class="text-white mt-1" style="font-size:0.73rem;line-height:1.3;"><?= htmlspecialchars($gbDesc) ?></div>
                            </div>
                            <?php if (!$isMyGlobal): ?>
                            <a href="bet_accept.php?id=<?= $gb['id'] ?>&action=accept"
                               class="btn btn-warning btn-sm py-0 flex-shrink-0" style="font-size:0.6rem;white-space:nowrap;">
                                TENU !
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>

                <!-- PANEL TOUS LES GAGES PUBLICS -->
                <div id="globalBetsPanelOverlay" style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;z-index:1060;background:rgba(0,0,0,0.82);" onclick="if(event.target===this)closeGlobalBetsPanel()">
                    <div style="margin:20px auto;width:min(640px,94vw);max-height:calc(100vh - 40px);background:#0d0d1a;border:1px solid #ff8c00;border-radius:10px;display:flex;flex-direction:column;overflow:hidden;">
                        <div style="background:#0a0a14;padding:10px 14px;border-bottom:1px solid #2a1a00;display:flex;justify-content:space-between;align-items:center;flex-shrink:0;">
                            <div>
                                <span class="text-warning fw-bold" style="font-size:0.78rem;letter-spacing:1px;">🌍 TOUS LES GAGES PUBLICS</span>
                                <span id="globalPanelCount" class="text-muted ms-2" style="font-size:0.6rem;"></span>
                            </div>
                            <button onclick="closeGlobalBetsPanel()" style="background:none;border:1px solid #333;color:#aaa;border-radius:5px;padding:2px 10px;font-size:0.65rem;cursor:pointer;">✕ Fermer</button>
                        </div>
                        <!-- Filtres -->
                        <div style="padding:8px 12px;border-bottom:1px solid #1a1a2a;flex-shrink:0;display:flex;gap:6px;flex-wrap:wrap;align-items:center;">
                            <input type="text" id="globalSearchInput" placeholder="🔍 Chercher..." oninput="filterGlobalBets()"
                                   style="background:#111;border:1px solid #333;color:#fff;border-radius:5px;padding:3px 8px;font-size:0.65rem;flex:1;min-width:120px;">
                            <select id="globalCatFilter" onchange="filterGlobalBets()"
                                    style="background:#111;border:1px solid #333;color:#ffc107;border-radius:5px;padding:3px 8px;font-size:0.65rem;">
                                <option value="">Toutes catégories</option>
                            </select>
                            <button onclick="loadGlobalBets('random')" style="background:rgba(255,193,7,0.1);border:1px solid rgba(255,193,7,0.3);color:#ffc107;border-radius:5px;padding:3px 8px;font-size:0.6rem;cursor:pointer;">🔀 Aléatoire</button>
                            <button onclick="loadGlobalBets('recent')" style="background:rgba(13,202,240,0.1);border:1px solid rgba(13,202,240,0.3);color:#0dcaf0;border-radius:5px;padding:3px 8px;font-size:0.6rem;cursor:pointer;">🕒 Récents</button>
                        </div>
                        <div id="globalBetsPanelBody" style="flex:1;overflow-y:auto;padding:10px;"></div>
                    </div>
                </div>
                <?php endif; // v1.7 showPublicBets ?>

                <div class="card p-3 mb-3 bg-dark shadow" style="border:1px solid <?= $isIsolated ? '#a78bfa' : '#0d6efd' ?>;">
                    <h6 class="fw-bold text-uppercase small mb-2" style="color:<?= $isIsolated ? '#a78bfa' : '#0d6efd' ?>;">
                        <?php if ($isIsolated): ?>
                            🤝 <?= t('terme_lancer_gage') ?>
                            <span class="text-muted fw-normal" style="font-size:0.6rem;letter-spacing:0;text-transform:none;">— <?= htmlspecialchars(ucfirst($groupType)) ?> · <?= htmlspecialchars($privateCircle['name'] ?? '') ?></span>
                        <?php else: ?>
                            🔥 <?= t('terme_lancer_gage') ?>
                        <?php endif; ?>
                    </h6>
                    <form action="index.php" method="POST" id="betForm">
                        <input type="hidden" name="action" value="create_bet">
                        <?php if ($isIsolated): ?>
                        <input type="hidden" name="is_group_bet" value="1"> <?php // v1.7 ?>
                        <?php endif; ?>
                        <div class="row g-2">
                            <div class="col-12">
                                <input type="text" name="description" id="betDesc"
                                       class="form-control form-control-sm bg-dark text-white border-secondary"
                                       placeholder="<?= $isIsolated ? 'L\'engagement... (ex: Je m\'engage à faire mes devoirs chaque soir)' : 'Le défi... (ex: Je gage que Pascal va scorer ce soir)' ?>"
                                       required oninput="autoDetectParieur(this.value)"
                                       onkeydown="if(event.key==='Enter'){event.preventDefault();return false;}">
                            </div>
                            <div class="col-12 position-relative">
                                <label class="text-white" style="font-size:0.65rem;">
                                    <?= $isIsolated ? 'MEMBRE' : strtoupper(tr('terme_gageur')) . ' 2' ?>
                                    <span id="p2RequiredBadge" style="color:#dc3545;font-size:0.6rem;">(obligatoire)</span><span id="p2OptionalBadge" style="color:#888;font-size:0.6rem;display:none;">(optionnel — gage ouvert)</span>
                                </label>
                                <div class="input-group input-group-sm">
                                    <input type="text" id="parieur2Search"
                                           class="form-control bg-dark text-white border-secondary"
                                           placeholder="🔍 <?= $isIsolated ? 'Nom du membre...' : 'Nom du gageur 2...' ?>"
                                           autocomplete="off" oninput="searchParieur(this.value)"
                                           onkeydown="if(event.key==='Enter'){event.preventDefault();return false;}">
                                    <input type="hidden" name="parieur2_id" id="parieur2Id">
                                    <button type="button" class="btn btn-outline-secondary btn-sm" onclick="clearParieur()" title="Effacer">✕</button>
                                </div>
                                <div id="parieurSuggestions"
                                     style="display:none;position:absolute;z-index:100;width:100%;background:#1a1a1a;border:1px solid #444;border-radius:0 0 6px 6px;max-height:160px;overflow-y:auto;">
                                </div>
                                <div id="parieurSelected" class="mt-1 p-2 rounded" style="font-size:0.65rem;display:none;background:#0a1a0a;border:1px solid #28a745;">
                                    <div class="text-success fw-bold mb-1"><?= $isIsolated ? 'Membre sélectionné' : tr('terme_gageur') . ' 2 sélectionné' ?> : <strong id="parieurName"></strong></div>
                                    <div id="parieurContact" class="text-muted" style="font-size:0.6rem;"></div>
                                    <div class="text-info mt-1" style="font-size:0.6rem;">(en attente de son acceptation)</div>
                                </div>
                            </div>

                            <?php if ($isIsolated): // v1.7 — récompense texte au lieu de points ?>
                            <div class="col-12">
                                <label class="text-white" style="font-size:0.65rem;">RÉCOMPENSE <span style="color:#a78bfa;font-size:0.58rem;">(si l'engagement est tenu)</span></label>
                                <input type="text" name="reward_text" id="betRewardText"
                                       class="form-control form-control-sm bg-dark text-white border-secondary"
                                       placeholder="Ex: 1h de Xbox, sortie au cinéma, congé de vaisselle..."
                                       maxlength="255" style="border-color:#a78bfa!important;">
                                <input type="hidden" name="amount" value="1"> <?php // montant symbolique ?>
                            </div>
                            <?php else: ?>
                            <div class="col-5">
                                <label class="text-white" style="font-size:0.65rem;">HONNEUR (1-50)</label>
                                <input type="number" name="amount" min="1" max="50" step="1" value="5"
                                       class="form-control form-control-sm bg-dark text-white border-secondary" required>
                            </div>
                            <?php endif; ?>

                            <?php
                            $walletEnabled = (int)getWalletConfig($pdo, 'wallet_enabled', 1);
                            $walletBetEnabled = (int)getWalletConfig($pdo, 'wallet_bet_enabled', 0);
                            $myWallet = (int)($user['wallet_points'] ?? 0);
                            ?>
                            <?php if ($canWalletBet && $walletEnabled && $walletBetEnabled && $myWallet > 0 && !$isMinor && !$isIsolated): ?>
                            <div class="col-12">
                                <div class="d-flex align-items-center gap-2">
                                    <div class="form-check form-check-sm mb-0">
                                        <input class="form-check-input" type="checkbox" name="use_wallet" id="useWallet" value="1"
                                               onchange="document.getElementById('walletStakeWrap').style.display=this.checked?'':'none'">
                                        <label class="form-check-label text-warning" for="useWallet" style="font-size:0.65rem;">
                                            Miser des jetons (solde: <?= number_format($myWallet) ?>)
                                        </label>
                                    </div>
                                </div>
                                <div id="walletStakeWrap" style="display:none;margin-top:4px;">
                                    <?php $walletBetMax = (int)getWalletConfig($pdo,'wallet_bet_max',500); $walletInputMax = min($myWallet, $walletBetMax); ?>
                                    <input type="number" name="wallet_stake" min="1" max="<?= $walletInputMax ?>" 
                                           class="form-control form-control-sm bg-dark text-warning border-warning"
                                           placeholder="Mise en jetons..." style="max-width:160px;">
                                    <small style="color:#aaa;font-size:0.6rem;">Le gagnant remporte la mise double</small>
                                </div>
                            </div>
                            <?php endif; ?>
                            <div class="col-4">
                                <label class="text-white" style="font-size:0.65rem;">ÉCHÉANCE <span style="color:#dc3545;font-size:0.6rem;">(obligatoire)</span></label>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text bg-dark border-secondary text-info" style="cursor:pointer;" onclick="document.getElementById('echeancePicker')._flatpickr.open()">📅</span>
                                    <input type="text" id="echeancePicker" name="echeance"
                                           class="form-control bg-dark text-white border-secondary"
                                           placeholder="Choisir une date..." readonly style="cursor:pointer;">
                                </div>
                            </div>
                            <div class="col-3 d-flex align-items-end">
                                <button type="button" class="btn btn-sm w-100 fw-bold" style="background:<?= $isIsolated ? '#a78bfa' : '#0d6efd' ?>;color:#fff;" onclick="validateAndSubmitBet()"><?= $isIsolated ? strtoupper(tr('terme_gager')) : strtoupper(tr('terme_lancer_gage')) ?></button>
                            </div>
                            <div class="col-12 d-flex align-items-center gap-3 flex-wrap">
                                <?php if (!$isIsolated): // v1.7 — gage ouvert caché en mode isolé ?>
                                <div class="form-check form-check-sm mb-0">
                                    <input class="form-check-input" type="checkbox" name="is_global" id="isGlobal" value="1">
                                    <label class="form-check-label text-warning" for="isGlobal" style="font-size:0.65rem;">
                                        <?= t('terme_gage') ?> ouvert (tout le site — 1er qui accepte = <?= t('terme_gageur') ?> 2)
                                    </label>
                                </div>
                                <?php endif; ?>
                                <div class="form-check form-check-sm mb-0" id="sendEmailCheck" style="display:none;">
                                    <input class="form-check-input" type="checkbox" name="send_email" id="sendEmail" value="1" checked>
                                    <label class="form-check-label text-info" for="sendEmail" style="font-size:0.65rem;">
                                        Envoyer par courriel au <?= t('terme_gageur') ?> 2
                                    </label>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- GAGES EN ATTENTE D'ACCEPTATION (pour le parieur 2) -->
                <?php
                try {
                    $pendingAccept = $pdo->prepare("
                        SELECT b.*, u.username as owner_name
                        FROM bets b
                        JOIN users u ON u.id = b.user_id
                        WHERE b.parieur2_id = ?
                          AND (b.acceptance_status = 'pending_p2' OR (b.acceptance_status IS NULL AND b.parieur2_id IS NOT NULL AND b.status = 'pending'))
                        ORDER BY b.id DESC LIMIT 5
                    ");
                    $pendingAccept->execute([$_SESSION['user_id']]);
                    $pendingBets = $pendingAccept->fetchAll();
                    if (!empty($pendingBets)): ?>
                <div class="card p-2 mb-3 border-warning bg-dark shadow">
                    <h6 class="text-warning fw-bold small mb-2">⏳ GAGES EN ATTENTE DE TA RÉPONSE (<?= count($pendingBets) ?>)</h6>
                    <?php foreach ($pendingBets as $pb): ?>
                    <div class="d-flex align-items-center gap-2 mb-1 p-1 rounded" style="background:#1a1500;">
                        <div class="flex-grow-1">
                            <small class="text-info"><?= htmlspecialchars($pb['owner_name']) ?></small>
                            <span class="text-white ms-1" style="font-size:0.75rem;"><?= htmlspecialchars(mb_substr($pb['description'],0,50)) ?></span>
                            <small class="text-success ms-1"><?= (int)$pb['amount'] ?> pts</small>
                        </div>
                        <a href="bet_accept.php?id=<?= $pb['id'] ?>&action=accept" class="btn btn-xs btn-success py-0">✓ ACCEPTER</a>
                        <a href="bet_accept.php?id=<?= $pb['id'] ?>&action=refuse" class="btn btn-xs btn-danger py-0">✗ REFUSER</a>
                    </div>
                    <?php endforeach; ?>
                </div>
                    <?php endif;
                } catch (Exception $e) {} ?>

                <?php endif; // isFullMember ?>

                <!-- BARRE RECHERCHE + FILTRES -->
                <div class="d-flex gap-2 mb-2 align-items-center flex-wrap">
                    <div class="input-group input-group-sm flex-grow-1" style="min-width:180px;">
                        <span class="input-group-text bg-dark border-secondary text-muted">🔍</span>
                        <input type="text" id="searchBets" class="form-control bg-dark text-white border-secondary"
                               placeholder="Chercher un gage..." oninput="filterBets(this.value)">
                        <button class="btn btn-outline-secondary btn-sm" onclick="document.getElementById('searchBets').value='';filterBets('')">✕</button>
                    </div>
                    <select id="filterStatus" class="form-select form-select-sm bg-dark text-white border-secondary" style="max-width:130px;" onchange="filterBets(document.getElementById('searchBets').value)">
                        <option value="">Tous statuts</option>
                        <option value="PENDING">⏳ En attente</option>
                        <option value="ACCEPTED">✓ Accepté</option>
                        <option value="WON">🏆 Gagné</option>
                        <option value="LOST">❌ Perdu</option>
                        <option value="COMPLETED">✅ Complété</option>
                        <option value="CANCELLED">🚫 Annulé</option>
                        <option value="HONORED">🤝 Honoré</option>
                        <option value="NOT_HONORED">⚠️ Non-Honoré</option>
                    </select>
                    <select id="filterWho" class="form-select form-select-sm bg-dark text-white border-secondary" style="max-width:130px;" onchange="filterBets(document.getElementById('searchBets').value)">
                        <option value="circle" selected>Mon cercle</option>
                        <option value="mine">Mes gages</option>
                        <option value="">Tous (+ publics)</option>
                        <option value="global">Publics seuls</option>
                    </select>

                    <?php if (count($userCircles) > 1): ?>
                    <div class="d-flex align-items-center gap-1" style="flex-shrink:0;">
                        <span style="font-size:0.6rem;color:#888;white-space:nowrap;">Cercle :</span>
                        <select id="circleSwitch" class="form-select form-select-sm bg-dark text-white border-secondary"
                                style="max-width:130px;font-size:0.65rem;"
                                onchange="switchCircle(this.value)">
                            <?php foreach ($userCircles as $uc): ?>
                            <option value="<?= (int)$uc['id'] ?>" <?= (int)$uc['id']===$myCircleId?'selected':'' ?>>
                                <?= htmlspecialchars(mb_substr($uc['name'],0,15)) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                </div>

                <div id="lista-gages">
                    <?php
                    // $myCircleId, $myUserId et $userCircles déjà définis plus haut

                    // Construire la requête selon le contexte
                     if ($isFullMember) {
                         // Garantir que les colonnes clés existent
                         try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS is_global TINYINT(1) DEFAULT 0"); } catch(Exception $e){}
                         try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS hidden TINYINT(1) DEFAULT 0"); } catch(Exception $e){}
                         try { $pdo->exec("ALTER TABLE bets ADD COLUMN IF NOT EXISTS parieur2_id INT DEFAULT NULL"); } catch(Exception $e){}
                         // Préférence masquer gages publics
                         $hidePublicBets = !empty($user['hide_public_bets']);
                         $globalCond = $hidePublicBets ? "" : "OR b.is_global = 1";
                         $hiddenCond = "AND (b.hidden IS NULL OR b.hidden = 0)";

                        // Gages triés: cercle + mes gages en priorité, publics après
                        $stmtBets = $pdo->prepare("
                            SELECT b.*, u.username,
                                   c.name as circle_name,
                                   u2.username as parieur2_name,
                                   CASE
                                     WHEN b.circle_id = ? THEN 1
                                     WHEN b.user_id = ? OR b.parieur2_id = ? THEN 2
                                     WHEN b.user_id IN (SELECT friend_id FROM friends WHERE user_id = ? AND status='active') THEN 3
                                     WHEN b.is_global = 1 THEN 4
                                     ELSE 5
                                   END as sort_priority
                            FROM bets b
                            JOIN users u ON u.id = b.user_id
                            LEFT JOIN circles c ON c.id = b.circle_id
                            LEFT JOIN users u2 ON u2.id = b.parieur2_id
                            WHERE (b.hidden IS NULL OR b.hidden = 0)
                              AND (
                                b.circle_id = ?
                                OR b.user_id = ?
                                OR b.parieur2_id = ?
                                OR b.is_global = 1
                                OR b.user_id IN (SELECT friend_id FROM friends WHERE user_id = ? AND status = 'active')
                              )
                            ORDER BY sort_priority ASC, b.id DESC LIMIT 30
                        ");
                        $stmtBets->execute([$myCircleId, $myUserId, $myUserId, $myUserId, $myCircleId, $myUserId, $myUserId, $myUserId]);
                    } else {
                        // Visiteur : seulement les gages globaux ou publics
                         $hasGlobal = true; // is_global colonne garantie
                        if ($hasGlobal) {
                            $stmtBets = $pdo->query("SELECT b.*, u.username, c.name as circle_name, u2.username as parieur2_name
                                FROM bets b JOIN users u ON u.id=b.user_id
                                LEFT JOIN circles c ON c.id=b.circle_id
                                LEFT JOIN users u2 ON u2.id=b.parieur2_id
                                WHERE b.is_global=1 ORDER BY b.id DESC LIMIT 10");
                        } else {
                            $stmtBets = $pdo->query("SELECT b.*, u.username, NULL as circle_name, NULL as parieur2_name
                                FROM bets b JOIN users u ON u.id=b.user_id ORDER BY b.id DESC LIMIT 10");
                        }
                    }

                    while ($bet = $stmtBets->fetch()):
                        $statusText = strtoupper($bet['status']);
                        // Filtrer les mots interdits dans la description
                        $bet['description'] = filterBadWords($bet['description'], $pdo);
                        // Affiner le statut selon acceptance_status
                        if ($bet['status'] === 'pending' && !empty($bet['acceptance_status'])) {
                            if ($bet['acceptance_status'] === 'pending_p2') $statusText = 'EN ATTENTE';
                            elseif ($bet['acceptance_status'] === 'accepted') $statusText = 'ACCEPTÉ';
                            elseif ($bet['acceptance_status'] === 'refused')  $statusText = 'REFUSÉ';
                        }
                        if (!empty($bet['honored']))     $statusText = 'HONORÉ';
                        if (!empty($bet['not_honored'])) $statusText = 'NON-HONORÉ';
                        $badgeClass = match(true) {
                            in_array($bet['status'],['lost','cancelled']) => 'bg-danger',
                            $bet['status'] === 'won'                       => 'bg-success',
                            $bet['status'] === 'completed'                 => 'bg-info text-dark',
                            !empty($bet['honored'])                        => 'bg-success',
                            !empty($bet['not_honored'])                    => 'bg-danger',
                            $bet['status'] === 'pending'                   => 'bg-warning text-dark',
                            default                                        => 'bg-secondary',
                        };
                        $isOwner = ($isLoggedIn && (int)$bet['user_id'] === (int)$_SESSION['user_id']);
                    ?>
                        <?php
                        $betSource = 'public';
                        if ((int)($bet['circle_id']??0) === $myCircleId) $betSource = 'cercle';
                        elseif ((int)$bet['user_id']===$myUserId || (int)($bet['parieur2_id']??0)===$myUserId) $betSource = 'moi';
                        $betSourceColors = ['cercle'=>'#0dcaf0','moi'=>'#a78bfa','public'=>'#6c757d'];
                        $betSourceLabels = ['cercle'=>'CERCLE','moi'=>'MON GAGE','public'=>'PUBLIC'];
                        ?>
                        <div class="card p-3 mb-3 bg-dark shadow-sm small gage-card"
                             style="<?= !empty($bet['is_friend_bet']) ? 'border:1px solid #ffc107;box-shadow:0 0 8px rgba(255,193,7,0.15)!important;' : 'border-color:var(--bs-secondary)!important;' ?>"
                             id="bet-<?= $bet['id'] ?>"
                             data-owner="<?= (int)$bet['user_id'] ?>"
                             data-p2="<?= (int)($bet['parieur2_id']??0) ?>"
                             data-circle="<?= (int)($bet['circle_id']??0) ?>"
                             data-global="<?= (int)($bet['is_global']??0) ?>"
                             data-source="<?= $betSource ?>"
                             data-betjson="<?= htmlspecialchars(json_encode([
                                'id'          => $bet['id'],
                                'description' => $bet['description'],
                                'amount'      => $bet['amount'],
                                'wallet_stake'=> $bet['wallet_stake']??0,
                                'status'      => $bet['status'],
                                'username'    => $bet['username'],
                                'parieur2'    => $bet['parieur2_name']??'',
                                'circle'      => $bet['circle_name']??'',
                                'echeance'    => $bet['echeance']??'',
                                'honored'     => $bet['honored']??0,
                                'vote_oui'    => $bet['vote_oui']??0,
                                'vote_non'    => $bet['vote_non']??0,
                                'is_global'   => $bet['is_global']??0,
                                'source'      => $betSource,
                             ]), ENT_QUOTES) ?>"
                             style="cursor:pointer;"
                             onclick="openBetModal(this)">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <span class="text-info fw-bold" style="font-size: 0.7rem;">#<?= $bet['id'] ?> | <?= (int)$bet['amount'] ?> pts
                                <span style="font-size:0.48rem;font-weight:700;letter-spacing:0.5px;padding:1px 5px;border-radius:3px;border:1px solid <?= $betSourceColors[$betSource] ?>;color:<?= $betSourceColors[$betSource] ?>;margin-left:4px;"><?= $betSourceLabels[$betSource] ?></span>
                                <?php if (!empty($bet['wallet_stake']) && (int)$bet['wallet_stake'] > 0): ?>
                                <span class="badge bg-warning text-dark ms-1" style="font-size:0.55rem;">&#9654; <?= (int)$bet['wallet_stake'] ?> jetons</span>
                                <?php endif; ?>
                                </span>
                                <span class="badge <?= $badgeClass ?>" style="font-size:0.55rem;"><?= $statusText ?></span>
                            </div>
                            <div class="text-white mb-1 fw-bold"><?= htmlspecialchars($bet['description']) ?></div>
                            <?php if (!empty($bet['reward_text'])): // v1.7 — récompense texte ?>
                            <div class="mb-1">
                                <span style="font-size:0.58rem;padding:2px 7px;border-radius:10px;background:rgba(167,139,250,0.12);border:1px solid rgba(167,139,250,0.35);color:#a78bfa;">
                                    🎁 <?= htmlspecialchars($bet['reward_text']) ?>
                                </span>
                            </div>
                            <?php endif; ?>
                            <div class="mb-1 d-flex gap-1 flex-wrap">
                                <?php if (!empty($bet['is_friend_bet'])): ?>
                                <span style="font-size:0.52rem;font-weight:700;padding:1px 6px;border-radius:10px;background:rgba(255,193,7,0.12);border:1px solid rgba(255,193,7,0.4);color:#ffc107;">⚡ Gage ami</span>
                                <?php endif; ?>
                                <?php if (!empty($bet['honor_pledge'])): ?>
                                <span style="font-size:0.52rem;font-weight:700;padding:1px 6px;border-radius:10px;background:rgba(40,167,69,0.12);border:1px solid rgba(40,167,69,0.4);color:#28a745;">🤝 Honneur mis</span>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                            <?php if (!empty($bet['bet_category'])): ?>
                            <div class="mb-1">
                                <span style="font-size:0.52rem;font-weight:700;letter-spacing:0.5px;padding:1px 6px;border-radius:10px;background:rgba(255,193,7,0.12);border:1px solid rgba(255,193,7,0.35);color:#ffc107;">
                                    <?= htmlspecialchars($bet['bet_category']) ?>
                                    <?php if (!empty($bet['bet_subcategory'])): ?>
                                    · <?= htmlspecialchars($bet['bet_subcategory']) ?>
                                    <?php endif; ?>
                                </span>
                            </div>
                            <?php endif; ?>
                                <!-- Gauche : 📸 + ⚙️ + 🤝 -->
                                <div class="d-flex gap-1 flex-shrink-0">
                                    <!-- Upload photo -->
                                    <a href="upload_photo.php?bet_id=<?= $bet['id'] ?>" class="btn btn-xs btn-outline-secondary py-0" title="Ajouter une preuve">[+]</a>
                                    <button class="btn btn-xs btn-outline-info py-0" onclick="showGallery(<?= $bet['id'] ?>, '<?= htmlspecialchars(addslashes(mb_substr($bet['description'],0,35))) ?>')" title="Voir les medias">[v]</button>

                                    <?php
                                    // Déterminer le gagnant
                                    $isGageur2    = (int)($bet['parieur2_id'] ?? 0) === (int)$_SESSION['user_id'];
                                    $betStatus    = $bet['status'] ?? '';
                                    // won = gageur1 a gagné, lost = gageur2 a gagné
                                    $isWinner     = ($betStatus === 'won' && $isOwner)
                                                 || ($betStatus === 'lost' && $isGageur2);
                                    $isLoser      = ($betStatus === 'won' && $isGageur2)
                                                 || ($betStatus === 'lost' && $isOwner);
                                    $honoreSet    = !empty($bet['honored']);
                                    $nonHonoreSet = !empty($bet['not_honored']);
                                    $betEcheance  = $bet['echeance'] ?? '';
                                    $votesClosed  = in_array($betStatus,['won','lost'])
                                        || (!empty($betEcheance) && $betEcheance !== '0000-00-00'
                                            && strtotime($betEcheance.' 23:59:59') < time());
                                    ?>
                                    <!-- Honorer / Non-honoré : gagnant seulement -->
                                    <?php if ($isWinner && $votesClosed && !$honoreSet && !$nonHonoreSet): ?>
                                    <a href="honor_bet.php?id=<?= $bet['id'] ?>"
                                       class="btn btn-xs btn-outline-success py-0"
                                       onclick="return confirm('Le perdant a honoré son gage ?')">🤝 Honoré</a>
                                    <a href="not_honored.php?id=<?= $bet['id'] ?>"
                                       class="btn btn-xs btn-outline-danger py-0"
                                       onclick="return confirm('Confirmer que le gage n\'a PAS été honoré ?')">❌ Non-honoré</a>
                                    <?php elseif ($honoreSet): ?>
                                    <span class="badge bg-success px-1 py-0" style="font-size:0.55rem;line-height:1.6;">🤝 Honoré</span>
                                    <?php elseif ($nonHonoreSet): ?>
                                    <span class="badge bg-danger px-1 py-0" style="font-size:0.55rem;line-height:1.6;">❌ Non-honoré</span>
                                    <?php if ($isLoser && $votesClosed): ?>
                                    <a href="arbitrage_bet.php?id=<?= $bet['id'] ?>"
                                       class="btn btn-xs btn-outline-warning py-0"
                                       onclick="return confirm('Demander un arbitrage à l\'Oracle ou l\'Admin ?')">⚖️ Arbitrage</a>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                    <?php
                                    $betIsLocked = ($bet['acceptance_status'] === 'accepted')
                                        || ($bet['status'] === 'completed')
                                        || ($bet['honored'] ?? 0);
                                    if (($isAdmin || $isOwner) && !$betIsLocked): ?>
                                        <button class="btn btn-outline-warning btn-xs py-0" onclick="event.stopPropagation();var m=new bootstrap.Modal(document.getElementById('editModal<?= $bet['id'] ?>'));m.show();"><i class="fa-solid fa-gear"></i></button>
                                    <?php elseif ($betIsLocked && ($isAdmin || $isOwner)): ?>
                                        <span title="Gage verrouillé — accepté par les deux parties" style="color:#555;font-size:0.7rem;padding:2px 4px;border:1px solid #333;border-radius:4px;cursor:not-allowed;">🔒</span>
                                        
                                    <?php endif; ?>
                                    <?php if ($isAdmin || $isOwner): ?>
                                        <!-- MODALE D'ÉDITION -->
                                        <div class="modal fade" id="editModal<?= $bet['id'] ?>" tabindex="-1" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered">
                                                <div class="modal-content bg-dark border-warning text-white shadow-lg">
                                                    <div class="modal-header border-secondary py-2">
                                                        <h6 class="modal-title text-warning">Modifier Défi #<?= $bet['id'] ?></h6>
                                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                                    </div>
                                                    <form action="edit_gage.php" method="POST">
                                                        <input type="hidden" name="bet_id" value="<?= $bet['id'] ?>">
                                                        <div class="modal-body text-start">
                                                            <div class="mb-3">
                                                                <label class="form-label text-warning fw-bold small">GAGE</label>
                                                                <textarea name="description" class="form-control bg-black text-white border-secondary" required><?= htmlspecialchars($bet['description']) ?></textarea>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label class="form-label text-warning fw-bold small">GAGEUR 2</label>
                                                                <select name="parieur2" class="form-select bg-black text-white border-secondary">
                                                                    <option value="">-- Sélectionner un membre --</option>
                                                                    <?php
                                                                    $stmtUsers = $pdo->query("SELECT id, username FROM users ORDER BY username ASC");
                                                                    while($u = $stmtUsers->fetch()) {
                                                                        $selected = (isset($bet['parieur2_id']) && $bet['parieur2_id'] == $u['id']) ? 'selected' : '';
                                                                        echo "<option value='{$u['id']}' $selected>{$u['username']}</option>";
                                                                    }
                                                                    ?>
                                                                </select>
                                                            </div>
                                                            <div class="row g-2 mb-3">
                                                                <div class="col-6">
                                                                    <label class="form-label text-white fw-bold small">ÉCHÉANCE</label>
                                                                    <div class="input-group">
                                                                        <span class="input-group-text bg-black border-secondary text-warning py-0" style="cursor:pointer;" onclick="openModalCal(<?= $bet['id'] ?>)">
                                                                            <i class="fa-solid fa-calendar-days" style="font-size:0.8rem;"></i>
                                                                        </span>
                                                                        <input type="text" name="echeance"
                                                                               id="modalCal<?= $bet['id'] ?>"
                                                                               class="form-control bg-black text-white border-secondary"
                                                                               placeholder="Choisir une date..."
                                                                               value="<?= !empty($bet['echeance']) ? date('d M Y', strtotime($bet['echeance'])) : '' ?>"
                                                                               readonly style="cursor:pointer;">
                                                                    </div>
                                                                </div>
                                                                <div class="col-6">
                                                                    <label class="form-label text-warning fw-bold small">STATUS</label>
                                                                    <select name="status" class="form-select bg-black text-white border-secondary">
                                                                        <option value="pending" <?= $bet['status']=='pending'?'selected':'' ?>>Attente</option>
                                                                        <option value="WON" <?= $bet['status']=='WON'?'selected':'' ?>>Gagné</option>
                                                                        <option value="LOST" <?= $bet['status']=='LOST'?'selected':'' ?>>Perdu</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            <div class="row g-2 mb-3">
                                                                <div class="col-6">
                                                                    <label class="form-label text-warning fw-bold small">CELLULAIRE</label>
                                                                    <input type="text" name="cellulaire" class="form-control bg-black text-white border-secondary" placeholder="000-000-0000" value="<?= htmlspecialchars($bet['cellulaire'] ?? '') ?>">
                                                                </div>
                                                                <div class="col-6">
                                                                    <label class="form-label text-warning fw-bold small">COURRIEL</label>
                                                                    <input type="email" name="courriel" class="form-control bg-black text-white border-secondary" placeholder="exemple@mail.com" value="<?= htmlspecialchars($bet['courriel'] ?? '') ?>">
                                                                </div>
                                                            </div>
                                                            <div class="mt-3">
                                                                <label class="form-label text-warning fw-bold small">POINTS D'HONNEUR (1-50)</label>
                                                                <input type="number" name="amount" class="form-control bg-black text-white border-secondary" value="<?= (int)$bet['amount'] ?>" min="1" max="50" step="1">
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer border-secondary p-2 d-flex justify-content-between">
                                                            <button type="submit" name="action_edit" value="delete" class="btn btn-outline-danger btn-sm" onclick="return confirm('Supprimer définitivement ?')">🗑️</button>
                                                            <button type="submit" name="action_edit" value="save" class="btn btn-warning btn-sm fw-bold">ENREGISTRER</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="d-flex gap-1">
                                    <?php
                                    $stmtImg = $pdo->prepare("SELECT file_path FROM bet_proofs WHERE bet_id = ?");
                                    $stmtImg->execute([$bet['id']]);
                                    foreach ($stmtImg->fetchAll() as $img): ?>
                                        <img src="<?= htmlspecialchars($img['file_path']) ?>" class="rounded border border-info" style="width: 25px; height: 25px; object-fit: cover; cursor:pointer;" onclick="showGallery(<?= $bet['id'] ?>, '<?= htmlspecialchars(addslashes(mb_substr($bet['description'],0,35))) ?>')">
                                    <?php endforeach; ?>
                                </div>

                                <!-- VOTES + REPORT groupés à droite -->
                                <div class="d-flex align-items-center gap-1 ms-auto" id="vote-zone-<?= $bet['id'] ?>">
                                <?php
                                $monVote = false;
                                if ($isLoggedIn && $_SESSION['user_id'] > 0) {
                                    $stmtCheck = $pdo->prepare("SELECT vote FROM bet_votes WHERE bet_id = ? AND voter_id = ?");
                                    $stmtCheck->execute([$bet['id'], $_SESSION['user_id']]);
                                    $monVote = $stmtCheck->fetch();
                                } else {
                                    $visitorIp = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
                                    $stmtCheck = $pdo->prepare("SELECT vote FROM bet_votes WHERE bet_id = ? AND ip_address = ? AND voter_id IS NULL");
                                    $stmtCheck->execute([$bet['id'], $visitorIp]);
                                    $monVote = $stmtCheck->fetch();
                                }
                                $stmtCount = $pdo->prepare("SELECT SUM(CASE WHEN vote IN ('1','oui') THEN 1 ELSE 0 END) as oui, SUM(CASE WHEN vote IN ('0','non') THEN 1 ELSE 0 END) as non FROM bet_votes WHERE bet_id = ?");
                                $stmtCount->execute([$bet['id']]);
                                $v      = $stmtCount->fetch();
                                $totalV = ($v['oui'] ?? 0) + ($v['non'] ?? 0);
                                $p_oui  = ($totalV > 0) ? round(($v['oui'] / $totalV) * 100) : 0;
                                $p_non  = ($totalV > 0) ? round(($v['non'] / $totalV) * 100) : 0;
                                ?>

                                <?php if ($monVote): ?>
                                    <div style="min-width:110px;">
                                        <div class="d-flex justify-content-between" style="font-size:0.58rem;">
                                            <span class="text-success fw-bold"><?= $p_oui ?>% OUI</span>
                                            <span class="text-danger fw-bold"><?= $p_non ?>% NON</span>
                                        </div>
                                        <div class="progress" style="height:4px;background:#222;">
                                            <div class="progress-bar bg-success" style="width:<?= $p_oui ?>%;"></div>
                                        </div>
                                        <div class="text-muted text-center" style="font-size:0.55rem;"><?= $totalV ?> vote<?= $totalV > 1 ? 's' : '' ?></div>
                                    </div>
                                <?php else:
                                    $echeanceStr = $bet['echeance'] ?? '';
                                    $echeanceExpired = !empty($echeanceStr) && $echeanceStr !== '0000-00-00' && strtotime($echeanceStr . ' 23:59:59') < time();
                                    if ($echeanceExpired): ?>
                                    <span class="text-muted" style="font-size:0.6rem;font-style:italic;">Votes terminés</span>
                                    <?php if ($totalV > 0): ?>
                                        <span class="text-muted" style="font-size:0.55rem;">(<?= $totalV ?>)</span>
                                    <?php endif; ?>
                                    <?php else: ?>
                                    <?php if ($canVoteBet): ?><button class="btn btn-success btn-xs py-0" onclick="voterAjax(<?= $bet['id'] ?>, 'oui', this)">OUI</button>
                                    <button class="btn btn-danger  btn-xs py-0" onclick="voterAjax(<?= $bet['id'] ?>, 'non', this)">NON</button><?php endif; ?>
                                    <?php if ($totalV > 0): ?>
                                        <span class="text-muted" style="font-size:0.55rem;">(<?= $totalV ?>)</span>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                <?php endif; ?>

                                <?php if ($isLoggedIn): ?>
                                    <button class="btn btn-xs btn-outline-secondary py-0" onclick="reportGage(<?= $bet['id'] ?>)" title="Signaler">🚩</button>
                                <?php endif; ?>
                                </div><!-- fin vote+report -->
                            </div><!-- fin footer -->
                        </div>
                    <?php endwhile; ?>
                </div>
                <div class="text-center mt-2">
                    <button id="load-more-btn" class="btn btn-outline-info btn-xs fw-bold" onclick="loadMoreBets()">VOIR LES 10 SUIVANTS</button>
                    <button class="btn btn-outline-secondary btn-xs fw-bold" onclick="resetBets()" id="reset-btn" style="display:none;">RETOUR AU TOP</button>
                </div>
            </div>

            <!-- COL 3 : CHAT -->
            <div id="col3Chat" class="desktop-only-col" style="flex: 0 0 <?= $showCol3 ? '420px' : '0' ?>; width:<?= $showCol3 ? '420px' : '0' ?>; display:<?= $showCol3 ? 'flex' : 'none' ?>; flex-direction:column; gap:8px; overflow:hidden; position:sticky; top:8px; transition: flex 0.25s, width 0.25s; align-self:flex-start; height:calc(100vh - 80px);">
                <?php if (!$useOverlay): ?>
                <button class="col-collapse-btn col3-collapse-btn" id="col3CollapseBtn" onclick="toggleColCollapse('col3')" title="Réduire">▶</button>
                <?php endif; ?>

                <!-- CHAT -->
                <div class="card bg-dark border-secondary shadow" id="chatCard" style="flex:1; min-height:300px; display:flex; flex-direction:column; font-size:0.75rem; margin-top:0;">
                    <div class="card-header bg-primary text-white fw-bold small py-1 d-flex justify-content-between align-items-center" style="min-height:34px;">
                        <span style="font-size:0.7rem;">MUR</span>
                        <div class="d-flex align-items-center gap-2">
                            <?php
                            $circleId = (int)($_SESSION['circle_id'] ?? 1);
                            // Dropdown cercles avec compteur non lus
                            try {
                                $myCirclesChat = $pdo->prepare("
                                    SELECT c.id, c.name,
                                    (SELECT COUNT(*) FROM messages m
                                     WHERE m.circle_id = c.id
                                     AND m.id > COALESCE(
                                         (SELECT MAX(m2.id) FROM messages m2
                                          WHERE m2.circle_id = c.id
                                          AND m2.user_id = ?), 0)
                                    ) as unread
                                    FROM circles c
                                    JOIN circle_members cm ON cm.circle_id = c.id
                                    WHERE cm.user_id = ?
                                    ORDER BY c.name ASC
                                ");
                                $myCirclesChat->execute([$_SESSION['user_id'], $_SESSION['user_id']]);
                                $circlesForChat = $myCirclesChat->fetchAll();
                            } catch (Exception $e) { $circlesForChat = []; }
                            if (count($circlesForChat) > 1): ?>
                            <select id="circleSelector" onchange="changeCircle(this.value)"
                                    style="background:#1a4a7a;color:#fff;border:none;font-size:0.65rem;border-radius:3px;padding:2px 6px;max-width:160px;cursor:pointer;">
                                <?php foreach ($circlesForChat as $cl):
                                    $unread = (int)$cl['unread'];
                                ?>
                                <option value="<?= $cl['id'] ?>" <?= $cl['id'] == $circleId ? 'selected' : '' ?>>
                                    <?= htmlspecialchars(mb_substr($cl['name'],0,12)) ?><?= $unread > 0 ? " ({$unread})" : '' ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <?php endif; ?>
                            <span class="badge bg-danger" style="font-size:0.5rem;">LIVE</span>
                            <?php if ($isPremium || $isPremPlus || isAdmin($user)): ?>
                            <button onclick="toggleChatSection()" id="toggle-chat"
                                    class="btn btn-xs py-0 btn-outline-light" style="font-size:0.55rem;line-height:1;">&#9660;</button>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div id="chat-box" class="p-2" style="flex:1; overflow-y:auto; background:#0a0a0a; font-size:0.8rem; min-height:0;"></div>

                    <?php if ($isFullMember):
                        // Charger icônes disponibles pour cet utilisateur
                        $userTier   = $user['tier'] ?? 'free';
                        $userPts    = (int)($user['interaction_points'] ?? 0);
                        $tierOrder  = ['free'=>0,'premium'=>1,'premium_plus'=>2,'admin'=>3];
                        // $isPremium et $isPremPlus déjà définis en haut du fichier

                        try {
                            $iconStmt = $pdo->query("SELECT * FROM chat_icons WHERE is_active=1 ORDER BY sort_order, required_points");
                            $allIcons = $iconStmt->fetchAll();
                        } catch (Exception $e) { $allIcons = []; }

                        $availableIcons = array_filter($allIcons, function($ic) use ($tierOrder, $userTierN, $userPts) {
                            return ($tierOrder[$ic['required_tier']]??0) <= $userTierN && $userPts >= (int)$ic['required_points'];
                        });
                        $lockedIcons = array_filter($allIcons, function($ic) use ($tierOrder, $userTierN, $userPts) {
                            return ($tierOrder[$ic['required_tier']]??0) > $userTierN || $userPts < (int)$ic['required_points'];
                        });
                    ?>

                    <!-- Zone saisie -->
                    <div class="p-2 border-top border-secondary bg-dark">

                        <!-- Barre d'outils : icône sélectionnée + couleur (Premium+) déplacée ici -->
                        <!-- Tracking interne de l'icône (invisible) -->
                        <span id="selectedIconDisplay" style="display:none;"></span>

                        <div class="input-group input-group-sm">
                            <!-- Color picker à la place de l'icône 😄 -->
                            <?php if ($isPremPlus): ?>
                            <input type="color" id="chatColorPicker" value="#e0e0e0"
                                   title="Couleur du texte"
                                   style="width:34px;height:30px;border:1px solid #555;border-radius:4px 0 0 4px;cursor:pointer;padding:2px;background:#111;flex-shrink:0;">
                            <button onclick="resetColor()" title="Réinitialiser la couleur"
                                    style="background:none;border:1px solid #555;border-left:none;color:#999;cursor:pointer;font-size:0.6rem;padding:0 5px;height:30px;flex-shrink:0;">↺</button>
                            <?php endif; ?>

                            <?php if (!empty($allIcons)): ?>
                            <button class="btn btn-outline-secondary" onclick="clearIcon()" title="Icônes" style="font-size:0.85rem;padding:0 8px;display:none;" id="iconPickerBtn">😄</button>
                            <?php endif; ?>

                            <!-- Bouton discret pour ouvrir le picker (toujours là, invisible) -->
                            <?php if (!empty($allIcons)): ?>
                            <button onclick="toggleIconPicker()" title="Choisir une icône"
                                    style="background:none;border:none;color:#999;cursor:pointer;font-size:0.7rem;padding:0 4px;flex-shrink:0;"
                                    id="iconOpenBtn">＋😊</button>
                            <?php endif; ?>

                            <input type="text" id="msg-input" class="form-control bg-dark text-white border-secondary"
                                   placeholder="Message..." onkeypress="if(event.key==='Enter'&&!event.shiftKey){sendMessage();}">

                            <?php if ($isPremPlus): ?>
                            <label class="btn btn-outline-info mb-0" title="Photo" style="padding:0 8px;display:flex;align-items:center;cursor:pointer;">
                                [+]<input type="file" id="chatPhotoInput" accept="image/*" style="display:none;" onchange="previewChatPhoto(this)">
                            </label>
                            <?php endif; ?>

                            <button class="btn btn-primary" onclick="sendMessage()">
                                <i class="fa-solid fa-paper-plane"></i>
                            </button>
                        </div>

                        <!-- Progress bar upload photo -->
                        <div id="chatUploadProgress" style="display:none;margin-top:4px;">
                            <div class="progress" style="height:4px;">
                                <div class="progress-bar progress-bar-striped progress-bar-animated bg-info" style="width:0%;" id="chatProgressBar"></div>
                            </div>
                            <small class="text-muted" style="font-size:0.6rem;" id="chatProgressLabel">Envoi en cours...</small>
                        </div>

                        <!-- Aperçu photo -->
                        <div id="chatPhotoPreview" style="display:none;margin-top:4px;" class="d-flex align-items-center gap-2">
                            <img id="chatPhotoImg" style="max-height:45px;border-radius:3px;border:1px solid #0dcaf0;">
                            <button onclick="clearChatPhoto()" style="font-size:0.6rem;background:none;border:none;color:#aaa;cursor:pointer;">✕ supprimer</button>
                        </div>

                        <!-- PICKER ICÔNES -->
                        <?php if (!empty($allIcons)): ?>
                        <div id="iconPickerInline" style="display:none;margin-top:4px;background:#0d0d0d;border:1px solid #333;border-radius:6px;padding:6px;flex-wrap:wrap;gap:6px;max-height:90px;overflow-y:auto;" class="d-flex">
                            <?php foreach ($availableIcons as $ic): ?>
                                <span data-emoji="<?= htmlspecialchars($ic['emoji']) ?>"
                                      title="<?= htmlspecialchars($ic['label']??$ic['emoji']) ?>"
                                      style="font-size:1.4rem;cursor:pointer;padding:2px 5px;border-radius:5px;border:1px solid transparent;transition:0.1s;user-select:none;"
                                      onmouseover="this.style.background='#2a2a2a';this.style.borderColor='#555';"
                                      onmouseout="this.style.background='';this.style.borderColor='transparent';"
                                      onclick="selectIcon(this)">
                                    <?= $ic['emoji'] ?>
                                </span>
                            <?php endforeach; ?>
                            <?php foreach ($lockedIcons as $ic):
                                $req = ($tierOrder[$ic['required_tier']]??0) > $userTierN ? strtoupper($ic['required_tier']) : $ic['required_points']." pts";
                            ?>
                                <span title="🔒 Requis : <?= $req ?>"
                                      style="font-size:1.4rem;padding:2px 5px;opacity:0.25;cursor:not-allowed;filter:grayscale(1);">
                                    <?= $ic['emoji'] ?>
                                </span>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>

                    <?php else: ?>
                    <div class="p-2 text-center text-muted border-top border-secondary" style="font-size:0.65rem;">
                        Connecte-toi pour participer au chat
                    </div>
                    <?php endif; ?>
                </div>

                <!-- VISIONNEUSE PHOTOS (se remplit au clic sur [v] d'un gage) -->
                <div class="card bg-dark border-secondary shadow" id="galleryCard" style="height:200px;">
                    <div class="card-header py-1 d-flex justify-content-between align-items-center" style="background:#0d0d0d;">
                        <span class="small fw-bold text-info" style="font-size:0.62rem;" id="galleryTitle">MEDIAS DU GAGE</span>
                        <div class="d-flex gap-1 align-items-center">
                            <button class="btn btn-xs py-0 btn-outline-warning" style="font-size:0.55rem;" onclick="toggleTumbling()" id="tumblingBtn" title="Voir tous les medias">TOUS</button>
                            <button class="btn btn-xs py-0 btn-outline-secondary" style="font-size:0.55rem;display:none;" onclick="closeGallery()" id="galleryCloseBtn">X</button>
                            <?php if ($isPremium || $isPremPlus || isAdmin($user)): ?>
                            <button onclick="toggleSection('gallery')" id="toggle-gallery"
                                    class="btn btn-xs py-0 btn-outline-light" style="font-size:0.55rem;line-height:1;">&#9660;</button>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div id="section-gallery">
                    <div id="gallery-zone" class="p-1 d-flex gap-1 align-items-center justify-content-center" style="overflow-x:auto;overflow-y:hidden;height:190px;">
                        <p class="text-muted mb-0 w-100 text-center" style="font-size:0.6rem;">Clique sur [v] d'un gage pour voir les medias</p>
                    </div>
                    </div>
                </div>

            </div>

            <!-- COL 4 : AMIS — visible pour Free, remplacée par pastille pour Premium -->
            <div class="friends-col desktop-only-col" style="display:flex; flex-direction:column; overflow:hidden; width:<?= $showCol1Full ? '180px' : '0' ?>; min-width:<?= $showCol1Full ? '180px' : '0' ?>; transition: width 0.25s, min-width 0.25s; position:relative;">
                <?php if (!$useOverlay): ?>
                <button class="col-collapse-btn col4-collapse-btn" id="col4CollapseBtn" onclick="toggleColCollapse('col4')" title="Réduire">▶</button>
                <?php endif; ?>
                <div class="card bg-dark border-info shadow" style="display:flex;flex-direction:column;flex:1;">
                    <div class="card-header bg-info text-black fw-bold py-1 d-flex justify-content-between align-items-center" style="min-height:34px;">
                        <span style="font-size:0.7rem;">AMIS</span>
                        <div class="d-flex gap-1 align-items-center">
                            <i class="fa-solid fa-user-plus" style="font-size:0.65rem;cursor:pointer;" onclick="toggleAddFriend()" title="Ajouter un ami"></i>
                            <i class="fa-solid fa-rotate-right" style="font-size:0.6rem;cursor:pointer;" onclick="loadFriends()"></i>
                            <?php if ($isPremium || $isPremPlus || isAdmin($user)): ?>
                            <button onclick="toggleSection('amis')" id="toggle-amis"
                                    class="btn btn-xs py-0 btn-outline-dark" style="font-size:0.55rem;line-height:1;">&#9660;</button>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div id="section-amis" style="display:flex;flex-direction:column;flex:1;overflow:hidden;">
                    <!-- Zone recherche ami (cachée par défaut) -->
                    <div id="addFriendZone" style="display:none;background:#0a0a0a;border-bottom:1px solid #0dcaf0;padding:6px;">
                        <div class="input-group input-group-sm">
                            <input type="text" id="friendSearchInput" class="form-control bg-dark text-white border-secondary"
                                   placeholder="Nom du membre..." style="font-size:0.68rem;"
                                   oninput="searchFriendToAdd(this.value)">
                            <button class="btn btn-outline-secondary btn-sm" onclick="toggleAddFriend()">✕</button>
                        </div>
                        <div id="friendSearchResults" class="mt-1"></div>

                        <!-- Suggestions du cercle -->
                        <div id="circleSuggestions" class="mt-1">
                            <div style="font-size:0.6rem;color:#aaa;margin-bottom:3px;">Membres du cercle :</div>
                            <?php
                            try {
                                $circleId = (int)($_SESSION['circle_id'] ?? 1);
                                $suggestStmt = $pdo->prepare("
                                    SELECT u.id, u.username
                                    FROM users u
                                    JOIN circle_members cm ON cm.user_id = u.id
                                    WHERE cm.circle_id = ? AND u.id != ?
                                    AND u.id NOT IN (SELECT friend_id FROM friends WHERE user_id = ? AND status='active')
                                    ORDER BY u.username ASC LIMIT 8
                                ");
                                $suggestStmt->execute([$circleId, $_SESSION['user_id'], $_SESSION['user_id']]);
                                $suggestions = $suggestStmt->fetchAll();
                                foreach ($suggestions as $s):
                            ?>
                            <div class="d-flex align-items-center justify-content-between py-1" style="border-bottom:1px solid #111;">
                                <span class="text-white" style="font-size:0.68rem;"><?= htmlspecialchars($s['username']) ?></span>
                                <button onclick="addFriend(<?= $s['id'] ?>, '<?= htmlspecialchars(addslashes($s['username'])) ?>', this)"
                                        class="btn btn-xs btn-outline-success py-0" style="font-size:0.58rem;">+ Ami</button>
                            </div>
                            <?php endforeach; } catch (Exception $e) {} ?>
                        </div>
                    </div>

                    <div id="friends-list" style="flex:1;overflow-y:auto;background:#050505;" class="p-1">
                        <!-- Chargé par AJAX -->
                    </div>
                    </div><!-- fin section-amis -->
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- LIGHTBOX PHOTOS -->
<div id="lightboxOverlay" onclick="closeLightbox()"
     style="display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.92);z-index:9999;cursor:pointer;flex-direction:column;align-items:center;justify-content:center;">
    <div style="position:relative;max-width:90vw;max-height:90vh;">
        <img id="lightboxImg" src="" style="max-width:90vw;max-height:82vh;object-fit:contain;border:2px solid #0dcaf0;border-radius:6px;">
        <div id="lightboxCaption" class="text-center text-muted mt-2" style="font-size:0.75rem;"></div>
    </div>
    <div class="text-muted mt-2" style="font-size:0.65rem;">Cliquer n'importe où pour fermer</div>
</div>

<!-- MODALE ACTIONS AMIS[cite: 12] -->
<div class="modal fade" id="friendActionModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content bg-dark border-info text-white shadow-lg">
            <div class="modal-header border-secondary py-1">
                <h6 class="modal-title small" id="friendName">Action</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-2" id="friendActionsBody"></div>
        </div>
    </div>
</div>

<!-- MODALE GAGE RAPIDE AMI -->
<div class="modal fade" id="friendBetModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" style="max-width:380px;">
        <div class="modal-content text-white shadow-lg" style="background:#0d0d1a;border:2px solid #ffc107;border-radius:12px;">
            <div class="modal-header py-2" style="background:#0a0a14;border-bottom:1px solid #ffc107;">
                <div>
                    <h6 class="modal-title mb-0 fw-bold text-warning" style="font-size:0.8rem;letter-spacing:1px;">
                        ⚡ GAGE RAPIDE
                    </h6>
                    <div class="text-muted" id="fbModalSubtitle" style="font-size:0.6rem;">avec <span id="fbFriendName" class="text-warning fw-bold"></span></div>
                </div>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-3">
                <form method="POST" id="friendBetForm" action="index.php">
                    <input type="hidden" name="action" value="create_bet">
                    <input type="hidden" name="parieur2_id" id="fbP2Id">
                    <input type="hidden" name="is_friend_bet" value="1">

                    <!-- Description -->
                    <div class="mb-3">
                        <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">LE GAGE</label>
                        <textarea name="description" id="fbDesc" rows="3"
                                  class="form-control bg-dark text-white border-warning"
                                  placeholder="Je gage que..." required maxlength="255"
                                  style="font-size:0.78rem;resize:none;"></textarea>
                    </div>

                    <!-- Date limite -->
                    <div class="mb-3">
                        <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">DATE LIMITE <span class="text-danger">*</span></label>
                        <input type="date" name="echeance" id="fbEcheance"
                               class="form-control form-control-sm bg-dark text-white border-secondary"
                               min="<?= date('Y-m-d', strtotime('+1 day')) ?>"
                               required style="font-size:0.72rem;">
                    </div>

                    <!-- Points -->
                    <div class="mb-3">
                        <label class="text-white small fw-bold d-block mb-1" style="font-size:0.65rem;">POINTS D'HONNEUR</label>
                        <input type="number" name="amount" id="fbAmount"
                               class="form-control form-control-sm bg-dark text-white border-secondary"
                               value="5" min="1" max="50" style="font-size:0.72rem;">
                    </div>

                    <?php if ($canWalletBet && !$isMinor): ?>
                    <div class="mb-3">
                        <div class="form-check mb-1">
                            <input type="checkbox" name="use_wallet" id="fbUseWallet" class="form-check-input"
                                   onchange="document.getElementById('fbWalletRow').style.display=this.checked?'block':'none'">
                            <label class="form-check-label text-muted small" for="fbUseWallet" style="font-size:0.65rem;">
                                Ajouter des jetons en jeu
                            </label>
                        </div>
                        <div id="fbWalletRow" style="display:none;">
                            <input type="number" name="wallet_stake" id="fbWalletStake"
                                   class="form-control form-control-sm bg-dark text-white border-warning"
                                   placeholder="Nb jetons" min="1" max="<?= $walletInputMax ?>"
                                   style="font-size:0.72rem;">
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Honneur mis -->
                    <div class="mb-3 p-2 rounded" style="background:rgba(255,193,7,0.06);border:1px solid rgba(255,193,7,0.2);">
                        <div class="form-check">
                            <input type="checkbox" name="honor_pledge" id="fbHonorPledge" class="form-check-input" value="1">
                            <label class="form-check-label small text-warning fw-bold" for="fbHonorPledge" style="font-size:0.65rem;">
                                🤝 Je mets mon honneur là-dessus
                            </label>
                        </div>
                        <div class="text-muted mt-1" style="font-size:0.58rem;">
                            En cochant, tu t'engages publiquement à honorer ce gage si tu perds.
                        </div>
                    </div>

                    <!-- Erreur -->
                    <div id="fbError" style="display:none;font-size:0.65rem;color:#dc3545;background:rgba(220,53,69,0.1);border:1px solid #dc3545;border-radius:5px;padding:5px 9px;margin-bottom:8px;"></div>

                    <!-- Bouton -->
                    <button type="button" onclick="submitFriendBet()"
                            class="btn btn-warning fw-bold w-100" style="letter-spacing:1px;color:#000;">
                        ⚡ <?= strtoupper(tr('terme_lancer_gage')) ?>
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- MODALE PROFIL -->
<div class="modal fade" id="userProfileModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-primary text-white" id="userProfileContent"></div>
    </div>
</div>

<script>
// 1. Amis (Fichier 14)[cite: 12]
function loadFriends() {
    const list = document.getElementById('friends-list');
    if(!list) return;
    fetch('fetch_friends.php')
        .then(r => r.text())
        .then(data => { list.innerHTML = data; });
}

// ---- Gestion amis ----
function toggleAddFriend() {
    const z = document.getElementById('addFriendZone');
    z.style.display = z.style.display === 'none' ? 'block' : 'none';
    if (z.style.display === 'block') document.getElementById('friendSearchInput').focus();
}

let friendSearchTimer = null;
function searchFriendToAdd(q) {
    clearTimeout(friendSearchTimer);
    const box = document.getElementById('friendSearchResults');
    if (q.length < 2) { box.innerHTML = ''; return; }
    friendSearchTimer = setTimeout(() => {
        fetch('search_users.php?q=' + encodeURIComponent(q))
            .then(r => r.json())
            .then(data => {
                if (!data.length) { box.innerHTML = '<div style="font-size:0.62rem;color:#aaa;padding:3px;">Aucun résultat</div>'; return; }
                box.innerHTML = data.map(u =>
                    `<div class="d-flex align-items-center justify-content-between py-1" style="border-bottom:1px solid #111;">
                        <span class="text-white" style="font-size:0.68rem;">${u.username}</span>
                        <button onclick="addFriend(${u.id},'${u.username.replace(/'/g,"\\'")}',this)"
                                class="btn btn-xs btn-outline-success py-0" style="font-size:0.58rem;">+ Ami</button>
                    </div>`
                ).join('');
            });
    }, 300);
}

function addFriend(id, name, btn) {
    btn.disabled = true;
    btn.innerText = '...';
    fetch('friend_actions.php?action=request&id=' + id)
        .then(r => r.text())
        .then(() => {
            btn.innerText = '⏳ Demande envoyée';
            btn.classList.replace('btn-outline-success', 'btn-outline-secondary');
        })
        .catch(() => { btn.disabled = false; btn.innerText = '+ Ami'; });
}

function acceptFriend(id, btn) {
    btn.disabled = true;
    fetch('friend_actions.php?action=accept&id=' + id)
        .then(() => { loadFriends(); });
}
function declineFriend(id, btn) {
    btn.disabled = true;
    fetch('friend_actions.php?action=decline&id=' + id)
        .then(() => { loadFriends(); });
}

function openFriendMenu(id, name) {
    document.getElementById('friendName').innerText = name;
    document.getElementById('friendActionsBody').innerHTML = `
        <button class="btn btn-warning btn-sm w-100 mb-2 fw-bold" onclick="openFriendBet(${id}, '${name.replace(/'/g,"\\'")}'); bootstrap.Modal.getInstance(document.getElementById('friendActionModal')).hide();" style="color:#000;">
            ⚡ Gage rapide avec ${name}
        </button>
        <button class="btn btn-info btn-sm w-100 mb-2" onclick="window.location='messages.php?with=${id}'">
            📩 Envoyer un message
        </button>
        <button class="btn btn-outline-light btn-sm w-100 mb-2" onclick="viewProfile(${id})">
            👤 Voir le profil
        </button>
        <button class="btn btn-warning btn-sm w-100 mb-2" data-fav="0" id="favBtn_${id}" onclick="toggleFav(${id}, this)">
            Ajouter favori
        </button>
        <button class="btn btn-outline-warning btn-sm w-100 mb-2" onclick="openRating(${id}, '${name}')">
            ★ Evaluer ce membre
        </button>
        <button class="btn btn-outline-secondary btn-sm w-100 mb-2" onclick="sendPoke(${id})">
            👉 Envoyer un Poke
        </button>
        <button class="btn btn-outline-danger btn-sm w-100" onclick="removeFriend(${id})" >
            ✕ Retirer des amis
        </button>
    `;
    new bootstrap.Modal(document.getElementById('friendActionModal')).show();
}

function openFriendBet(id, name) {
    document.getElementById('fbP2Id').value = id;
    document.getElementById('fbFriendName').innerText = name;
    document.getElementById('fbDesc').value = '';
    document.getElementById('fbEcheance').value = '';
    document.getElementById('fbAmount').value = '5';
    document.getElementById('fbError').style.display = 'none';
    if (document.getElementById('fbUseWallet')) {
        document.getElementById('fbUseWallet').checked = false;
        document.getElementById('fbWalletRow').style.display = 'none';
    }
    if (document.getElementById('fbHonorPledge')) document.getElementById('fbHonorPledge').checked = false;
    new bootstrap.Modal(document.getElementById('friendBetModal')).show();
}

function submitFriendBet() {
    const desc  = document.getElementById('fbDesc').value.trim();
    const ech   = document.getElementById('fbEcheance').value.trim();
    const errEl = document.getElementById('fbError');
    if (!desc) { errEl.textContent = '⚠ Décris le gage avant de lancer.'; errEl.style.display='block'; return; }
    if (!ech)  { errEl.textContent = '⚠ La date limite est obligatoire.'; errEl.style.display='block'; return; }
    errEl.style.display = 'none';
    document.getElementById('friendBetForm').submit();
}

function toggleFav(id, btn) {
    const isFav = btn.dataset.fav === '1';
    const newFav = isFav ? 0 : 1;
    fetch('friend_actions.php?action=favorite&id=' + id + '&fav=' + newFav)
        .then(() => {
            btn.dataset.fav = newFav;
            btn.innerText = newFav ? 'Retirer favori' : 'Ajouter favori';
            btn.classList.toggle('btn-success', newFav == 1);
            btn.classList.toggle('btn-warning', newFav == 0);
            loadFriends();
        });
}

function removeFriend(id) {
    if (!confirm('Retirer cet ami ?')) return;
    fetch('friend_actions.php?action=remove&id=' + id)
        .then(() => { bootstrap.Modal.getInstance(document.getElementById('friendActionModal')).hide(); loadFriends(); });
}

function sendPoke(id) {
    const fd = new FormData();
    fd.append('send_pm', '1');
    fd.append('receiver_id', id);
    fd.append('content', '👉 POKE !');
    fetch('messages.php', { method:'POST', body:fd })
        .then(() => {
            bootstrap.Modal.getInstance(document.getElementById('friendActionModal'))?.hide();
            // Petit feedback visuel
            const toast = document.createElement('div');
            toast.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#0d6efd;color:#fff;padding:8px 16px;border-radius:6px;font-size:0.75rem;z-index:9999;';
            toast.innerText = '👉 Poke envoyé !';
            document.body.appendChild(toast);
            setTimeout(() => toast.remove(), 2500);
        });
}

// 2. Chat & Rankings
let lastChatHTML = '';
function loadMessages() {
    const cb = document.getElementById('chat-box');
    if (!cb) return;
    const wasAtBottom = cb.scrollHeight - cb.scrollTop <= cb.clientHeight + 30;

    fetch('fetch_messages.php').then(r => r.text()).then(data => {
        if (!data || data === lastChatHTML) return; // Rien de nouveau
        lastChatHTML = data;
        cb.innerHTML = data;
        // Scroll vers le bas seulement si on était déjà en bas
        if (wasAtBottom) cb.scrollTop = cb.scrollHeight;
    }).catch(() => {});
}

function sendMessage() {
    const i = document.getElementById('msg-input');
    const photoInput = document.getElementById('chatPhotoInput');
    if (!i) return;

    const content = i.value.trim();
    const pickerBtn = document.getElementById('iconPickerBtn');
    const selectedIcon  = (pickerBtn && pickerBtn.innerText !== '+') ? pickerBtn.innerText.trim() : '';
    const selectedColor = document.getElementById('chatColorPicker')?.value || '';
    const hasPhoto = photoInput && photoInput.files.length > 0;

    if (!content && !hasPhoto) return;

    const showProgress = hasPhoto;
    if (showProgress) {
        document.getElementById('chatUploadProgress').style.display = 'block';
        let pct = 0;
        const interval = setInterval(() => {
            pct = Math.min(pct + 15, 85);
            document.getElementById('chatProgressBar').style.width = pct + '%';
        }, 150);

        const fd = new FormData();
        fd.append('content', content);
        if (selectedIcon)  fd.append('icon', selectedIcon);
        if (selectedColor && selectedColor !== '#e0e0e0') fd.append('text_color', selectedColor);
        fd.append('chat_photo', photoInput.files[0]);

        fetch('circle_wall.php', { method:'POST', body:fd }).then(() => {
            clearInterval(interval);
            document.getElementById('chatProgressBar').style.width = '100%';
            document.getElementById('chatProgressLabel').innerText = 'Envoyé !';
            setTimeout(() => {
                document.getElementById('chatUploadProgress').style.display = 'none';
                document.getElementById('chatProgressBar').style.width = '0%';
            }, 800);
            i.value = ''; clearIcon(); clearChatPhoto(); loadMessages();
        });
    } else {
        const p = new URLSearchParams();
        p.append('content', content);
        if (selectedIcon)  p.append('icon', selectedIcon);
        if (selectedColor && selectedColor !== '#e0e0e0') p.append('text_color', selectedColor);
        fetch('circle_wall.php', { method:'POST', body:p }).then(() => {
            i.value = ''; clearIcon(); loadMessages();
        });
    }
}

// Flatpickr dans les modales de gage
function openModalCal(betId) {
    const el = document.getElementById('modalCal' + betId);
    if (!el) return;
    if (!el._flatpickr) {
        flatpickr(el, {
            locale: 'fr',
            dateFormat: 'Y-m-d',
            altInput: true,
            altFormat: 'j F Y',
            minDate: 'today',
            disableMobile: true,
        });
    }
    el._flatpickr.open();
}

// ---- Changer de cercle ----
function changeCircle(circleId) {
    const cb = document.getElementById('chat-box');
    if (cb) cb.innerHTML = '<div class="text-muted text-center py-3" style="font-size:0.7rem;">Chargement...</div>';
    // Sync le dropdown du filtre
    const filtSel = document.getElementById('circleSwitch');
    if (filtSel && filtSel.value !== String(circleId)) filtSel.value = circleId;
    // Sync le dropdown du chat
    const chatSel = document.getElementById('circleSelector');
    if (chatSel && chatSel.value !== String(circleId)) chatSel.value = circleId;
    fetch('set_circle.php?id=' + circleId)
        .then(r => r.text())
        .then(res => {
            if (res.trim() === 'ok') {
                loadMessages();
            } else {
                if (cb) cb.innerHTML = '<div class="text-danger text-center py-2" style="font-size:0.7rem;">Erreur: ' + res + '</div>';
            }
        })
        .catch(() => { loadMessages(); });
}

// ---- Icônes chat ----
let iconPickerOpen = false;
function toggleIconPicker() {
    const picker = document.getElementById('iconPickerInline');
    if (!picker) return;
    iconPickerOpen = !iconPickerOpen;
    picker.style.display = iconPickerOpen ? 'flex' : 'none';
    const btn = document.getElementById('iconPickerBtn');
    if (btn) btn.style.borderColor = iconPickerOpen ? '#0dcaf0' : '';
}
function selectIcon(el) {
    const emoji = el.dataset.emoji;
    const display = document.getElementById('selectedIconDisplay');
    const pickerBtn = document.getElementById('iconPickerBtn');
    if (display) { display.innerText = emoji; display.dataset.emoji = emoji; }
    if (pickerBtn) { pickerBtn.innerText = emoji; pickerBtn.style.display = 'inline-flex'; }
    toggleIconPicker();
}
function clearIcon() {
    const display = document.getElementById('selectedIconDisplay');
    const pickerBtn = document.getElementById('iconPickerBtn');
    if (display) { display.innerText = ''; display.dataset.emoji = ''; }
    if (pickerBtn) { pickerBtn.style.display = 'none'; }
}
function resetColor() {
    const cp = document.getElementById('chatColorPicker');
    if (cp) cp.value = '#e0e0e0';
}

// ---- Photo chat ----
function previewChatPhoto(input) {
    if (!input.files.length) return;
    const preview = document.getElementById('chatPhotoPreview');
    const img     = document.getElementById('chatPhotoImg');
    const reader  = new FileReader();
    reader.onload = e => { img.src = e.target.result; preview.style.display = ''; };
    reader.readAsDataURL(input.files[0]);
    document.getElementById('chatExtras').style.display = 'flex';
}
function clearChatPhoto() {
    const input   = document.getElementById('chatPhotoInput');
    const preview = document.getElementById('chatPhotoPreview');
    if (input)   input.value = '';
    if (preview) preview.style.display = 'none';
}

// ---- Toast bonus journalier ----
<?php if (isset($_SESSION['daily_bonus_today']) && $_SESSION['daily_bonus_today'] > 0): ?>
document.addEventListener('DOMContentLoaded', function() {
    const toast = document.createElement('div');
    toast.style.cssText = 'position:fixed;bottom:24px;left:50%;transform:translateX(-50%);background:#ffc107;color:#000;padding:10px 20px;border-radius:8px;font-size:0.8rem;z-index:9999;font-weight:bold;box-shadow:0 4px 12px rgba(0,0,0,0.4);';
    toast.innerHTML = '+<?= (int)$_SESSION['daily_bonus_today'] ?> jetons — Bonus de connexion !';
    <?php if ($isMinor): ?>if(true){toast.remove();return;}<?php endif; // Pas de bonus jetons pour mineurs ?>
    document.body.appendChild(toast);
    setTimeout(() => { toast.style.opacity='0'; toast.style.transition='opacity 0.5s'; setTimeout(()=>toast.remove(),500); }, 3000);
    <?php unset($_SESSION['daily_bonus_today']); ?>
});
<?php endif; ?>

// ---- Panneaux Dashboard (Pastilles Premium) ----
function openDashPanel(id) {
    const overlay = document.getElementById('dashPanelOverlay');
    if (!overlay) return;
    const titles = {classements:'CLASSEMENTS',chat:'CHAT / MUR',evenements:'EVENEMENTS',medias:'MEDIAS',amis:'AMIS',cercles:'MES CERCLES'};
    document.getElementById('dashPanelTitle').innerText = titles[id] || id.toUpperCase();
    document.getElementById('dashPanelBody').innerHTML  = '<div class="text-muted text-center py-3 small">Chargement...</div>';
    overlay.style.display = 'flex';
    overlay.style.alignItems = 'flex-start';
    overlay.style.justifyContent = 'center';
    document.querySelectorAll('.pastille-btn').forEach(p => p.classList.remove('p-active'));
    const btn = document.getElementById('pastille-' + id);
    if (btn) { btn.classList.add('p-active'); btn.style.opacity = '1'; }
    // Afficher le bouton plein écran seulement pour le mur/chat
    const fsBtn = document.getElementById('dashPanelFullscreenBtn');
    if (fsBtn) fsBtn.style.display = (id === 'chat') ? 'inline-block' : 'none';
    switch(id) {
        case 'classements': loadPanelClassements(); break;
        case 'chat':        loadPanelChat();        break;
        case 'evenements':  loadPanelEvenements();  break;
        case 'medias':      loadPanelMedias();      break;
        case 'amis':        loadPanelAmis();      break;
        case 'cercles':     loadPanelCercles();   break;
    }
}
function closeDashPanel() {
    const overlay = document.getElementById('dashPanelOverlay');
    if (overlay) overlay.style.display = 'none';
    document.querySelectorAll('.pastille-btn').forEach(p => { p.classList.remove('p-active'); });
}
function loadPanelClassements() {
    const body = document.getElementById('dashPanelBody');
    body.innerHTML = ''
        + '<div style="margin-bottom:6px;display:flex;gap:6px;align-items:center;">'
        + '<select id="panelRankSelect" onchange="panelLoadRank(this.value)" style="background:#111;border:1px solid #333;color:#ffc107;border-radius:4px;padding:3px 8px;font-size:0.65rem;flex:1;">'
        + '<option value="points">Honneur</option>'
        + '<option value="gain_perte">Gain/Perte</option>'
        + '<option value="gages">Gages</option>'
        + (<?= $isIsolated ? 'true' : 'false' ?> ? '<option value="honores">Honorés</option>' : '') // v1.7
        + '<option value="interaction">Interactions</option>'
        + '<option value="fiable">Fiables</option>'
        + (<?= ($isMinor || $isPrivateUser) ? 'false' : 'true' ?> ? '<option value="wallet">Jetons</option>' : '')
        + '</select>'
        + '<div style="display:flex;gap:3px;">'
        + ['all:Tout','week:Sem.','month:Mois','year:An'].map(p => { const [v,l]=p.split(':'); return `<button onclick="setPanelRankPeriod('${v}')" data-pp="${v}" style="background:none;border:1px solid #333;color:#aaa;border-radius:4px;padding:1px 5px;font-size:0.5rem;cursor:pointer;" class="panel-period-btn">${l}</button>`; }).join('')
        + '</div>'
        + '</div>'
        + '<table class="table table-dark table-sm mb-0 small" style="width:100%;">'
        + '<tbody id="panelRankingTable"><tr><td class="text-muted text-center py-2">Chargement...</td></tr></tbody>'
        + '</table>';
    setTimeout(() => { setPanelRankPeriod('all'); panelLoadRank('points'); }, 50);
}
let _panelRankPeriod = 'all';
function setPanelRankPeriod(p) {
    _panelRankPeriod = p;
    document.querySelectorAll('.panel-period-btn').forEach(b => { b.style.opacity = b.dataset.pp===p?'1':'0.4'; b.style.fontWeight = b.dataset.pp===p?'700':'400'; });
    panelLoadRank(document.getElementById('panelRankSelect')?.value || 'points');
}
function panelLoadRank(type) {
    fetch('fetch_rankings.php?type=' + type + '&period=' + _panelRankPeriod)
        .then(r => {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.text();
        })
        .then(html => {
            const tb = document.getElementById('panelRankingTable');
            if (tb && html.trim()) {
                tb.innerHTML = html;
            } else if (tb) {
                tb.innerHTML = '<tr><td class="text-muted text-center py-2">Aucune donnee</td></tr>';
            }
        })
        .catch(err => {
            const tb = document.getElementById('panelRankingTable');
            if (tb) tb.innerHTML = '<tr><td class="text-danger text-center py-2 small">Erreur: ' + err.message + '</td></tr>';
        });
}
function loadPanelChat() {
    const src = document.getElementById('chatCard');
    if (!src) return;
    const clone = src.cloneNode(true);
    clone.id = 'chatCardClone';
    clone.style.height = '60vh';
    document.getElementById('dashPanelBody').innerHTML = '';
    document.getElementById('dashPanelBody').style.padding = '0';
    document.getElementById('dashPanelBody').appendChild(clone);
    const origBox = document.getElementById('chat-box');
    const cloneBox = clone.querySelector('#chat-box');
    if (origBox && cloneBox) { cloneBox.innerHTML = origBox.innerHTML; cloneBox.scrollTop = cloneBox.scrollHeight; }
    const ci = clone.querySelector('#chatInput');
    if (ci) {
        ci.id = 'chatInputPanel';
        ci.addEventListener('keypress', e => {
            if (e.key !== 'Enter') return;
            const m = document.getElementById('chatInput');
            if (m) { m.value = ci.value; sendMessage(); ci.value = ''; }
        });
    }
    clearInterval(window._panelChatSync);
    window._panelChatSync = setInterval(() => {
        const ov = document.getElementById('dashPanelOverlay');
        if (!ov || ov.style.display === 'none') { clearInterval(window._panelChatSync); return; }
        const orig = document.getElementById('chat-box');
        const cl = document.getElementById('chatCardClone');
        const clB = cl ? cl.querySelector('#chat-box') : null;
        if (orig && clB) clB.innerHTML = orig.innerHTML;
    }, 3000);
}
function loadPanelEvenements() {
    const body = document.getElementById('dashPanelBody');
    body.innerHTML = ''
        + '<div style="margin-bottom:6px;display:flex;gap:6px;">'
        + '<button onclick="panelEvView(\'list\')" id="panelEvList" class="btn btn-warning btn-xs py-0" style="font-size:0.6rem;">Liste</button>'
        + '<button onclick="panelEvView(\'cal\')"  id="panelEvCal"  class="btn btn-outline-warning btn-xs py-0" style="font-size:0.6rem;">Calendrier</button>'
        + '</div>'
        + '<div id="panelEvContent" style="font-size:0.78rem;overflow-y:auto;max-height:70vh;">'
        + '<div class="text-muted small text-center py-2">Chargement...</div>'
        + '</div>';
    setTimeout(() => panelEvView('list'), 50);
}
function panelEvView(mode) {
    const dest = document.getElementById('panelEvContent');
    if (!dest) return;
    if (mode === 'list') {
        dest.innerHTML = '<div class="text-muted small text-center py-2">Chargement...</div>';
        fetch('fetch_panel_events.php')
            .then(r => {
                if (!r.ok) throw new Error('HTTP ' + r.status);
                return r.text();
            })
            .then(html => {
                dest.innerHTML = html && html.trim()
                    ? html
                    : '<p class="text-muted small text-center py-3">Aucun evenement a venir.</p>';
            })
            .catch(err => {
                dest.innerHTML = '<p class="text-danger small text-center py-3">Erreur: ' + err.message + '</p>';
            });
    } else {
        dest.innerHTML = '<div class="text-muted small text-center py-2">Chargement...</div>';
        fetch('fetch_panel_events.php?view=cal')
            .then(r => r.text())
            .then(html => {
                dest.innerHTML = html && html.trim()
                    ? html
                    : '<p class="text-muted small text-center py-3">Aucun événement.</p>';
            })
            .catch(() => {
                dest.innerHTML = '<p class="text-danger small text-center py-3">Erreur chargement calendrier.</p>';
            });
    }
    const bl = document.getElementById('panelEvList');
    const bc = document.getElementById('panelEvCal');
    if (bl) { bl.className = 'btn btn-xs py-0 ' + (mode==='list'?'btn-warning':'btn-outline-warning'); bl.style.fontSize='0.6rem'; }
    if (bc) { bc.className = 'btn btn-xs py-0 ' + (mode==='cal' ?'btn-warning':'btn-outline-warning'); bc.style.fontSize='0.6rem'; }
}
// ── PANEL CERCLES — visible pour tous ─────────────────────────
function loadPanelCercles() {
    const body = document.getElementById('dashPanelBody');
    body.innerHTML = '<div class="text-muted text-center py-3 small">Chargement...</div>';

    fetch('fetch_user_circles.php')
        .then(r => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.text(); })
        .then(html => {
            if (!html || !html.trim()) {
                body.innerHTML = '<p class="text-muted small text-center py-4">Aucun cercle.</p>';
                return;
            }
            // Injecter HTML sans les balises <script>
            const noScript = html.replace(/<script[\s\S]*?<\/script>/gi, '');
            body.innerHTML = noScript;

            // Extraire et exécuter les scripts manuellement
            const scriptMatch = html.match(/<script[^>]*>([\s\S]*?)<\/script>/i);
            if (scriptMatch) {
                try { new Function(scriptMatch[1])(); } catch(e) { console.error('CC script error:', e); }
            }
        })
        .catch(err => {
            body.innerHTML = '<p class="text-danger small text-center py-3">Erreur: ' + err.message + '</p>';
        });
}

// ── Fonctions globales des cercles (injectées ici car innerHTML ne lance pas les <script>) ──
function ncTab(t){
    ['creer','rejoindre'].forEach(id=>{
        const s=document.getElementById('nc-sec-'+id);
        const tab=document.getElementById('nc-tab-'+id);
        if(s) s.style.display=id===t?'block':'none';
        if(tab) tab.classList.toggle('active',id===t);
    });
}

function ccToggleSection(id){
    const el=document.getElementById(id);
    if(!el)return;
    const isOpen=el.style.display!=='none'&&el.style.display!=='';
    ['cc-bet','cc-manage','cc-new-circle','cc-join'].forEach(sid=>{
        const s=document.getElementById(sid);
        if(s&&sid!==id) s.style.display='none';
    });
    el.style.display=isOpen?'none':'block';
    if(!isOpen && id==='cc-manage') {
        // Forcer l'onglet membres visible
        ['membres','inviter','code'].forEach(t=>{
            const p=document.getElementById('mp-'+t);
            const tab=document.getElementById('mt-'+t);
            if(p) p.style.display=t==='membres'?'block':'none';
            if(tab) tab.classList.toggle('active',t==='membres');
        });
    }
}

function ccManTab(t){
    ['membres','inviter','code'].forEach(id=>{
        const p=document.getElementById('mp-'+id);
        const tab=document.getElementById('mt-'+id);
        if(p) p.style.display=id===t?'block':'none';
        if(tab) tab.classList.toggle('active',id===t);
    });
}

function ccSwitchCircle(id){
    fetch('fetch_user_circles.php?action=switch&id='+id)
        .then(r=>r.text()).then(res=>{
            if(res.trim()==='ok'){
                const t=document.createElement('div');
                t.style.cssText='position:fixed;bottom:20px;right:20px;background:#fd7e14;color:#000;padding:8px 16px;border-radius:6px;font-size:0.75rem;font-weight:700;z-index:9999;';
                t.textContent='Cercle activé ! Rechargement...';
                document.body.appendChild(t);
                setTimeout(()=>window.location.reload(),800);
            }
        });
}

function ccLeave(id,name){
    if(!confirm('Quitter "'+name+'" ?'))return;
    fetch('fetch_user_circles.php?action=leave&id='+id)
        .then(r=>r.text()).then(()=>window.location.reload());
}

function ccCreate(){
    const nameEl=document.getElementById('cc-new-name');
    const name=nameEl?nameEl.value.trim():'';
    const msg=document.getElementById('cc-new-msg');
    if(!name){ccShowMsg(msg,'Nom requis.','danger');return;}
    const fd=new FormData();fd.append('name',name);
    fetch('fetch_user_circles.php?action=create',{method:'POST',body:fd})
        .then(r=>r.json()).then(data=>{
            if(data.error){ccShowMsg(msg,data.error,'danger');return;}
            window.location.reload();
        });
}

function ncCreate(){
    const nameEl=document.getElementById('nc-name');
    const name=nameEl?nameEl.value.trim():'';
    const msg=document.getElementById('nc-create-msg');
    if(!name){ccShowMsg(msg,'Nom requis.','danger');return;}
    const fd=new FormData();fd.append('name',name);
    fetch('fetch_user_circles.php?action=create',{method:'POST',body:fd})
        .then(r=>r.json()).then(data=>{
            if(data.error){ccShowMsg(msg,data.error,'danger');return;}
            window.location.reload();
        });
}

function ccJoin(){
    const codeEl=document.getElementById('cc-join-code');
    const code=codeEl?codeEl.value.trim().toUpperCase():'';
    const msg=document.getElementById('cc-join-msg');
    if(!code){ccShowMsg(msg,'Entrez un code.','danger');return;}
    fetch('fetch_user_circles.php?action=join_code&code='+encodeURIComponent(code))
        .then(r=>r.json()).then(data=>{
            if(data.error){ccShowMsg(msg,data.error,'danger');return;}
            if(data.pending){ccShowMsg(msg,'⏳ '+(data.msg||"Demande envoyée — en attente d'approbation."),'warning');return;}
            window.location.reload();
        });
}

function ncJoin(){
    const codeEl=document.getElementById('nc-code');
    const code=codeEl?codeEl.value.trim().toUpperCase():'';
    const msg=document.getElementById('nc-join-msg');
    if(!code){ccShowMsg(msg,'Entrez un code.','danger');return;}
    fetch('fetch_user_circles.php?action=join_code&code='+encodeURIComponent(code))
        .then(r=>r.json()).then(data=>{
            if(data.error){ccShowMsg(msg,data.error,'danger');return;}
            if(data.pending){ccShowMsg(msg,'⏳ '+(data.msg||"Demande envoyée — en attente d'approbation."),'warning');return;}
            window.location.reload();
        });
}

function ccSubmitBet(circleId){
    const descEl=document.getElementById('cc-bet-desc');
    const p2El=document.getElementById('cc-bet-p2');
    const ptsEl=document.getElementById('cc-bet-pts');
    const desc=descEl?descEl.value.trim():'';
    const p2=p2El?p2El.value.trim():'';
    const pts=ptsEl?parseInt(ptsEl.value)||0:0;
    const msg=document.getElementById('cc-bet-msg');
    if(!desc){ccShowMsg(msg,'Décris le gage.','danger');return;}
    const fd=new FormData();
    fd.append('create_bet','1');
    fd.append('description',desc);
    fd.append('amount',pts);
    fd.append('parieur2',p2);
    fd.append('circle_id',circleId);
    fetch('index.php',{method:'POST',body:fd})
        .then(()=>{
            ccShowMsg(msg,'Gage lancé !','success');
            if(descEl) descEl.value='';
            if(p2El) p2El.value='';
            setTimeout(()=>{closeDashPanel();window.location.reload();},1200);
        }).catch(()=>ccShowMsg(msg,'Erreur','danger'));
}

function ccSearchInv(cid,q){
    const box=document.getElementById('cc-inv-results');
    if(!box||q.length<2){if(box)box.innerHTML='';return;}
    fetch('fetch_user_circles.php?action=search_users&cid='+cid+'&q='+encodeURIComponent(q))
        .then(r=>r.json()).then(users=>{
            if(!users.length){box.innerHTML='<div style="font-size:0.62rem;color:#888;padding:3px;">Aucun résultat</div>';return;}
            box.innerHTML=users.map(u=>`
                <div style="display:flex;justify-content:space-between;align-items:center;padding:3px 0;border-bottom:1px solid #0d0d0d;">
                    <span style="font-size:0.7rem;color:#ddd;">${u.username}</span>
                    <button onclick="document.getElementById('cc-inv-name').value='${u.username.replace(/'/g,"\\'")}';"
                            style="background:rgba(40,167,69,0.15);border:1px solid #28a745;color:#777;border-radius:3px;padding:1px 6px;font-size:0.6rem;cursor:pointer;">Choisir</button>
                </div>`).join('');
        });
}

function ccInvite(cid){
    const nameEl=document.getElementById('cc-inv-name');
    const name=nameEl?nameEl.value.trim():'';
    const msg=document.getElementById('cc-inv-msg');
    if(!name){ccShowMsg(msg,'Entrez un nom.','danger');return;}
    const fd=new FormData();fd.append('username',name);
    fetch('fetch_user_circles.php?action=invite&cid='+cid,{method:'POST',body:fd})
        .then(r=>r.json()).then(data=>{
            if(data.error){ccShowMsg(msg,data.error,'danger');return;}
            ccShowMsg(msg,data.msg,'success');
            if(nameEl)nameEl.value='';
            const r=document.getElementById('cc-inv-results');if(r)r.innerHTML='';
            const s=document.getElementById('cc-inv-search');if(s)s.value='';
        });
}

function ccRemoveMember(cid,mid,name){
    if(!confirm('Retirer '+name+' ?'))return;
    fetch('fetch_user_circles.php?action=remove_member&cid='+cid+'&mid='+mid)
        .then(()=>window.location.reload());
}

function ccCopyCode(code,btn){ ccCopyCodeFallback(code,btn); }
function ccCopyCodeFallback(code,btn){
    const success = () => {
        const o=btn.innerHTML; btn.innerHTML='✓ Copié!'; btn.style.color='#28a745';
        setTimeout(()=>{ btn.innerHTML=o; btn.style.color=''; },1800);
    };
    // Essayer clipboard API (HTTPS seulement)
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(code).then(success).catch(()=>fallback());
    } else {
        fallback();
    }
    function fallback() {
        // Méthode textarea - fonctionne en HTTP
        const ta = document.createElement('textarea');
        ta.value = code; ta.style.position='fixed'; ta.style.opacity='0';
        document.body.appendChild(ta); ta.select();
        try { document.execCommand('copy'); success(); }
        catch(e) { prompt('Code du cercle (copier manuellement):', code); }
        document.body.removeChild(ta);
    }
}

function ccShowMsg(el,msg,type){
    if(!el)return;
    el.style.display='block';
    el.style.background=type==='success'?'rgba(40,167,69,0.15)':'rgba(220,53,69,0.15)';
    el.style.border='1px solid '+(type==='success'?'#28a745':'#dc3545');
    el.style.color=type==='success'?'#28a745':'#dc3545';
    el.textContent=msg;
    setTimeout(()=>{el.style.display='none';},4000);
}

// ── PANEL AMIS complet ────────────────────────────────────────
function loadPanelAmis() {
    const body    = document.getElementById('dashPanelBody');
    const toolbar = document.getElementById('dashPanelToolbar');
    body.innerHTML = '';

    // Toolbar FIXE au-dessus du scroll (dans dashPanelToolbar)
    if (toolbar) {
        toolbar.style.display = 'block';
        toolbar.style.cssText = 'flex-shrink:0;padding:6px 8px;border-bottom:1px solid #1a1a2a;background:#0a0a12;';
        toolbar.innerHTML = `
            <div style="display:flex;gap:6px;align-items:center;">
                <input id="panelFriendSearch" type="text" placeholder="Rechercher un membre..." autocomplete="off"
                       style="flex:1;background:#0a0a14;border:1px solid #333;color:#ddd;border-radius:5px;padding:4px 8px;font-size:0.68rem;"
                       oninput="panelSearchFriend(this.value)">
                <button onclick="loadPanelAmis()" title="Rafraîchir"
                        style="background:none;border:1px solid #333;color:#aaa;border-radius:5px;padding:3px 7px;font-size:0.68rem;cursor:pointer;">↻</button>
            </div>
            <div id="panelFriendSearchResults" style="margin-top:4px;"></div>`;
    }

    // Zone liste amis (scrollable dans dashPanelBody)
    const listBox = document.createElement('div');
    listBox.id = 'panelFriendList';
    listBox.innerHTML = '<div class="text-muted text-center py-2" style="font-size:0.7rem;">Chargement...</div>';
    body.appendChild(listBox);

    // Zone menu ami (inline)
    const menuBox = document.createElement('div');
    menuBox.id = 'panelFriendMenu';
    menuBox.style.display = 'none';
    body.appendChild(menuBox);

    panelRefreshFriends();
}

function panelRefreshFriends() {
    const box = document.getElementById('panelFriendList');
    if (!box) return;
    box.innerHTML = '<div class="text-muted text-center py-2" style="font-size:0.7rem;">Chargement...</div>';
    fetch('fetch_friends.php')
        .then(r => { if (!r.ok) throw new Error('HTTP '+r.status); return r.text(); })
        .then(html => {
            box.innerHTML = html || '<div class="text-muted text-center py-3" style="font-size:0.7rem;">Aucun ami pour l\'instant.</div>';
            // Scroll vers le haut pour voir les demandes en attente
            const body = document.getElementById('dashPanelBody');
            if (body) body.scrollTop = 0;
        })
        .catch(err => { box.innerHTML = '<div class="text-danger text-center py-2" style="font-size:0.7rem;">Erreur: '+err.message+'</div>'; });
}

let _pfsTimer = null;
function panelSearchFriend(q) {
    clearTimeout(_pfsTimer);
    const box = document.getElementById('panelFriendSearchResults');
    if (!box) return;
    if (q.length < 2) { box.innerHTML = ''; return; }
    _pfsTimer = setTimeout(() => {
        fetch('search_users.php?q=' + encodeURIComponent(q))
            .then(r => r.json())
            .then(data => {
                if (!data.length) { box.innerHTML = '<div style="font-size:0.62rem;color:#aaa;padding:3px 2px;">Aucun r\u00e9sultat</div>'; return; }
                box.innerHTML = '<div style="font-size:0.6rem;color:#999;margin-bottom:4px;letter-spacing:0.5px;">R\u00c9SULTATS</div>'
                    + data.map(u => {
                        let btn = '';
                        const rel = u.relation || 'aucun';
                        if (rel === 'ami') {
                            btn = '<span style="background:rgba(40,167,69,0.15);border:1px solid #28a745;color:#777;border-radius:4px;padding:2px 8px;font-size:0.6rem;">\u2713 Ami</span>';
                        } else if (rel === 'envoyee') {
                            btn = '<span style="background:rgba(108,117,125,0.15);border:1px solid #555;color:#aaa;border-radius:4px;padding:2px 8px;font-size:0.6rem;">\u23f3 Envoy\u00e9e</span>';
                        } else if (rel === 'recue') {
                            btn = '<div style="display:flex;gap:3px;">'
                                + '<button onclick="panelAcceptFriend(' + u.id + ')" style="background:rgba(40,167,69,0.2);border:1px solid #28a745;color:#777;border-radius:4px;padding:2px 7px;font-size:0.6rem;cursor:pointer;">\u2713 Accepter</button>'
                                + '<button onclick="panelDeclineFriend(' + u.id + ')" style="background:rgba(220,53,69,0.15);border:1px solid #dc3545;color:#dc3545;border-radius:4px;padding:2px 7px;font-size:0.6rem;cursor:pointer;">\u2715</button>'
                                + '</div>';
                        } else {
                            btn = '<button onclick="panelAddFriend(' + u.id + ',\'' + u.username.replace(/'/g,"\\'") + '\',this)" style="background:rgba(13,202,240,0.15);border:1px solid #0dcaf0;color:#0dcaf0;border-radius:4px;padding:2px 8px;font-size:0.6rem;cursor:pointer;">+ Ami</button>';
                        }
                        const circleBadge = u.in_circle
                            ? '<span style="font-size:0.5rem;background:rgba(253,126,20,0.2);border:1px solid #fd7e14;color:#fd7e14;border-radius:3px;padding:0 4px;margin-left:4px;">Cercle</span>'
                            : '';
                        return '<div style="display:flex;align-items:center;justify-content:space-between;padding:5px 6px;background:#0a0a14;border:1px solid #1a1a2a;border-radius:5px;margin-bottom:3px;">'
                            + '<div><span style="font-size:0.72rem;color:#ddd;font-weight:600;">' + u.username + '</span>' + circleBadge + '</div>'
                            + btn + '</div>';
                    }).join('');
            })
            .catch(() => { box.innerHTML = ''; });
    }, 300);
}


function panelAddFriend(id, name, btn) {
    btn.disabled = true; btn.innerText = '...';
    fetch('friend_actions.php?action=request&id=' + id)
        .then(r => r.text())
        .then(() => {
            btn.innerText = '⏳ Envoyée';
            btn.style.color = '#aaa'; btn.style.borderColor = '#555';
        })
        .catch(() => { btn.disabled = false; btn.innerText = '+ Ami'; });
}

function panelOpenFriendMenu(id, name, isFav) {
    // Cacher la liste, afficher le menu
    const listBox = document.getElementById('panelFriendList');
    const menuBox = document.getElementById('panelFriendMenu');
    if (listBox) listBox.style.display = 'none';
    if (!menuBox) return;
    menuBox.style.display = 'block';
    menuBox.innerHTML = `
        <div style="display:flex;align-items:center;gap:8px;margin-bottom:10px;padding-bottom:8px;border-bottom:1px solid #1a1a3a;">
            <button onclick="panelCloseFriendMenu()" title="Retour"
                    style="background:none;border:1px solid #333;color:#aaa;border-radius:5px;padding:3px 8px;font-size:0.75rem;cursor:pointer;">← Retour</button>
            <span style="font-size:0.8rem;font-weight:bold;color:#0dcaf0;">${name}</span>
        </div>
        <div style="display:flex;flex-direction:column;gap:6px;">
            <button onclick="openFriendBet(${id}, '${name.replace(/'/g,"\\'")}'); panelCloseFriendMenu();"
                    style="background:rgba(255,193,7,0.15);border:2px solid #ffc107;color:#ffc107;border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:700;cursor:pointer;text-align:left;">
                ⚡ &nbsp;Gage rapide avec ${name}
            </button>
            <button onclick="window.location='messages.php?with=${id}'"
                    style="background:rgba(13,110,253,0.15);border:1px solid rgba(13,110,253,0.4);color:#888;border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:600;cursor:pointer;text-align:left;">
                📩 &nbsp;Envoyer un message
            </button>
            <button onclick="viewProfile(${id})"
                    style="background:rgba(255,255,255,0.05);border:1px solid #333;color:#ddd;border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:600;cursor:pointer;text-align:left;">
                👤 &nbsp;Voir le profil
            </button>
            <button id="panelFavBtn_${id}" data-fav="${isFav?1:0}" onclick="panelToggleFav(${id}, this)"
                    style="background:${isFav?'rgba(40,167,69,0.15)':'rgba(255,193,7,0.1)'};border:1px solid ${isFav?'#28a745':'#ffc107'};color:${isFav?'#28a745':'#ffc107'};border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:600;cursor:pointer;text-align:left;">
                ${isFav ? '⭐ Retirer des favoris' : '☆ Ajouter aux favoris'}
            </button>
            <button onclick="openRating(${id}, '${name}')"
                    style="background:rgba(255,193,7,0.08);border:1px solid rgba(255,193,7,0.3);color:#ffc107;border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:600;cursor:pointer;text-align:left;">
                ★ &nbsp;Évaluer ce membre
            </button>
            <button onclick="panelSendPoke(${id})"
                    style="background:rgba(13,202,240,0.08);border:1px solid rgba(13,202,240,0.3);color:#0dcaf0;border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:600;cursor:pointer;text-align:left;">
                👉 &nbsp;Envoyer un Poke
            </button>
            <div style="border-top:1px solid #1a1a1a;margin-top:4px;padding-top:6px;">
                <button onclick="panelRemoveFriend(${id}, '${name}')"
                        style="background:rgba(220,53,69,0.12);border:1px solid rgba(220,53,69,0.4);color:#dc3545;border-radius:6px;padding:7px 10px;font-size:0.7rem;font-weight:600;cursor:pointer;text-align:left;width:100%;">
                    ✕ &nbsp;Retirer des amis
                </button>
            </div>
        </div>`;
}

function panelCloseFriendMenu() {
    const listBox = document.getElementById('panelFriendList');
    const menuBox = document.getElementById('panelFriendMenu');
    if (listBox) listBox.style.display = 'block';
    if (menuBox) menuBox.style.display = 'none';
    panelRefreshFriends();
}

function panelToggleFav(id, btn) {
    const isFav = btn.dataset.fav === '1';
    const newFav = isFav ? 0 : 1;
    fetch('friend_actions.php?action=favorite&id=' + id + '&fav=' + newFav)
        .then(() => {
            btn.dataset.fav = newFav;
            btn.innerText = newFav ? '⭐ Retirer des favoris' : '☆ Ajouter aux favoris';
            btn.style.background = newFav ? 'rgba(40,167,69,0.15)' : 'rgba(255,193,7,0.1)';
            btn.style.borderColor = newFav ? '#28a745' : '#ffc107';
            btn.style.color       = newFav ? '#28a745' : '#ffc107';
        });
}

function panelSendPoke(id) {
    const fd = new FormData();
    fd.append('send_pm','1'); fd.append('receiver_id', id); fd.append('content','👉 POKE !');
    fetch('messages.php', { method:'POST', body:fd }).then(() => {
        const toast = document.createElement('div');
        toast.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#0d6efd;color:#fff;padding:8px 16px;border-radius:6px;font-size:0.75rem;z-index:9999;';
        toast.innerText = '👉 Poke envoyé !';
        document.body.appendChild(toast);
        setTimeout(() => toast.remove(), 2500);
    });
}

function panelRemoveFriend(id, name) {
    if (!confirm('Retirer ' + name + ' de vos amis ?')) return;
    fetch('friend_actions.php?action=remove&id=' + id)
        .then(() => panelCloseFriendMenu());
}

function panelAcceptFriend(id) {
    fetch('friend_actions.php?action=accept&id=' + id)
        .then(() => panelRefreshFriends());
}

function panelDeclineFriend(id) {
    fetch('friend_actions.php?action=decline&id=' + id)
        .then(() => panelRefreshFriends());
}

function loadPanelMedias() {
    const body = document.getElementById('dashPanelBody');
    const circleId = <?php echo (int)($_SESSION['circle_id'] ?? 0); ?>;

    body.innerHTML = '<div style="text-align:center;padding:20px;color:#999;font-size:0.72rem;">Chargement des médias...</div>';

    // Charger toutes les photos publiques + du cercle
    fetch('get_proofs.php?all=1&public=1&circle_id=' + circleId)
        .then(r => r.json())
        .then(photos => {
            if (!photos.length) {
                body.innerHTML = '<div style="text-align:center;padding:30px;color:#666;font-size:0.72rem;">Aucun média disponible pour l\'instant.</div>';
                return;
            }
            let html = '<div style="display:flex;flex-wrap:wrap;gap:6px;padding:8px;">';
            photos.forEach((p, i) => {
                const ext = (p.file_path || '').split('.').pop().toLowerCase();
                const isVideo = ['mp4','mov','avi','webm'].includes(ext);
                if (isVideo) {
                    html += `<div onclick="openMediaLightbox(${i}, ${JSON.stringify(photos).replace(/"/g,'&quot;')})" style="width:80px;height:80px;background:#0a0a14;border:1px solid #1a1a2a;border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden;">
                        <video src="${p.file_path}" style="width:100%;height:100%;object-fit:cover;" muted></video>
                        <div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.35);">
                            <span style="font-size:1.4rem;">▶</span>
                        </div>
                        <div style="position:absolute;bottom:2px;right:3px;font-size:0.45rem;color:#aaa;">#${p.bet_id}</div>
                    </div>`;
                } else {
                    html += `<div onclick="openMediaLightbox(${i}, ${JSON.stringify(photos).replace(/"/g,'&quot;')})" style="width:80px;height:80px;background:#0a0a14;border:1px solid #1a1a2a;border-radius:6px;cursor:pointer;overflow:hidden;position:relative;">
                        <img src="${p.file_path}" style="width:100%;height:100%;object-fit:cover;" loading="lazy">
                        <div style="position:absolute;bottom:2px;right:3px;font-size:0.45rem;color:#aaa;">#${p.bet_id}</div>
                    </div>`;
                }
            });
            html += '</div>';
            body.innerHTML = html;
        })
        .catch(() => {
            body.innerHTML = '<div style="text-align:center;padding:20px;color:#dc3545;font-size:0.72rem;">Erreur de chargement.</div>';
        });
}

// ── Lightbox média ─────────────────────────────────────────────────
function openMediaLightbox(index, photos) {
    let current = index;

    const overlay = document.createElement('div');
    overlay.id = 'mediaLightbox';
    overlay.style.cssText = 'position:fixed;inset:0;z-index:99999;background:rgba(0,0,0,0.95);display:flex;align-items:center;justify-content:center;flex-direction:column;';
    overlay.onclick = (e) => { if (e.target === overlay) closeLightbox(); };

    function renderMedia(idx) {
        const p   = photos[idx];
        const ext = (p.file_path||'').split('.').pop().toLowerCase();
        const isV = ['mp4','mov','avi','webm'].includes(ext);
        overlay.innerHTML = `
            <div style="position:absolute;top:12px;right:16px;z-index:2;">
                <button onclick="closeLightbox()" style="background:rgba(255,255,255,0.1);border:1px solid #555;color:#fff;border-radius:50%;width:36px;height:36px;font-size:1rem;cursor:pointer;">✕</button>
            </div>
            <div style="position:absolute;top:12px;left:16px;font-size:0.65rem;color:#888;">Gage #${p.bet_id} · ${idx+1}/${photos.length}</div>
            <div style="max-width:90vw;max-height:80vh;position:relative;">
                ${isV
                    ? `<video src="${p.file_path}" controls autoplay style="max-width:90vw;max-height:80vh;border-radius:8px;"></video>`
                    : `<img src="${p.file_path}" style="max-width:90vw;max-height:80vh;border-radius:8px;object-fit:contain;" />`
                }
            </div>
            <div style="display:flex;gap:20px;margin-top:16px;">
                ${idx > 0 ? `<button onclick="renderMedia(${idx-1})" style="background:rgba(255,255,255,0.1);border:1px solid #555;color:#fff;padding:8px 20px;border-radius:6px;cursor:pointer;font-size:0.8rem;">← Précédent</button>` : '<div style="width:100px"></div>'}
                <a href="${p.file_path}" download style="background:rgba(13,202,240,0.15);border:1px solid #0dcaf0;color:#0dcaf0;padding:8px 16px;border-radius:6px;font-size:0.8rem;text-decoration:none;">⬇ Télécharger</a>
                ${idx < photos.length-1 ? `<button onclick="renderMedia(${idx+1})" style="background:rgba(255,255,255,0.1);border:1px solid #555;color:#fff;padding:8px 20px;border-radius:6px;cursor:pointer;font-size:0.8rem;">Suivant →</button>` : '<div style="width:100px"></div>'}
            </div>`;
        // Rendre renderMedia accessible depuis les boutons inline
        overlay.querySelectorAll('[onclick^="renderMedia"]').forEach(btn => {
            const n = parseInt(btn.getAttribute('onclick').match(/\d+/)[0]);
            btn.onclick = () => renderMedia(n);
        });
        current = idx;
    }

    document.body.appendChild(overlay);
    renderMedia(index);

    // Navigation clavier
    document.addEventListener('keydown', lightboxKeyNav);
    function lightboxKeyNav(e) {
        if (e.key === 'Escape') closeLightbox();
        if (e.key === 'ArrowRight' && current < photos.length-1) renderMedia(current+1);
        if (e.key === 'ArrowLeft'  && current > 0)               renderMedia(current-1);
    }
    overlay._keyNav = lightboxKeyNav;
}

function closeLightbox() {
    const lb = document.getElementById('mediaLightbox');
    if (lb) {
        if (lb._keyNav) document.removeEventListener('keydown', lb._keyNav);
        lb.remove();
    }
}


// ---- Toggle chat section ----
function toggleChatSection() {
    const card = document.getElementById('chatCard');
    const btn  = document.getElementById('toggle-chat');
    const box  = document.getElementById('chat-box');
    const footer = card ? card.querySelector('.card-footer') : null;
    const input  = card ? card.querySelector('.card-footer,.input-group,.form-control') : null;
    const hidden = card ? card.style.height === '36px' : false;
    if (hidden) {
        card.style.flex = '1'; card.style.minHeight = '300px';
        if (btn) btn.innerHTML = '&#9660;';
        localStorage.removeItem('chatHidden');
    } else {
        card.style.height = '36px';
        card.style.overflow = 'hidden';
        if (btn) btn.innerHTML = '&#9650;';
        localStorage.setItem('chatHidden', '1');
    }
}
document.addEventListener('DOMContentLoaded', () => {
    if (localStorage.getItem('chatHidden') === '1') {
        const card = document.getElementById('chatCard');
        const btn  = document.getElementById('toggle-chat');
        if (card) { card.style.height = '36px'; card.style.overflow = 'hidden'; }
        if (btn) btn.innerHTML = '&#9650;';
    }
});

// ---- Toggle sections (Premium+) ----
const hiddenSections = JSON.parse(localStorage.getItem('hiddenSections') || '{}');
function toggleSection(id) {
    const el  = document.getElementById('section-' + id);
    const btn = document.getElementById('toggle-' + id);
    if (!el) return;
    const hidden = el.style.display === 'none';
    el.style.display = hidden ? '' : 'none';
    if (btn) btn.innerHTML = hidden ? '&#9660;' : '&#9650;';
    hiddenSections[id] = !hidden;
    localStorage.setItem('hiddenSections', JSON.stringify(hiddenSections));
}
// Restaurer les préférences au chargement
document.addEventListener('DOMContentLoaded', () => {
    Object.entries(hiddenSections).forEach(([id, hidden]) => {
        if (hidden) {
            const el  = document.getElementById('section-' + id);
            const btn = document.getElementById('toggle-' + id);
            if (el)  el.style.display = 'none';
            if (btn) btn.innerHTML = '&#9650;';
        }
    });
});

// ---- Notation utilisateur ----
let currentRatedId = 0;
let currentRating  = 3;
function openRating(id, name) {
    currentRatedId = id;
    currentRating  = 3;
    document.getElementById('ratingTitle').innerText = 'Evaluer ' + name;
    updateStars(3);
    new bootstrap.Modal(document.getElementById('ratingModal')).show();
}
function setRating(val) {
    currentRating = val;
    updateStars(val);
}
function updateStars(val) {
    document.getElementById('ratingValue').innerText = val + '/5';
    const stars = document.querySelectorAll('#starSelector span');
    stars.forEach((s, i) => { s.style.opacity = i < val ? '1' : '0.3'; });
}
function submitRating() {
    const comment = document.getElementById('ratingComment').value;
    const fd = new FormData();
    fd.append('rated_id', currentRatedId);
    fd.append('stars', currentRating);
    fd.append('comment', comment);
    fetch('rate_user.php', { method:'POST', body:fd })
        .then(r => r.json())
        .then(d => {
            bootstrap.Modal.getInstance(document.getElementById('ratingModal')).hide();
            if (d.success) {
                const toast = document.createElement('div');
                toast.style.cssText = 'position:fixed;bottom:20px;right:20px;background:#ffc107;color:#000;padding:8px 16px;border-radius:6px;font-size:0.75rem;z-index:9999;font-weight:bold;';
                toast.innerText = 'Note envoyee : ' + currentRating + '/5 (moy: ' + d.avg + ')';
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 3000);
            }
        });
}

// ---- Vue événements : liste / calendrier ----
function setEvView(mode) {
    document.getElementById('evViewList').style.display = mode === 'list' ? '' : 'none';
    document.getElementById('evViewCal').style.display  = mode === 'cal'  ? '' : 'none';
    document.getElementById('evBtnList').className = 'btn btn-xs py-0 ' + (mode==='list'?'btn-warning':'btn-outline-warning');
    document.getElementById('evBtnCal').className  = 'btn btn-xs py-0 ' + (mode==='cal' ?'btn-warning':'btn-outline-warning');
    document.getElementById('evBtnList').style.fontSize = '0.55rem';
    document.getElementById('evBtnCal').style.fontSize  = '0.55rem';
}
function toggleCalDay(id) {
    const el = document.getElementById(id);
    if (!el) return;
    // Fermer les autres
    document.querySelectorAll('[id^="day_"]').forEach(d => { if(d.id !== id) d.style.display = 'none'; });
    el.style.display = el.style.display === 'none' ? '' : 'none';
}

// ---- Recherche et filtre gages ----
// ── Pastille retour en haut ────────────────────────────────────
(function() {
    const btn = document.getElementById('scrollTopBtn');
    if (!btn) return;
    const betForm = document.querySelector('.gage-form-card') || document.querySelector('#betFormCard');
    function checkScroll() {
        if (window.innerWidth > 767) { btn.style.display = 'none'; return; }
        // Afficher si le formulaire gage n'est plus visible
        const form = document.querySelector('[name="action"][value="create_bet"]');
        if (!form) { btn.style.display = 'flex'; return; }
        const rect = form.closest('.card') ? form.closest('.card').getBoundingClientRect() : null;
        btn.style.display = (rect && rect.bottom > 0) ? 'none' : 'flex';
    }
    window.addEventListener('scroll', checkScroll, {passive:true});
    window.addEventListener('resize', checkScroll, {passive:true});
    checkScroll();
})();

// ── Modale détail gage ────────────────────────────────────────────
let _allCards = [];
let _curBetIdx = -1;
let _touchStartY = 0;

function openBetModal(cardEl) {
    const raw = cardEl.dataset.betjson;
    if (!raw) return;
    let d;
    try { d = JSON.parse(raw); } catch(e) { return; }

    // Index pour navigation
    _allCards = Array.from(document.querySelectorAll('.gage-card[data-betjson]'));
    _curBetIdx = _allCards.indexOf(cardEl);

    _fillBetModal(d);
    document.getElementById('betDetailOverlay').style.display = 'block';
    document.body.style.overflow = 'hidden';
}

function _fillBetModal(d) {
    const statusColors = {pending:'#ffc107',accepted:'#0dcaf0',completed:'#28a745',won:'#28a745',lost:'#dc3545',cancelled:'#6c757d'};
    const sourceColors = {cercle:'#0dcaf0',moi:'#a78bfa',public:'#6c757d'};
    const sourceLabels = {cercle:'CERCLE',moi:'MON GAGE',public:'PUBLIC'};
    const sc = sourceColors[d.source] || '#6c757d';
    const sl = sourceLabels[d.source] || d.source.toUpperCase();

    document.getElementById('bdBadge').textContent   = sl;
    document.getElementById('bdBadge').style.borderColor = sc;
    document.getElementById('bdBadge').style.color   = sc;
    document.getElementById('bdId').textContent      = '#' + d.id;
    document.getElementById('bdDesc').textContent    = d.description;
    document.getElementById('bdLanceur').textContent = d.username;
    document.getElementById('bdParieur2').textContent= d.parieur2 || '—';
    document.getElementById('bdAmount').textContent  = d.amount + ' pts';

    const stEl = document.getElementById('bdStatus');
    stEl.textContent = (d.status||'').toUpperCase();
    stEl.style.color = statusColors[d.status] || '#aaa';

    // Jetons
    if (d.wallet_stake > 0) {
        document.getElementById('bdJetonsWrap').style.display = '';
        document.getElementById('bdJetons').textContent = '◆ ' + d.wallet_stake;
    } else {
        document.getElementById('bdJetonsWrap').style.display = 'none';
    }
    // Échéance
    if (d.echeance && d.echeance !== '0000-00-00 00:00:00' && d.echeance !== '') {
        document.getElementById('bdEcheanceWrap').style.display = '';
        document.getElementById('bdEcheance').textContent = new Date(d.echeance).toLocaleDateString('fr-CA');
    } else {
        document.getElementById('bdEcheanceWrap').style.display = 'none';
    }
    // Cercle
    if (d.circle) {
        document.getElementById('bdCercleWrap').style.display = '';
        document.getElementById('bdCercle').textContent = d.circle;
    } else {
        document.getElementById('bdCercleWrap').style.display = 'none';
    }
    // Votes
    const totalV = (d.vote_oui||0) + (d.vote_non||0);
    if (totalV > 0) {
        document.getElementById('bdVotesWrap').style.display = '';
        const pOui = Math.round((d.vote_oui / totalV) * 100);
        document.getElementById('bdOui').textContent = pOui + '% OUI (' + d.vote_oui + ')';
        document.getElementById('bdNon').textContent = (100-pOui) + '% NON (' + d.vote_non + ')';
        document.getElementById('bdBar').style.width = pOui + '%';
    } else {
        document.getElementById('bdVotesWrap').style.display = 'none';
    }
    // Actions
    const actions = document.getElementById('bdActions');
    actions.innerHTML = '';
    const addBtn = (label, href, color) => {
        const a = document.createElement('a');
        a.href = href; a.textContent = label;
        a.style.cssText = `background:rgba(0,0,0,0.3);border:1px solid ${color};color:${color};padding:7px 14px;border-radius:6px;font-size:0.72rem;font-weight:600;text-decoration:none;`;
        actions.appendChild(a);
    };
    addBtn('📸 Médias', 'javascript:void(0)', '#0dcaf0');
    actions.lastChild.onclick = () => { closeBetModal(); showGallery(d.id, d.description.substring(0,35)); };
    addBtn('📷 Ajouter preuve', 'upload_photo.php?bet_id='+d.id, '#888');
    if (d.honored) {
        const sp = document.createElement('span');
        sp.style.cssText = 'background:rgba(40,167,69,0.15);border:1px solid #28a745;color:#28a745;padding:7px 14px;border-radius:6px;font-size:0.72rem;font-weight:600;';
        sp.textContent = '✓ Honoré';
        actions.appendChild(sp);
    }

    // Navigation prev/next
    document.getElementById('bdPrev').style.opacity = _curBetIdx > 0 ? '1' : '0.3';
    document.getElementById('bdNext').style.opacity = _curBetIdx < _allCards.length-1 ? '1' : '0.3';
}

function navBet(dir) {
    const newIdx = _curBetIdx + dir;
    if (newIdx < 0 || newIdx >= _allCards.length) return;
    _curBetIdx = newIdx;
    const raw = _allCards[_curBetIdx].dataset.betjson;
    try { _fillBetModal(JSON.parse(raw)); } catch(e) {}
    // Scroll to top of modal card
    document.getElementById('betDetailCard').scrollTop = 0;
}

function closeBetModal() {
    document.getElementById('betDetailOverlay').style.display = 'none';
    document.body.style.overflow = '';
}

// Swipe touch mobile (haut = suivant, bas = précédent)
document.addEventListener('touchstart', (e) => {
    if (document.getElementById('betDetailOverlay').style.display === 'block') {
        _touchStartY = e.touches[0].clientY;
    }
}, {passive: true});

document.addEventListener('touchend', (e) => {
    if (document.getElementById('betDetailOverlay').style.display !== 'block') return;
    const dy = _touchStartY - e.changedTouches[0].clientY;
    if (Math.abs(dy) > 50) navBet(dy > 0 ? 1 : -1);
}, {passive: true});

// Flèches clavier
document.addEventListener('keydown', (e) => {
    if (document.getElementById('betDetailOverlay').style.display !== 'block') return;
    if (e.key === 'ArrowDown' || e.key === 'ArrowRight') navBet(1);
    if (e.key === 'ArrowUp'   || e.key === 'ArrowLeft')  navBet(-1);
    if (e.key === 'Escape') closeBetModal();
});

// ── Scroll infini gages ───────────────────────────────────────────
let betPage = 1;
let betLoading = false;
let betAllLoaded = false;

// ── GAGES PUBLICS — Mélanger + Panel complet ─────────────────────
function shuffleGlobalBets() {
    const list = document.getElementById('globalBetsList');
    if (!list) return;
    const cards = Array.from(list.querySelectorAll('.global-bet-card'));
    for (let i = cards.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        list.appendChild(cards[j]);
        cards.splice(j, 1);
    }
    // Animation flash
    list.style.opacity = '0.4';
    list.style.transition = 'opacity 0.2s';
    setTimeout(() => { list.style.opacity = '1'; }, 200);
}

let _globalBetsAll = [];
let _globalBetsMode = 'recent';

function openGlobalBetsPanel() {
    document.getElementById('globalBetsPanelOverlay').style.display = 'flex';
    document.getElementById('globalBetsPanelOverlay').style.alignItems = 'flex-start';
    loadGlobalBets('recent');
}
function closeGlobalBetsPanel() {
    document.getElementById('globalBetsPanelOverlay').style.display = 'none';
}

function loadGlobalBets(mode) {
    _globalBetsMode = mode || 'recent';
    const body = document.getElementById('globalBetsPanelBody');
    body.innerHTML = '<div class="text-muted text-center py-4" style="font-size:0.7rem;">⏳ Chargement...</div>';

    fetch('fetch_more_bets.php?global=1&limit=100')
        .then(r => r.json())
        .then(data => {
            _globalBetsAll = data.bets || [];
            // Peupler les catégories
            const cats = [...new Set(_globalBetsAll.map(b => b.bet_category).filter(Boolean))];
            const sel = document.getElementById('globalCatFilter');
            sel.innerHTML = '<option value="">Toutes catégories</option>';
            cats.forEach(c => { const o = document.createElement('option'); o.value = c; o.textContent = c; sel.appendChild(o); });
            renderGlobalBets();
        })
        .catch(() => { body.innerHTML = '<div class="text-danger text-center py-4 small">Erreur de chargement.</div>'; });
}

function filterGlobalBets() { renderGlobalBets(); }

function renderGlobalBets() {
    const q   = (document.getElementById('globalSearchInput')?.value || '').toLowerCase().trim();
    const cat = document.getElementById('globalCatFilter')?.value || '';
    let bets = [..._globalBetsAll];

    // Filtres
    if (q)   bets = bets.filter(b => b.description.toLowerCase().includes(q) || (b.username||'').toLowerCase().includes(q));
    if (cat) bets = bets.filter(b => b.bet_category === cat);

    // Tri
    if (_globalBetsMode === 'random') {
        for (let i = bets.length - 1; i > 0; i--) { const j = Math.floor(Math.random()*(i+1)); [bets[i],bets[j]]=[bets[j],bets[i]]; }
    } else {
        bets.sort((a, b) => b.id - a.id);
    }

    const body = document.getElementById('globalBetsPanelBody');
    document.getElementById('globalPanelCount').textContent = bets.length + ' gage(s)';

    if (!bets.length) {
        body.innerHTML = '<div class="text-muted text-center py-5 small">Aucun gage public disponible.</div>';
        return;
    }

    body.innerHTML = bets.map(b => `
        <div style="background:#0a0a1a;border:1px solid rgba(255,140,0,0.3);border-left:3px solid #ff8c00;border-radius:6px;padding:10px 12px;margin-bottom:8px;">
            <div class="d-flex justify-content-between align-items-start gap-2">
                <div style="min-width:0;">
                    <span style="color:#ffc107;font-weight:700;font-size:0.65rem;">${b.username}</span>
                    <span style="color:#888;font-size:0.58rem;margin:0 4px;">·</span>
                    <span style="color:#28a745;font-size:0.6rem;">${b.amount} pts</span>
                    ${b.bet_category ? `<span style="font-size:0.5rem;padding:0 5px;border-radius:8px;background:rgba(255,193,7,0.1);border:1px solid rgba(255,193,7,0.25);color:#ffc107;margin-left:4px;">${b.bet_category}${b.bet_subcategory?' · '+b.bet_subcategory:''}</span>` : ''}
                    <div style="color:#fff;font-size:0.73rem;margin-top:4px;line-height:1.35;">${b.description}</div>
                </div>
                <a href="bet_accept.php?id=${b.id}&action=accept"
                   style="background:#ffc107;color:#000;border:none;border-radius:5px;padding:4px 10px;font-size:0.6rem;font-weight:700;white-space:nowrap;text-decoration:none;flex-shrink:0;">
                    TENU !
                </a>
            </div>
        </div>
    `).join('');
}

// Fermer panel avec Escape
document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closeGlobalBetsPanel();
});

function loadMoreBets() {
    if (betLoading || betAllLoaded) return;
    betLoading = true;
    const whoFilter = document.getElementById('filterWho')?.value || '';
    const statusFilter = document.getElementById('filterStatus')?.value || '';
    fetch('fetch_more_bets.php?page=' + (++betPage) + '&who=' + encodeURIComponent(whoFilter) + '&status=' + encodeURIComponent(statusFilter))
        .then(r => r.json())
        .then(data => {
            betLoading = false;
            if (!data.html || data.html.trim() === '') { betAllLoaded = true; return; }
            const zone = document.getElementById('bets-zone');
            if (zone) zone.insertAdjacentHTML('beforeend', data.html);
            if (data.done) betAllLoaded = true;
        }).catch(() => { betLoading = false; });
}

// Observer pour déclencher le chargement
const betObserver = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) loadMoreBets();
}, { threshold: 0.1 });
document.addEventListener('DOMContentLoaded', () => {
    const sentinel = document.getElementById('bets-sentinel');
    if (sentinel) betObserver.observe(sentinel);
});

// ── Collapse colonnes latérales ────────────────────────────────
const _colState = { col1: true, col3: true, col4: true };

function _positionCollapseButtons() {
    // Ne rien faire en mode pastilles
    if (<?= $useOverlay ? 'true' : 'false' ?>) return;
    // Positionner les boutons fixed selon la position réelle des colonnes
    const col1 = document.getElementById('col1Wrap');
    const col3 = document.getElementById('col3Chat');
    const col4 = document.querySelector('.friends-col');
    const btn1 = document.getElementById('col1CollapseBtn');
    const btn3 = document.getElementById('col3CollapseBtn');
    const btn4 = document.getElementById('col4CollapseBtn');

    if (col1 && btn1) {
        const r = col1.getBoundingClientRect();
        btn1.style.left = (r.right - 9) + 'px';
    }
    if (col3 && btn3) {
        const r = col3.getBoundingClientRect();
        btn3.style.left = (r.left - 9) + 'px';
    }
    if (col4 && btn4) {
        const r = col4.getBoundingClientRect();
        btn4.style.left = (r.left - 9) + 'px';
    }
}

document.addEventListener('DOMContentLoaded', _positionCollapseButtons);
window.addEventListener('resize', _positionCollapseButtons);
const _colWidths = { col1: '280px', col3: '420px', col4: '180px' };

function toggleColCollapse(col) {
    const isOpen = _colState[col];
    _colState[col] = !isOpen;

    const COLLAPSED_W = '18px';

    if (col === 'col1') {
        const wrap = document.getElementById('col1Wrap');
        const btn  = document.getElementById('col1CollapseBtn');
        if (isOpen) {
            wrap.style.flex     = '0 0 ' + COLLAPSED_W;
            wrap.style.minWidth = COLLAPSED_W;
            wrap.style.width    = COLLAPSED_W;
            wrap.classList.add('col-is-collapsed');
            btn.textContent     = '▶';
            btn.title           = 'Agrandir';
        } else {
            wrap.style.flex     = '0 0 ' + _colWidths.col1;
            wrap.style.minWidth = _colWidths.col1;
            wrap.style.width    = _colWidths.col1;
            wrap.classList.remove('col-is-collapsed');
            btn.textContent     = '◀';
            btn.title           = 'Réduire';
        }
    } else if (col === 'col3') {
        const wrap = document.getElementById('col3Chat');
        const btn  = document.getElementById('col3CollapseBtn');
        if (isOpen) {
            wrap.style.flex     = '0 0 ' + COLLAPSED_W;
            wrap.style.minWidth = COLLAPSED_W;
            wrap.style.width    = COLLAPSED_W;
            wrap.classList.add('col-is-collapsed');
            btn.textContent     = '◀';
            btn.title           = 'Agrandir';
        } else {
            wrap.style.flex     = '0 0 ' + _colWidths.col3;
            wrap.style.minWidth = _colWidths.col3;
            wrap.style.width    = _colWidths.col3;
            wrap.classList.remove('col-is-collapsed');
            btn.textContent     = '▶';
            btn.title           = 'Réduire';
        }
    } else if (col === 'col4') {
        const wrap = document.querySelector('.friends-col');
        const btn  = document.getElementById('col4CollapseBtn');
        if (isOpen) {
            wrap.style.width    = COLLAPSED_W;
            wrap.style.minWidth = COLLAPSED_W;
            wrap.classList.add('col-is-collapsed');
            btn.textContent     = '◀';
            btn.title           = 'Agrandir';
        } else {
            wrap.style.width    = _colWidths.col4;
            wrap.style.minWidth = _colWidths.col4;
            wrap.classList.remove('col-is-collapsed');
            btn.textContent     = '▶';
            btn.title           = 'Réduire';
        }
    }
    // Repositionner tous les boutons après animation
    setTimeout(_positionCollapseButtons, 280);
}

function switchCircle(circleId) {
    if (!circleId) return;
    // Sync le dropdown du chat si présent
    const chatSel = document.getElementById('circleSelector');
    if (chatSel) {
        chatSel.value = circleId;
        changeCircle(circleId);
    }
    // Sync le dropdown du filtre
    const filtSel = document.getElementById('circleSwitch');
    if (filtSel) filtSel.value = circleId;
    // Mettre à jour la session via set_circle
    fetch('set_circle.php?id=' + circleId).then(() => {
        // Recharger les gages pour ce cercle
        const url = new URL(window.location.href);
        url.searchParams.set('fc', circleId);
        window.location.href = url.toString();
    });
}

function filterBets(q) {
    const status  = document.getElementById('filterStatus')?.value || '';
    const who     = document.getElementById('filterWho')?.value || '';
    const cards   = document.querySelectorAll('.gage-card');
    const search  = q.toLowerCase().trim();
    const myId    = <?php echo $isLoggedIn ? (int)$_SESSION['user_id'] : 0; ?>;
    const circleId= <?php echo (int)($_SESSION['circle_id'] ?? 0); ?>;
    let visible   = 0;

    cards.forEach(card => {
        const text    = card.innerText.toLowerCase();
        const badge   = card.querySelector('.badge')?.innerText?.toUpperCase() || '';
        const owner   = parseInt(card.dataset.owner || 0);
        const p2      = parseInt(card.dataset.p2 || 0);
        const circle  = parseInt(card.dataset.circle || 0);
        const isGlobal= parseInt(card.dataset.global || 0);

        const matchQ  = !search || text.includes(search);
        // Vérifier statut + badges spéciaux
        const allText = card.innerText.toUpperCase();
        let matchS = true;
        if (status) {
            if (status === 'HONORED')     matchS = allText.includes('HONORÉ') || allText.includes('HONORE');
            else if (status === 'NOT_HONORED') matchS = allText.includes('NON HONOR');
            else if (status === 'ACCEPTED')   matchS = allText.includes('ACCEPTED') || allText.includes('ACCEPTÉ');
            else matchS = allText.includes(status);
        }
        let matchW    = true;
        if (who === 'mine')   matchW = (owner === myId || p2 === myId);
        if (who === 'circle') matchW = (circle === circleId && circleId > 0);
        if (who === 'global') matchW = isGlobal === 1;

        if (matchQ && matchS && matchW) { card.style.display = ''; visible++; }
        else card.style.display = 'none';
    });

    // Message si aucun résultat
    let noResult = document.getElementById('noResultBets');
    if (visible === 0) {
        if (!noResult) {
            noResult = document.createElement('div');
            noResult.id = 'noResultBets';
            noResult.className = 'text-muted text-center py-3 small';
            noResult.innerText = 'Aucun gage trouvé.';
            document.getElementById('lista-gages').appendChild(noResult);
        }
        noResult.style.display = '';
    } else if (noResult) {
        noResult.style.display = 'none';
    }
}

// ---- Gage Rapide depuis un événement ----
let gageEventTitle = '';
function gageRapide(eventTitle) {
    gageEventTitle = eventTitle;
    document.getElementById('gageRapidePrefix').innerText = 'Je te gage que ' + eventTitle;
    document.getElementById('gageRapideDesc').value = '';
    updateGageFinal();
    new bootstrap.Modal(document.getElementById('gageRapideModal')).show();
    setTimeout(() => document.getElementById('gageRapideDesc').focus(), 400);
}
function updateGageFinal() {
    const userPart = document.getElementById('gageRapideDesc').value.trim();
    const final = 'Je te gage que ' + gageEventTitle + ' ' + userPart;
    const hiddenField = document.getElementById('gageRapideFinal');
    if (hiddenField) hiddenField.value = final;
}

// ---- Supprimer message (admin/oracle) ----
function deleteMsg(msgId) {
    if (!confirm('Supprimer ce message ?')) return;
    const btn = document.getElementById('del-' + msgId);
    if (btn) btn.style.opacity = '0.3';
    fetch('delete_msg.php?id=' + msgId)
        .then(() => {
            const msgEl = document.getElementById('msg-' + msgId);
            if (msgEl) msgEl.style.transition = '0.3s';
            if (msgEl) msgEl.style.opacity = '0';
            setTimeout(() => { if (msgEl) msgEl.remove(); }, 300);
        })
        .catch(() => { if(btn) btn.style.opacity='1'; });
}

// ---- Signalement message (délégation d'événement) ----
document.addEventListener('click', function(e) {
    const btn = e.target.closest('[data-report]');
    if (!btn) return;
    const msgId = btn.dataset.report;
    if (btn.dataset.reported === '1') return;
    btn.dataset.reported = '1';
    btn.innerHTML = '&#10003;';
    btn.style.color = '#28a745';
    btn.style.cursor = 'default';
    const p = new URLSearchParams();
    p.append('report_msg', '1');
    p.append('message_id', msgId);
    fetch('circle_wall.php', { method:'POST', body:p })
        .then(r => r.json())
        .then(d => {
            if (d.error) {
                btn.dataset.reported = '0';
                btn.innerText = '🚩';
                btn.style.color = '#333';
                btn.style.cursor = 'pointer';
                return;
            }
            btn.title = 'Signalé (' + d.count + ')';
            if (d.flagged) setTimeout(loadMessages, 500);
        })
        .catch(() => {
            btn.dataset.reported = '0';
            btn.innerText = '🚩';
            btn.style.color = '#333';
        });
});

function reportMsg(msgId) {} // Garde pour compatibilité

// v1.7 — Classements avec filtre de période
let _rankPeriod = 'all';

function loadRankings(type = 'points') {
    const table = document.getElementById('rankingTable');
    if (!table) return;
    fetch('fetch_rankings.php?type=' + type + '&period=' + _rankPeriod)
        .then(r => r.text())
        .then(data => { table.innerHTML = data; });
}

function setRankPeriod(period) {
    _rankPeriod = period;
    document.querySelectorAll('.rank-period-btn').forEach(b => {
        b.style.opacity   = b.dataset.period === period ? '1' : '0.45';
        b.style.fontWeight = b.dataset.period === period ? '700' : '400';
    });
    loadRankings(document.getElementById('rankType')?.value || 'points');
}

// 3. Fiche Profil & Voir plus
function viewProfile(userId) {
    const content = document.getElementById('userProfileContent');
    content.innerHTML = '<div class="p-5 text-center"><div class="spinner-border text-primary"></div></div>';
    new bootstrap.Modal(document.getElementById('userProfileModal')).show();
    fetch('fetch_user_profile.php?id=' + userId).then(r => r.text()).then(data => { content.innerHTML = data; });
}

let offset = 10;
function loadMoreBets() {
    const btn = document.getElementById('load-more-btn');
    btn.innerHTML = "...";
    fetch('fetch_more_bets.php?offset=' + offset).then(r => r.text()).then(data => {
        if (data.trim() === "") { btn.innerHTML = "FIN"; btn.disabled = true; }
        else {
            document.getElementById('lista-gages').insertAdjacentHTML('beforeend', data);
            offset += 10;
            btn.innerHTML = "VOIR LES 10 SUIVANTS";
            const rb = document.getElementById('reset-btn');
            if (rb) rb.style.display = '';
        }
    });
}

function resetBets() {
    offset = 10;
    const lg = document.getElementById('lista-gages');
    const rb = document.getElementById('reset-btn');
    const btn = document.getElementById('load-more-btn');
    if (lg) lg.innerHTML = '<div class="text-muted small text-center py-2">Chargement...</div>';
    if (rb) rb.style.display = 'none';
    if (btn) { btn.innerHTML = 'VOIR LES 10 SUIVANTS'; btn.disabled = false; }
    fetch('fetch_more_bets.php?offset=0').then(r => r.text()).then(data => {
        if (lg) lg.innerHTML = data;
        window.scrollTo({top: 0, behavior: 'smooth'});
    });
}

// 4. Initialisation
document.addEventListener('click', e => {
    const box = document.getElementById('parieurSuggestions');
    if (box && !box.contains(e.target) && e.target.id !== 'parieur2Search') {
        box.style.display = 'none';
    }
});

// Initialisation
document.addEventListener('DOMContentLoaded', () => {
    // Calendrier Flatpickr pour le formulaire principal
    const echeanceEl = document.getElementById('echeancePicker');
    if (echeanceEl && typeof flatpickr !== 'undefined') {
        flatpickr(echeanceEl, {
            locale: 'fr',
            dateFormat: 'Y-m-d',
            altInput: true,
            altFormat: 'j F Y',
            minDate: 'today',
            disableMobile: true,
        });
    }
    loadRankings(); 
    loadMessages();
    loadFriends();
    document.getElementById('rankType')?.addEventListener('change', (e) => loadRankings(e.target.value));
});
// ---- Lightbox photos ----
function openLightbox(src, caption) {
    const overlay = document.getElementById('lightboxOverlay');
    document.getElementById('lightboxImg').src = src;
    document.getElementById('lightboxCaption').innerText = caption || '';
    overlay.style.display = 'flex';
    document.body.style.overflow = 'hidden';
}
function closeLightbox() {
    document.getElementById('lightboxOverlay').style.display = 'none';
    document.body.style.overflow = '';
}
// ── Validation formulaire gage ──────────────────────────────
function validateAndSubmitBet() {
    const form    = document.getElementById('betForm');
    const desc    = document.getElementById('betDesc');
    const p2Id    = document.getElementById('parieur2Id');
    const p2Name  = document.getElementById('parieur2Search');
    const ech     = document.getElementById('echeancePicker');
    const isGlob  = document.getElementById('isGlobal');
    const isGlobal= isGlob && isGlob.checked;

    // Desc
    if (!desc || !desc.value.trim()) {
        desc.classList.add('border-danger');
        desc.focus();
        showBetError('Décris le gage avant de lancer.');
        return;
    }
    desc.classList.remove('border-danger');

    // Gageur 2 obligatoire sauf gage global
    if (!isGlobal) {
        if (!p2Id || !p2Id.value) {
            p2Name.classList.add('border-danger');
            p2Name.focus();
            showBetError('Le Gageur 2 est obligatoire. Recherche un membre ou coche "Gage ouvert".');
            return;
        }
        p2Name.classList.remove('border-danger');
    }

    // Echéance obligatoire sauf gage global
    if (!isGlobal) {
        if (!ech || !ech.value.trim()) {
            ech.classList.add('border-danger');
            showBetError('La date d\'ech\'eance est obligatoire.');
            ech._flatpickr && ech._flatpickr.open();
            return;
        }
        ech.classList.remove('border-danger');
    }

    // Tout OK → soumettre
    hideBetError();
    form.submit();
}

function showBetError(msg) {
    let el = document.getElementById('betFormError');
    if (!el) {
        el = document.createElement('div');
        el.id = 'betFormError';
        el.style.cssText = 'font-size:0.68rem;color:#dc3545;background:rgba(220,53,69,0.12);border:1px solid #dc3545;border-radius:5px;padding:5px 9px;margin-top:4px;';
        const form = document.getElementById('betForm');
        const btn  = form ? form.querySelector('[onclick="validateAndSubmitBet()"]') : null;
        if (btn) btn.parentNode.insertBefore(el, btn.nextSibling);
    }
    el.textContent = '⚠ ' + msg;
    el.style.display = 'block';
}

function hideBetError() {
    const el = document.getElementById('betFormError');
    if (el) el.style.display = 'none';
}

// Bloquer Enter dans le formulaire gage (sauf textarea)
document.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('betForm');
    if (form) {
        form.addEventListener('keydown', e => {
            if (e.key === 'Enter' && e.target.tagName !== 'TEXTAREA') {
                e.preventDefault();
                return false;
            }
        });
    }
});

// Toggle obligatoire/optionnel selon gage global
document.addEventListener('DOMContentLoaded', () => {
    const chk = document.getElementById('isGlobal');
    if (!chk) return;
    chk.addEventListener('change', () => {
        const required = document.getElementById('p2RequiredBadge');
        const optional = document.getElementById('p2OptionalBadge');
        const p2Field  = document.getElementById('parieur2Search');
        const echField = document.getElementById('echeancePicker');
        if (chk.checked) {
            if (required) required.style.display = 'none';
            if (optional) optional.style.display = '';
            if (p2Field)  { p2Field.classList.remove('border-danger'); }
            if (echField) { echField.classList.remove('border-danger'); }
        } else {
            if (required) required.style.display = '';
            if (optional) optional.style.display = 'none';
        }
    });
});

// ── Modal Mur du cercle ──────────────────────────────────────
let _wallCircleId = 0;
let _wallInterval = null;

// Ouvrir le chat du cercle via le panel pastille (identique à la pastille CHAT/MUR)
function openChatForCircle(circleId) {
    // 1. Fermer la pastille cercles
    closeDashPanel();
    // 2. Changer le cercle actif
    fetch('set_circle.php?id=' + circleId).then(() => {
        // 3. Sync les dropdowns
        const chatSel = document.getElementById('circleSelector');
        if (chatSel) chatSel.value = circleId;
        const filtSel = document.getElementById('circleSwitch');
        if (filtSel) filtSel.value = circleId;
        // 4. Ouvrir le panel CHAT
        setTimeout(() => openDashPanel('chat'), 100);
    }).catch(() => {
        openDashPanel('chat');
    });
}

function openWallModal(circleId) {
    _wallCircleId = circleId;
    const overlay = document.getElementById('dashPanelOverlay');
    const title   = document.getElementById('dashPanelTitle');
    const body    = document.getElementById('dashPanelBody');
    if (!overlay) { window.open('circle_wall.php?id=' + circleId, '_blank'); return; }

    title.innerHTML = '<i class="fa-solid fa-comments fa-xs me-1"></i>MUR DU CERCLE';
    body.innerHTML  = '<div class="text-muted text-center py-3 small">Chargement du mur...</div>';
    overlay.style.display = 'flex';
    overlay.style.alignItems = 'flex-start';
    overlay.style.justifyContent = 'center';

    const panel = overlay.querySelector('div');
    if (panel) { panel.style.width = 'min(700px,95vw)'; panel.style.maxHeight = '85vh'; }

    wallLoadContent(circleId);
}

function wallLoadContent(circleId) {
    _wallCircleId = circleId;
    const body = document.getElementById('dashPanelBody');
    if (!body) return;
    body.innerHTML = '<div class="text-muted text-center py-2 small">Chargement...</div>';
    fetch('fetch_circle_wall_modal.php?id=' + circleId)
        .then(r => r.text())
        .then(html => {
            const noScript = html.replace(/<script[\s\S]*?<\/script>/gi, '');
            body.innerHTML = noScript;
            // Scroll en bas
            const msgs = document.getElementById('wall-msgs');
            if (msgs) msgs.scrollTop = msgs.scrollHeight;
            // Démarrer rafraîchissement
            if (_wallInterval) clearInterval(_wallInterval);
            _wallInterval = setInterval(() => wallRefreshMsgs(), 8000);
        })
        .catch(() => { body.innerHTML = '<p class="text-danger small text-center py-3">Erreur.</p>'; });
}

function wallRefreshMsgs() {
    if (!_wallCircleId) return;
    fetch('fetch_circle_wall_modal.php?id=' + _wallCircleId)
        .then(r => r.text())
        .then(html => {
            const tmp = document.createElement('div');
            tmp.innerHTML = html.replace(/<script[\s\S]*?<\/script>/gi, '');
            const newMsgs = tmp.querySelector('#wall-msgs');
            const curMsgs = document.getElementById('wall-msgs');
            if (newMsgs && curMsgs) {
                const atBottom = curMsgs.scrollHeight - curMsgs.scrollTop <= curMsgs.clientHeight + 40;
                curMsgs.innerHTML = newMsgs.innerHTML;
                if (atBottom) curMsgs.scrollTop = curMsgs.scrollHeight;
            }
        });
}

function wallSend() {
    if (!_wallCircleId) return;
    const inp  = document.getElementById('wall-input');
    const msg  = inp ? inp.value.trim() : '';
    const icon = document.getElementById('wall-icon-selected') ? document.getElementById('wall-icon-selected').dataset.emoji || '' : '';
    if (!msg) return;
    const fd = new FormData();
    fd.append('msg', msg);
    if (icon) fd.append('icon', icon);
    fetch('fetch_circle_wall_modal.php?id=' + _wallCircleId, {method:'POST', body:fd})
        .then(() => {
            if (inp) inp.value = '';
            wallRefreshMsgs();
        });
}

function wallSwitchCircle(id) {
    fetch('fetch_user_circles.php?action=switch&id=' + id)
        .then(r => r.text())
        .then(res => {
            if (res.trim() === 'ok') {
                if (_wallInterval) clearInterval(_wallInterval);
                wallLoadContent(id);
            }
        });
}

function wallOpenFullscreen() {
    window.open('circle_wall.php?id=' + _wallCircleId, '_blank');
}

// Nettoyer l'interval quand on ferme le panel
const _origCloseDashPanel = typeof closeDashPanel === 'function' ? closeDashPanel : null;

function closeDashPanel() {
    if (_wallInterval) { clearInterval(_wallInterval); _wallInterval = null; }
    const overlay = document.getElementById('dashPanelOverlay');
    if (overlay) overlay.style.display = 'none';
    const toolbar = document.getElementById('dashPanelToolbar');
    if (toolbar) { toolbar.style.display = 'none'; toolbar.innerHTML = ''; }
    const panel = overlay ? overlay.querySelector('div') : null;
    if (panel) { panel.style.width = ''; panel.style.maxHeight = ''; }
}

// openWallModal: voir définition principale ci-dessus

document.addEventListener('keydown', e => { if (e.key === 'Escape') closeLightbox(); });

// ---- Visionneuse photos par gage ----
function showGallery(betId, title) {
    stopTumbling();
    const zone = document.getElementById('gallery-zone');
    const ttl  = document.getElementById('galleryTitle');
    const btn  = document.getElementById('galleryCloseBtn');
    zone.innerHTML = '<p class="text-muted mb-0 w-100 text-center" style="font-size:0.6rem;">Chargement...</p>';
    ttl.innerText  = '📸 ' + title;
    btn.style.display = '';
    fetch('get_proofs.php?bet_id=' + betId + '&public=1')
        .then(r => r.json())
        .then(photos => {
            if (!photos || photos.length === 0) {
                zone.innerHTML = '<p class="text-muted mb-0 w-100 text-center" style="font-size:0.6rem;">Aucune photo</p>';
                return;
            }
            zone.innerHTML = photos.map((p, idx) => {
                const ext = (p.file_path||'').split('.').pop().toLowerCase();
                const isV = ['mp4','mov','webm'].includes(ext);
                return isV
                    ? `<div style="height:178px;position:relative;cursor:pointer;" onclick="openMediaLightbox(${idx}, photos_${betId})">
                        <video src="${p.file_path}" style="height:178px;border-radius:6px;"></video>
                        <div style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.3);border-radius:6px;"><span style="font-size:2rem;">▶</span></div>
                      </div>`
                    : `<img src="${p.file_path}" class="rounded border border-info flex-shrink-0"
                        style="height:178px;width:auto;max-width:100%;object-fit:contain;cursor:pointer;"
                        onclick="openMediaLightbox(${idx}, photos_${betId})">`;
            }).join('');
            // Stocker pour le lightbox
            window['photos_' + betId] = photos;
        })
        .catch(() => {
            zone.innerHTML = '<p class="text-danger mb-0 text-center" style="font-size:0.6rem;">Erreur</p>';
        });
}
function closeGallery() {
    stopTumbling();
    document.getElementById('gallery-zone').innerHTML = '<p class="text-muted mb-0 w-100 text-center" style="font-size:0.6rem;">Clique sur 📸 d\'un gage</p>';
    document.getElementById('galleryCloseBtn').style.display = 'none';
    document.getElementById('galleryTitle').innerText = '📸 PHOTOS DU GAGE';
}

// ---- Tumbling : défilement de TOUTES les photos ----
let tumblingInterval = null;
let tumblingPhotos   = [];
let tumblingIndex    = 0;

function toggleTumbling() {
    if (tumblingInterval) { stopTumbling(); return; }
    // Charger toutes les photos du cercle
    const zone = document.getElementById('gallery-zone');
    const ttl  = document.getElementById('galleryTitle');
    const btn  = document.getElementById('tumblingBtn');
    zone.innerHTML = '<p class="text-muted mb-0 w-100 text-center" style="font-size:0.6rem;">Chargement...</p>';
    ttl.innerText = '📸 DÉFILEMENT — TOUTES LES PHOTOS';
    btn.innerHTML = '⏹ STOP';
    btn.classList.replace('btn-outline-warning','btn-warning');
    document.getElementById('galleryCloseBtn').style.display = '';

    fetch('get_proofs.php?all=1')
        .then(r => r.json())
        .then(photos => {
            if (!photos || photos.length === 0) {
                zone.innerHTML = '<p class="text-muted mb-0 w-100 text-center" style="font-size:0.6rem;">Aucune photo dans le cercle</p>';
                stopTumbling(); return;
            }
            tumblingPhotos = photos;
            tumblingIndex  = 0;
            showTumblingPhoto();
            tumblingInterval = setInterval(showTumblingPhoto, 2500);
        });
}
function showTumblingPhoto() {
    if (!tumblingPhotos.length) return;
    const p    = tumblingPhotos[tumblingIndex % tumblingPhotos.length];
    const zone = document.getElementById('gallery-zone');
    zone.innerHTML = `<div class="position-relative w-100 h-100 d-flex align-items-center justify-content-center">
        <img src="${p.file_path}"
            class="rounded border border-warning"
            style="height:178px;width:auto;max-width:100%;object-fit:contain;cursor:pointer;"
            onclick="openLightbox('${p.file_path}','Gage #${p.bet_id}')">
        <div class="text-muted text-center w-100" style="font-size:0.55rem;position:absolute;bottom:2px;">Gage #${p.bet_id} · ${tumblingIndex+1}/${tumblingPhotos.length}</div>
    </div>`;
    tumblingIndex++;
}
function stopTumbling() {
    if (tumblingInterval) { clearInterval(tumblingInterval); tumblingInterval = null; }
    tumblingPhotos = []; tumblingIndex = 0;
    const btn = document.getElementById('tumblingBtn');
    if (btn) { btn.innerHTML = '▶ TOUTES'; btn.classList.replace('btn-warning','btn-outline-warning'); }
}

// ---- Auto-complétion Gageur 2 ----
let searchTimeout = null;
function searchParieur(q) {
    clearTimeout(searchTimeout);
    document.getElementById('parieur2Id').value = '';
    document.getElementById('parieurSelected').style.display = 'none';
    if (q.length < 2) { document.getElementById('parieurSuggestions').style.display = 'none'; return; }
    searchTimeout = setTimeout(() => {
        fetch('search_users.php?q=' + encodeURIComponent(q))
            .then(r => r.json())
            .then(data => {
                const box = document.getElementById('parieurSuggestions');
                if (!data.length) { box.style.display = 'none'; return; }
                box.innerHTML = data.map(u =>
                    `<div style="padding:8px 12px;cursor:pointer;font-size:0.78rem;border-bottom:1px solid #1a1a2a;color:#e0e0e0;background:#0d0d1a;"
                          onmouseover="this.style.background='#1a1a3a';this.style.color='#0dcaf0'" 
                          onmouseout="this.style.background='#0d0d1a';this.style.color='#e0e0e0'"
                          onmousedown="event.preventDefault();event.stopPropagation();"
                          onclick="event.preventDefault();event.stopPropagation();selectParieur(${u.id}, '${u.label.replace(/'/g,"\\'")}', '${u.username.replace(/'/g,"\\'")}'); return false;">
                        ${u.label}
                    </div>`
                ).join('');
                box.style.cssText = 'display:block;background:#0d0d1a;border:1px solid #0dcaf0;border-radius:6px;position:absolute;z-index:9999;width:100%;max-height:200px;overflow-y:auto;box-shadow:0 4px 20px rgba(0,0,0,0.6);margin-top:2px;';
            });
    }, 300);
}
function selectParieur(id, label, username) {
    document.getElementById('parieur2Id').value    = id;
    document.getElementById('parieur2Search').value = username;
    document.getElementById('parieurName').innerText = label;
    document.getElementById('parieurSelected').style.display = '';
    document.getElementById('parieurSuggestions').style.display = 'none';

    // Charger les infos de contact du gageur 2
    fetch('search_users.php?check_email=1&get_contact=1&id=' + id)
        .then(r => r.json())
        .then(d => {
            const contactDiv = document.getElementById('parieurContact');
            const emailBox   = document.getElementById('sendEmailCheck');
            let contactHtml  = '';
            if (d.email)  contactHtml += 'Courriel : <span class="text-white">' + d.email + '</span>';
            if (d.phone)  contactHtml += (contactHtml?' &nbsp;|&nbsp; ':'') + 'Tel : <span class="text-white">' + d.phone + '</span>';
            if (!contactHtml) contactHtml = 'Aucune info de contact publique';
            if (contactDiv) contactDiv.innerHTML = contactHtml;
            if (emailBox)   emailBox.style.display = d.has_email ? '' : 'none';
        }).catch(() => {});
}
function clearParieur() {
    document.getElementById('parieur2Id').value = '';
    document.getElementById('parieur2Search').value = '';
    document.getElementById('parieurSelected').style.display = 'none';
    document.getElementById('parieurSuggestions').style.display = 'none';
}
function autoDetectParieur(text) {
    if (document.getElementById('parieur2Id').value) return;
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        const words = text.split(/\s+/).filter(w => w.length >= 3);
        if (!words.length) return;
        const lastWord = words[words.length - 1];
        fetch('search_users.php?q=' + encodeURIComponent(lastWord))
            .then(r => r.json())
            .then(data => {
                if (data.length === 1) {
                    const box = document.getElementById('parieurSuggestions');
                    box.innerHTML = `<div style="padding:8px 10px;background:#1a2a1a;border-bottom:1px solid #333;">
                        <span style="font-size:0.72rem;color:#aaa;">Gageur 2 détecté :</span>
                        <strong style="color:#0f0;font-size:0.75rem;"> ${data[0].username}</strong>
                        <div class="d-flex gap-2 mt-1">
                            <button type="button" onclick="event.preventDefault();event.stopPropagation();selectParieur(${data[0].id},'${data[0].label.replace(/'/g,"\\'")}','${data[0].username.replace(/'/g,"\\'")}'); document.getElementById('parieurSuggestions').style.display='none'; return false;"
                                style="font-size:0.68rem;padding:2px 10px;background:#28a745;border:none;border-radius:4px;color:#fff;cursor:pointer;">
                                ✓ Oui, c'est lui
                            </button>
                            <button type="button" onclick="event.preventDefault();event.stopPropagation();document.getElementById('parieurSuggestions').style.display='none'; return false;"
                                style="font-size:0.68rem;padding:2px 10px;background:#444;border:none;border-radius:4px;color:#fff;cursor:pointer;">
                                ✗ Non
                            </button>
                        </div>
                    </div>`;
                    box.style.display = 'block';
                }
            });
    }, 600);
}

// ---- Report ----
function reportGage(id) {
    document.getElementById('reportTargetId').value = id;
    new bootstrap.Modal(document.getElementById('reportModal')).show();
}

// ---- Vote AJAX ----
function voterAjax(betId, vote, btn) {
    const zone = document.getElementById('vote-zone-' + betId);
    const card = document.getElementById('bet-' + betId);
    if (!zone) return;
    zone.querySelectorAll('button').forEach(b => b.disabled = true);

    fetch('vote_gage.php?id=' + betId + '&v=' + vote + '&ajax=1')
        .then(r => r.json())
        .then(d => {
            // Afficher le résultat brièvement
            zone.innerHTML = '<div style="min-width:120px;">'
                + '<div class="d-flex justify-content-between" style="font-size:0.58rem;">'
                + '<span class="text-success fw-bold">' + d.p_oui + '% OUI</span>'
                + '<span class="text-danger fw-bold">' + d.p_non + '% NON</span></div>'
                + '<div class="progress" style="height:4px;background:#222;">'
                + '<div class="progress-bar bg-success" style="width:' + d.p_oui + '%;"></div></div>'
                + '<div class="text-muted text-center" style="font-size:0.55rem;">' + d.total + ' vote' + (d.total > 1 ? 's' : '') + '</div>'
                + '</div>';

            if (!card) return;

            // Choisir l'effet selon le vote
            const isOui = vote === 'oui';

            // Délai court pour voir le résultat avant l'animation
            setTimeout(() => {
                // Figer la hauteur pour une animation fluide
                card.style.overflow   = 'hidden';
                card.style.height     = card.offsetHeight + 'px';
                card.style.transition = 'none';

                // Petite impulsion de couleur
                card.style.boxShadow = isOui
                    ? '0 0 18px 4px rgba(40,167,69,0.7)'
                    : '0 0 18px 4px rgba(220,53,69,0.7)';

                setTimeout(() => {
                    // Ajouter les keyframes si pas encore là
                    if (!document.getElementById('voteAnimStyle')) {
                        const s = document.createElement('style');
                        s.id = 'voteAnimStyle';
                        s.textContent = `
                            @keyframes voteVanishOui {
                                0%   { transform:scale(1) rotate(0deg);   opacity:1; filter:brightness(1); }
                                15%  { transform:scale(1.04) rotate(-1deg); filter:brightness(1.4) hue-rotate(60deg); }
                                40%  { transform:scale(0.95) rotate(2deg);  opacity:0.8; }
                                60%  { transform:scale(1.1) translateY(-8px) rotate(-2deg); opacity:0.5; filter:blur(1px); }
                                100% { transform:scale(0) translateY(-40px) rotate(8deg); opacity:0; filter:blur(4px); height:0; margin:0; padding:0; }
                            }
                            @keyframes voteVanishNon {
                                0%   { transform:scale(1) rotate(0deg);   opacity:1; }
                                10%  { transform:scale(1.03) rotate(1deg); filter:brightness(1.3) hue-rotate(-30deg); }
                                30%  { transform:scale(0.97) rotate(-2deg); opacity:0.85; }
                                55%  { transform:scale(0.9) translateX(12px) rotate(3deg); opacity:0.5; filter:blur(0.5px); }
                                80%  { transform:scale(0.5) translateX(30px) rotate(-5deg); opacity:0.2; }
                                100% { transform:scale(0) translateX(60px) rotate(-12deg); opacity:0; filter:blur(3px); }
                            }
                            @keyframes nextSlideIn {
                                0%   { opacity:0; transform:translateY(18px) scale(0.97); }
                                100% { opacity:1; transform:translateY(0) scale(1); }
                            }
                            .bet-vanish-oui { animation: voteVanishOui 0.72s cubic-bezier(0.4,0,0.2,1) forwards !important; }
                            .bet-vanish-non { animation: voteVanishNon 0.65s cubic-bezier(0.4,0,0.2,1) forwards !important; }
                        `;
                        document.head.appendChild(s);
                    }

                    // Lancer l'animation de disparition
                    card.style.boxShadow = '';
                    card.style.transition = '';
                    card.classList.add(isOui ? 'bet-vanish-oui' : 'bet-vanish-non');

                    card.addEventListener('animationend', () => {
                        // Réduire la hauteur pour que le suivant remonte
                        card.style.transition = 'height 0.25s ease, margin 0.25s ease, padding 0.25s ease, opacity 0.2s ease';
                        card.style.height  = '0';
                        card.style.margin  = '0';
                        card.style.padding = '0';
                        card.style.opacity = '0';

                        // Faire apparaître le suivant
                        const next = card.nextElementSibling;
                        if (next && next.classList.contains('gage-card')) {
                            next.style.animation = 'nextSlideIn 0.4s ease forwards';
                        }

                        setTimeout(() => card.remove(), 280);
                    }, { once: true });

                }, 200);
            }, 700);
        })
        .catch(() => { zone.querySelectorAll('button').forEach(b => b.disabled = false); });
}

setInterval(loadMessages, 3000);
setInterval(loadFriends, 15000);
</script>

<!-- Modal Report -->
<div class="modal fade" id="reportModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content bg-dark border-danger text-white">
            <div class="modal-header border-secondary py-2">
                <h6 class="modal-title small text-danger">🚩 Signaler un gage</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="submit_report.php" method="POST">
                <input type="hidden" name="target_id" id="reportTargetId">
                <input type="hidden" name="target_type" value="bet">
                <div class="modal-body p-3">
                    <label class="small text-white d-block mb-1">Raison</label>
                    <select name="reason" class="form-select form-select-sm mb-2">
                        <option value="violent">Violent</option>
                        <option value="sexual">Sexuel</option>
                        <option value="inadequate" selected>Inadéquat</option>
                        <option value="other">Autre</option>
                    </select>
                    <label class="small text-white d-block mb-1">Note (optionnel)</label>
                    <textarea name="notes" class="form-control form-control-sm" rows="2" placeholder="Explique brièvement…"></textarea>
                </div>
                <div class="modal-footer border-secondary py-2">
                    <button type="submit" class="btn btn-danger btn-sm fw-bold w-100">ENVOYER</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modale Gage Rapide -->
<div class="modal fade" id="gageRapideModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-warning text-white">
            <div class="modal-header border-secondary py-2">
                <h6 class="modal-title text-warning fw-bold">Gage Rapide</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="index.php" method="POST">
                <input type="hidden" name="action" value="create_bet">
                <input type="hidden" name="description" id="gageRapideFinal">
                <div class="modal-body">
                    <!-- Phrase en haut -->
                    <div class="p-2 mb-3 rounded" style="background:#111;border:1px solid #444;">
                        <span style="font-size:0.75rem;color:#888;" id="gageRapidePrefix">Je te gage que...</span>
                        <span style="font-size:0.75rem;color:#fff;font-weight:bold;" id="gageUserPreview"></span>
                    </div>
                    <!-- Champ en dessous -->
                    <label class="text-white small d-block mb-1">Ta phrase :</label>
                    <input type="text" id="gageRapideDesc"
                           class="form-control bg-dark text-white border-secondary mb-3"
                           placeholder="...va gagner ce soir !"
                           oninput="document.getElementById('gageUserPreview').innerText=' '+this.value; updateGageFinal()"
                           required>
                    <div class="row g-2">
                        <div class="col-6">
                            <label class="text-white small">Points d'honneur</label>
                            <input type="number" name="amount" value="5" min="1" max="50" class="form-control form-control-sm bg-dark text-white border-secondary">
                        </div>
                        <div class="col-6">
                            <label class="text-white small">Visible</label>
                            <select name="is_global" class="form-select form-select-sm bg-dark text-white border-secondary">
                                <option value="0">Mon cercle</option>
                                <option value="1">Tout le site</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-secondary py-2">
                    <button type="submit" class="btn btn-warning fw-bold w-100" onclick="updateGageFinal()">LANCER LE GAGE</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modale notation utilisateur -->
<div class="modal fade" id="ratingModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content bg-dark border-warning text-white">
            <div class="modal-header border-secondary py-2">
                <h6 class="modal-title text-warning fw-bold" id="ratingTitle">Evaluer</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <div id="starSelector" style="font-size:2rem;cursor:pointer;letter-spacing:4px;color:#ffc107;">
                        <span data-v="1" onclick="setRating(1)">★</span>
                        <span data-v="2" onclick="setRating(2)">★</span>
                        <span data-v="3" onclick="setRating(3)">★</span>
                        <span data-v="4" onclick="setRating(4)">★</span>
                        <span data-v="5" onclick="setRating(5)">★</span>
                    </div>
                    <div id="ratingValue" class="text-warning small">3/5</div>
                </div>
                <input type="text" id="ratingComment" class="form-control form-control-sm bg-dark text-white border-secondary"
                       placeholder="Commentaire (optionnel)..." maxlength="200">
            </div>
            <div class="modal-footer border-secondary py-2">
                <button type="button" class="btn btn-warning fw-bold w-100" onclick="submitRating()">ENVOYER</button>
            </div>
        </div>
    </div>
</div>

<!-- Pastille retour en haut (mobile) -->
<button id="scrollTopBtn" onclick="window.scrollTo({top:0,behavior:'smooth'})" title="Retour en haut">↑</button>

<!-- ══ MODALE DÉTAIL GAGE ════════════════════════════════════════ -->
<div id="betDetailOverlay" style="display:none;position:fixed;inset:0;z-index:9999;background:rgba(0,0,0,0.92);overscroll-behavior:contain;" onclick="if(event.target===this)closeBetModal()">
    <div id="betDetailPanel" style="position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:12px;">
        <div id="betDetailCard" style="background:#0d0d1a;border:1px solid #1a1a3a;border-radius:12px;width:min(520px,94vw);max-height:90vh;overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none;position:relative;">
            <style>#betDetailCard::-webkit-scrollbar{display:none}</style>

            <!-- Header -->
            <div style="background:#050520;padding:12px 16px;border-bottom:2px solid #0dcaf0;border-radius:12px 12px 0 0;display:flex;align-items:center;justify-content:space-between;position:sticky;top:0;z-index:2;">
                <div style="display:flex;align-items:center;gap:8px;">
                    <span id="bdBadge" style="font-size:0.58rem;font-weight:700;letter-spacing:1px;padding:2px 8px;border-radius:4px;border:1px solid #0dcaf0;color:#0dcaf0;"></span>
                    <span id="bdId" style="font-size:0.7rem;color:#888;"></span>
                </div>
                <div style="display:flex;gap:8px;align-items:center;">
                    <button id="bdPrev" onclick="navBet(-1)" style="background:rgba(255,255,255,0.08);border:1px solid #333;color:#ddd;border-radius:50%;width:28px;height:28px;font-size:0.75rem;cursor:pointer;display:flex;align-items:center;justify-content:center;">↑</button>
                    <button id="bdNext" onclick="navBet(1)"  style="background:rgba(255,255,255,0.08);border:1px solid #333;color:#ddd;border-radius:50%;width:28px;height:28px;font-size:0.75rem;cursor:pointer;display:flex;align-items:center;justify-content:center;">↓</button>
                    <button onclick="closeBetModal()" style="background:none;border:none;color:#666;cursor:pointer;font-size:1.1rem;line-height:1;">✕</button>
                </div>
            </div>

            <!-- Corps -->
            <div style="padding:20px;">
                <!-- Description -->
                <div id="bdDesc" style="font-size:1.05rem;font-weight:700;color:#fff;line-height:1.5;margin-bottom:16px;"></div>

                <!-- Infos -->
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-bottom:16px;">
                    <div style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">LANCEUR</div>
                        <div id="bdLanceur" style="font-size:0.82rem;color:#0dcaf0;font-weight:600;"></div>
                    </div>
                    <div style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">ADVERSAIRE</div>
                        <div id="bdParieur2" style="font-size:0.82rem;color:#a78bfa;font-weight:600;"></div>
                    </div>
                    <div style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">POINTS</div>
                        <div id="bdAmount" style="font-size:0.9rem;color:#ffc107;font-weight:700;"></div>
                    </div>
                    <div style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">STATUT</div>
                        <div id="bdStatus" style="font-size:0.82rem;font-weight:700;"></div>
                    </div>
                    <div id="bdJetonsWrap" style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;display:none;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">JETONS</div>
                        <div id="bdJetons" style="font-size:0.9rem;color:#ffc107;font-weight:700;"></div>
                    </div>
                    <div id="bdEcheanceWrap" style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;display:none;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">ÉCHÉANCE</div>
                        <div id="bdEcheance" style="font-size:0.78rem;color:#ddd;"></div>
                    </div>
                    <div id="bdCercleWrap" style="background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px;display:none;">
                        <div style="font-size:0.55rem;color:#888;letter-spacing:1px;margin-bottom:3px;">CERCLE</div>
                        <div id="bdCercle" style="font-size:0.78rem;color:#888;"></div>
                    </div>
                </div>

                <!-- Votes -->
                <div id="bdVotesWrap" style="margin-bottom:16px;display:none;">
                    <div style="font-size:0.6rem;color:#888;letter-spacing:1px;margin-bottom:5px;">VOTES DE LA COMMUNAUTÉ</div>
                    <div style="display:flex;justify-content:space-between;font-size:0.7rem;margin-bottom:3px;">
                        <span id="bdOui" style="color:#28a745;font-weight:700;"></span>
                        <span id="bdNon" style="color:#dc3545;font-weight:700;"></span>
                    </div>
                    <div style="height:5px;background:#222;border-radius:3px;overflow:hidden;">
                        <div id="bdBar" style="height:100%;background:linear-gradient(90deg,#28a745,#dc3545);border-radius:3px;transition:width 0.3s;"></div>
                    </div>
                </div>

                <!-- Actions -->
                <div id="bdActions" style="display:flex;gap:8px;flex-wrap:wrap;"></div>
            </div>

            <!-- Indicateur swipe mobile -->
            <div class="d-md-none" style="text-align:center;padding:8px 0 12px;color:#333;font-size:0.6rem;">
                ↕ Glisser haut/bas pour naviguer entre les gages
            </div>
        </div>
    </div>
</div>

<?php include 'footer.php'; ?>