<?php
session_start();
require_once 'config.php';
require_once 'functions.php';

if (!isset($_SESSION['user_id'])) { http_response_code(403); exit; }
$userId = (int)$_SESSION['user_id'];
$user   = getConnectedUser($pdo);
$isAdm  = isAdmin($user);
$tier   = $user['tier'] ?? 'free';

// Limites depuis admin_config
function getLimitCfg($pdo, $key, $default) {
    try {
        // Insérer la valeur par défaut si elle n'existe pas encore
        $pdo->prepare("INSERT IGNORE INTO admin_config (config_key,config_value) VALUES (?,?)")
            ->execute([$key, $default]);
        $s = $pdo->prepare("SELECT config_value FROM admin_config WHERE config_key=?");
        $s->execute([$key]); $v = $s->fetchColumn();
        return $v !== false ? (int)$v : $default;
    } catch (Exception $e) { return $default; }
}
$tierKey    = str_replace('_plus','plus', str_replace('premium_plus','premplus',$tier));
$maxCircles = $isAdm ? 999 : getLimitCfg($pdo, "limit_circles_{$tierKey}", ['free'=>1,'premium'=>5,'premium_plus'=>20][$tier]??1);
$tierLabels = ['free'=>'Free','premium'=>'Premium','premium_plus'=>'Premium+','admin'=>'Admin'];

// ── AJAX ACTIONS ──────────────────────────────────────────────
$action = $_GET['action'] ?? '';

if ($action === 'switch') {
    $cid = (int)$_GET['id'];
    $chk = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id=? AND user_id=?");
    $chk->execute([$cid, $userId]);
    if ($chk->fetch() || $isAdm) { $_SESSION['circle_id'] = $cid; echo 'ok'; } else { echo 'denied'; }
    exit;
}

if ($action === 'create') {
    $name = trim(htmlspecialchars($_POST['name'] ?? ''));
    if (!$name) { echo json_encode(['error'=>'Nom requis.']); exit; }
    // Compter seulement les cercles réellement créés par l'user (exclure cercle système id=1)
    $myCount = (int)$pdo->query("SELECT COUNT(*) FROM circles WHERE creator_id={$userId} AND id > 1")->fetchColumn();
    if ($myCount >= $maxCircles) { echo json_encode(['error'=>"Limite atteinte ({$maxCircles} max)."]); exit; }
    do {
        $code = strtoupper(substr(md5(uniqid(rand(),true)),0,8));
        $chk  = $pdo->prepare("SELECT id FROM circles WHERE invite_code=?"); $chk->execute([$code]);
    } while ($chk->fetch());
    $pdo->prepare("INSERT INTO circles (name,creator_id,invite_code,oracle_id) VALUES (?,?,?,?)")->execute([$name,$userId,$code,$userId]);
    $newId = (int)$pdo->lastInsertId();
    $pdo->prepare("INSERT INTO circle_members (circle_id,user_id) VALUES (?,?)")->execute([$newId,$userId]);
    $_SESSION['circle_id'] = $newId;
    echo json_encode(['ok'=>true,'name'=>$name,'code'=>$code,'id'=>$newId]);
    exit;
}

if ($action === 'leave') {
    $cid = (int)$_GET['id'];
    $chk = $pdo->prepare("SELECT creator_id FROM circles WHERE id=?"); $chk->execute([$cid]); $row=$chk->fetch();
    if ($row && (int)$row['creator_id']===$userId && !$isAdm) { echo 'creator'; exit; }
    $pdo->prepare("DELETE FROM circle_members WHERE circle_id=? AND user_id=?")->execute([$cid,$userId]);
    if ((int)($_SESSION['circle_id']??0)===$cid) $_SESSION['circle_id']=0;
    echo 'ok'; exit;
}

if ($action === 'join_code') {
    $code = strtoupper(trim($_GET['code']??''));
    if (!$code) { echo json_encode(['error'=>'Code vide.']); exit; }
    $cStmt = $pdo->prepare("SELECT id,name,oracle_id,creator_id FROM circles WHERE invite_code=?"); $cStmt->execute([$code]); $cRow=$cStmt->fetch();
    if (!$cRow) { echo json_encode(['error'=>'Code invalide.']); exit; }
    $chk = $pdo->prepare("SELECT id FROM circle_members WHERE circle_id=? AND user_id=?"); $chk->execute([$cRow['id'],$userId]);
    if ($chk->fetch()) { echo json_encode(['error'=>'Déjà membre de ce cercle.']); exit; }
    // Vérifier demande existante
    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){}
    $existReq = $pdo->prepare("SELECT status FROM circle_join_requests WHERE circle_id=? AND user_id=?"); $existReq->execute([$cRow['id'],$userId]); $er=$existReq->fetch();
    if ($er && $er['status']==='pending') { echo json_encode(['pending'=>true,'name'=>$cRow['name']]); exit; }
    if ($er && $er['status']==='refused') { echo json_encode(['error'=>'Ta demande a été refusée.']); exit; }
    // 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([$cRow['id'],$userId]);
    // Notifier Oracle/créateur
    $notifyId = (int)($cRow['oracle_id'] ?: $cRow['creator_id']);
    if ($notifyId && function_exists('addNotification')) {
        $uname = $pdo->prepare("SELECT username FROM users WHERE id=?"); $uname->execute([$userId]); $un=$uname->fetchColumn();
        addNotification($pdo, $notifyId, "$un demande à rejoindre le cercle {$cRow['name']}", "gestion_cercle.php");
    }
    echo json_encode(['ok'=>true,'pending'=>true,'name'=>$cRow['name'],'msg'=>"Demande envoyée ! L'Oracle doit approuver."]);
    exit;
}

if ($action === 'invite') {
    $cid=$_GET['cid']??0; $name=trim($_POST['username']??'');
    $c=$pdo->prepare("SELECT creator_id,oracle_id,name,invite_code FROM circles WHERE id=?"); $c->execute([$cid]); $circle=$c->fetch();
    if (!$circle||(((int)$circle['creator_id']!==$userId&&(int)$circle['oracle_id']!==$userId)&&!$isAdm)){echo json_encode(['error'=>'Non autorisé']);exit;}
    $inv=$pdo->prepare("SELECT id,username FROM users WHERE username=?"); $inv->execute([$name]); $invUser=$inv->fetch();
    if (!$invUser){echo json_encode(['error'=>'Introuvable']);exit;}
    $chk2=$pdo->prepare("SELECT id FROM circle_members WHERE circle_id=? AND user_id=?"); $chk2->execute([$cid,$invUser['id']]);
    if ($chk2->fetch()){echo json_encode(['error'=>'Déjà membre']);exit;}
    addNotification($pdo,$invUser['id'],$user['username']." t'invite dans \"".$circle['name']."\"","index.php");
    echo json_encode(['ok'=>true,'msg'=>"Invitation envoyée à ".htmlspecialchars($invUser['username'])]);
    exit;
}

if ($action === 'search_users') {
    $cid=(int)($_GET['cid']??0); $q='%'.trim($_GET['q']??'').'%';
    $s=$pdo->prepare("SELECT id,username FROM users WHERE username LIKE ? AND id NOT IN (SELECT user_id FROM circle_members WHERE circle_id=?) LIMIT 6");
    $s->execute([$q,$cid]); echo json_encode($s->fetchAll(PDO::FETCH_ASSOC)); exit;
}

if ($action === 'remove_member') {
    $cid=(int)$_GET['cid']; $mid=(int)$_GET['mid'];
    $c=$pdo->prepare("SELECT creator_id,oracle_id,name FROM circles WHERE id=?"); $c->execute([$cid]); $circle=$c->fetch();
    if (!$circle||(((int)$circle['creator_id']!==$userId&&(int)$circle['oracle_id']!==$userId)&&!$isAdm)){echo 'denied';exit;}
    $pdo->prepare("DELETE FROM circle_members WHERE circle_id=? AND user_id=?")->execute([$cid,$mid]);
    echo 'ok'; exit;
}

// ── CHARGEMENT DES CERCLES ─────────────────────────────────
try {
    $stmt = $pdo->prepare("
        SELECT c.id, c.name, c.oracle_id, c.invite_code, c.creator_id,
               (SELECT COUNT(*) FROM circle_members WHERE circle_id=c.id) AS nb_membres,
               (SELECT COUNT(*) FROM bets b2 WHERE b2.circle_id=c.id AND b2.status='pending') AS nb_gages
        FROM circles c
        JOIN circle_members cm ON cm.circle_id=c.id
        WHERE cm.user_id=?
        ORDER BY c.name ASC
    ");
    $stmt->execute([$userId]);
    $circles = $stmt->fetchAll();
} catch (Exception $e) { $circles=[]; }

$myCount   = (int)$pdo->query("SELECT COUNT(*) FROM circles WHERE creator_id={$userId} AND id > 1")->fetchColumn();
$activeId  = (int)($_SESSION['circle_id'] ?? 0);
$canCreate = $myCount < $maxCircles;

// Si pas de cercle actif mais l'user en a, prendre le premier
if ($activeId === 0 && !empty($circles)) {
    $activeId = (int)$circles[0]['id'];
    $_SESSION['circle_id'] = $activeId;
}

// Cercle actif complet avec membres
$activeCircle = null;
$activeMembers = [];
if ($activeId > 0) {
    foreach ($circles as $c) {
        if ((int)$c['id'] === $activeId) { $activeCircle = $c; break; }
    }
    if ($activeCircle) {
        try {
            $mStmt = $pdo->prepare("
                SELECT u.id, u.username, u.tier, u.last_activity, u.role_status
                FROM circle_members cm JOIN users u ON u.id=cm.user_id
                WHERE cm.circle_id=? ORDER BY u.username ASC
            ");
            $mStmt->execute([$activeId]);
            $activeMembers = $mStmt->fetchAll();
        } catch (Exception $e) {}
    }
}
?>
<style>
.cc-btn{border-radius:5px;padding:4px 10px;font-size:0.65rem;font-weight:700;cursor:pointer;border:1px solid;transition:opacity 0.15s;background:none}
.cc-btn:hover{opacity:0.8}
.cc-input{background:#0a0a14;border:1px solid #333;color:#ddd;border-radius:5px;padding:5px 9px;font-size:0.7rem;width:100%}
.cc-input:focus{outline:none;border-color:#fd7e14}
.cc-tab{padding:5px 12px;font-size:0.62rem;font-weight:700;cursor:pointer;border-bottom:2px solid transparent;color:#888;letter-spacing:0.5px;transition:all 0.15s}
.cc-tab.active{color:#fd7e14;border-bottom-color:#fd7e14}
.cc-msg{font-size:0.68rem;padding:5px 9px;border-radius:5px;margin-bottom:8px;display:none}
</style>

<?php if (empty($circles)): ?>
<!-- ══════════════════════════════════════════════
     PAS DE CERCLE — 2 options : Créer ou Rejoindre
═══════════════════════════════════════════════ -->
<div style="text-align:center;padding:20px 10px 16px;">
    <div style="font-size:2rem;margin-bottom:8px;">🔵</div>
    <div style="font-size:0.82rem;color:#ddd;font-weight:600;margin-bottom:4px;">Vous n'êtes dans aucun cercle</div>
    <div style="font-size:0.65rem;color:#888;">Créez votre propre cercle ou rejoignez-en un avec un code d'invitation.</div>
</div>

<div style="display:flex;gap:0;border-bottom:1px solid #1a1a1a;margin-bottom:12px;">
    <div class="cc-tab active" id="nc-tab-creer" onclick="ncTab('creer')">+ CRÉER UN CERCLE</div>
    <div class="cc-tab" id="nc-tab-rejoindre" onclick="ncTab('rejoindre')">REJOINDRE</div>
</div>

<!-- Créer -->
<div id="nc-sec-creer">
    <!-- Quota -->
    <div style="background:#0a0a12;border:1px solid #1a1a2a;border-radius:6px;padding:8px 12px;margin-bottom:10px;display:flex;align-items:center;justify-content:space-between;">
        <?php
        $tierColors=['free'=>'#aaa','premium'=>'#d4af37','premium_plus'=>'#a9a9a9','admin'=>'#dc3545'];
        $tc=$tierColors[$tier]??'#aaa';
        ?>
        <span style="font-size:0.72rem;font-weight:700;color:<?=$tc?>"><?=$tierLabels[$tier]??strtoupper($tier)?></span>
        <span style="font-size:0.68rem;color:<?=$canCreate?'#28a745':'#dc3545'?>;">
            <?=$myCount?> / <?=$maxCircles===999?'∞':$maxCircles?> cercle<?=$maxCircles>1?'s':''?> créé<?=$maxCircles>1?'s':''?>
        </span>
    </div>
    <?php if ($canCreate): ?>
    <div id="nc-create-msg" class="cc-msg"></div>
    <label style="font-size:0.62rem;color:#888;display:block;margin-bottom:4px;letter-spacing:0.5px;">NOM DU CERCLE</label>
    <input class="cc-input" id="nc-name" placeholder="Ex: Les Fous du Sport..." maxlength="50" autocomplete="off" style="margin-bottom:10px;">
    <button class="cc-btn" style="background:rgba(253,126,20,0.2);border-color:#fd7e14;color:#fd7e14;padding:8px;font-size:0.72rem;width:100%;" onclick="ncCreate()">
        🔵 Créer mon cercle
    </button>
    <?php else: ?>
    <div style="text-align:center;padding:12px;color:#888;">
        <div style="font-size:1.3rem;margin-bottom:6px;">🔒</div>
        <div style="font-size:0.72rem;">Limite atteinte pour votre forfait.</div>
        <a href="upgrade.php" style="color:#ffc107;font-size:0.68rem;font-weight:700;">Passer à Premium →</a>
    </div>
    <?php endif; ?>
</div>

<!-- Rejoindre -->
<div id="nc-sec-rejoindre" style="display:none;">
    <div id="nc-join-msg" class="cc-msg"></div>
    <div style="font-size:0.68rem;color:#999;margin-bottom:10px;">Entrez le code reçu d'un membre de cercle.</div>
    <label style="font-size:0.62rem;color:#888;display:block;margin-bottom:4px;letter-spacing:0.5px;">CODE D'INVITATION</label>
    <input class="cc-input" id="nc-code" placeholder="Ex: A3B7F2C9" maxlength="10" autocomplete="off"
           style="text-transform:uppercase;font-family:'Courier New',monospace;font-size:1rem;font-weight:700;letter-spacing:4px;text-align:center;margin-bottom:10px;">
    <button class="cc-btn" style="background:rgba(13,202,240,0.12);border-color:#0dcaf0;color:#0dcaf0;padding:8px;font-size:0.72rem;width:100%;" onclick="ncJoin()">
        Rejoindre ce cercle
    </button>
</div>

<?php else: ?>
<!-- ══════════════════════════════════════════════
     MEMBRE D'AU MOINS UN CERCLE
═══════════════════════════════════════════════ -->

<!-- Sélecteur de cercle si plusieurs -->
<?php if (count($circles) > 1): ?>
<div style="margin-bottom:10px;">
    <label style="font-size:0.6rem;color:#888;letter-spacing:1px;display:block;margin-bottom:4px;">CHANGER DE CERCLE ACTIF</label>
    <div style="display:flex;flex-wrap:wrap;gap:5px;">
    <?php foreach ($circles as $c):
        $cIsAct = (int)$c['id'] === $activeId;
        $cId2   = (int)$c['id'];
    ?>
        <?php if ($cIsAct): ?>
        <button disabled style="background:rgba(253,126,20,0.2);border:1px solid #fd7e14;color:#fd7e14;border-radius:5px;padding:3px 10px;font-size:0.65rem;font-weight:700;cursor:default;">
            ● <?=htmlspecialchars($c['name'])?>
        </button>
        <?php else: ?>
        <button onclick="ccSwitchCircle(<?=$cId2?>)" style="background:rgba(255,255,255,0.04);border:1px solid #333;color:#aaa;border-radius:5px;padding:3px 10px;font-size:0.65rem;font-weight:700;cursor:pointer;">
            <?=htmlspecialchars($c['name'])?>
        </button>
        <?php endif; ?>
    <?php endforeach; ?>
    </div>
</div>
<?php endif; ?>

<?php if ($activeCircle): ?>
<!-- Info du cercle actif -->
<div style="background:rgba(253,126,20,0.06);border:1px solid rgba(253,126,20,0.3);border-radius:8px;padding:10px 12px;margin-bottom:10px;">
    <div style="display:flex;align-items:center;gap:7px;margin-bottom:6px;">
        <span style="width:8px;height:8px;border-radius:50%;background:#fd7e14;box-shadow:0 0 6px #fd7e14;display:inline-block;flex-shrink:0;"></span>
        <span style="font-size:0.85rem;font-weight:700;color:#fd7e14;"><?=htmlspecialchars($activeCircle['name'])?></span>
        <?php $isCreator=(int)$activeCircle['creator_id']===$userId; $isOracle=(int)$activeCircle['oracle_id']===$userId; ?>
        <?php if($isCreator&&$isOracle): ?>
        <span style="font-size:0.52rem;background:rgba(253,126,20,0.2);border:1px solid #fd7e14;color:#fd7e14;border-radius:8px;padding:0 5px;">👑 Créateur · Oracle</span>
        <?php elseif($isCreator): ?>
        <span style="font-size:0.52rem;background:rgba(253,126,20,0.15);border:1px solid #fd7e14;color:#fd7e14;border-radius:8px;padding:0 5px;">👑 Créateur</span>
        <?php elseif($isOracle): ?>
        <span style="font-size:0.52rem;background:rgba(167,139,250,0.2);border:1px solid #a78bfa;color:#a78bfa;border-radius:8px;padding:0 5px;">⚖️ Oracle</span>
        <?php endif; ?>
    </div>
    <div style="display:flex;gap:12px;font-size:0.62rem;color:#888;margin-bottom:8px;">
        <span>👥 <?=(int)$activeCircle['nb_membres']?> membre<?=$activeCircle['nb_membres']>1?'s':''?></span>
        <span>⚡ <?=(int)$activeCircle['nb_gages']?> gage<?=$activeCircle['nb_gages']>1?'s':''?> actif<?=$activeCircle['nb_gages']>1?'s':''?></span>
    </div>
    <!-- Actions rapides -->
    <div style="display:flex;gap:5px;flex-wrap:wrap;">
        <button onclick="openChatForCircle(<?=$activeId?>)" style="background:rgba(13,202,240,0.12);border:1px solid rgba(13,202,240,0.4);color:#0dcaf0;border-radius:5px;padding:4px 10px;font-size:0.65rem;font-weight:700;cursor:pointer;">💬 Mur</button>
        <?php if($isCreator||$isOracle||$isAdm): ?>
        <button onclick="ccToggleSection('cc-manage')" class="cc-btn" style="background:rgba(13,202,240,0.08);border-color:rgba(13,202,240,0.3);color:#0dcaf0;">⚙️ Gérer</button>
        <?php endif; ?>
        <button onclick="ccToggleSection('cc-bet')" class="cc-btn" style="background:rgba(255,193,7,0.1);border-color:rgba(255,193,7,0.35);color:#ffc107;">⚡ Lancer un gage</button>
        <?php if($activeCircle['invite_code']): ?>
        <button onclick="ccCopyCodeFallback('<?=htmlspecialchars($activeCircle['invite_code'])?>', this)" class="cc-btn" style="background:rgba(255,255,255,0.04);border-color:#777;color:#888;">📋 Code</button>
        <?php endif; ?>
    </div>
</div>

<!-- LANCER UN GAGE dans le cercle -->
<div id="cc-bet" style="display:none;background:#080810;border:1px solid #1a1a2a;border-radius:8px;padding:10px 12px;margin-bottom:10px;">
    <div style="font-size:0.62rem;color:#ffc107;font-weight:700;letter-spacing:1px;margin-bottom:8px;">⚡ NOUVEAU GAGE DANS CE CERCLE</div>
    <div id="cc-bet-msg" class="cc-msg"></div>
    <label style="font-size:0.6rem;color:#888;display:block;margin-bottom:3px;">DÉFI</label>
    <textarea id="cc-bet-desc" class="cc-input" rows="2" placeholder="Décris le gage..." style="resize:none;margin-bottom:7px;"></textarea>
    <div style="display:flex;gap:6px;margin-bottom:7px;">
        <div style="flex:1;">
            <label style="font-size:0.6rem;color:#888;display:block;margin-bottom:3px;">GAGEUR 2</label>
            <input class="cc-input" id="cc-bet-p2" placeholder="Pseudo (optionnel)">
        </div>
        <div style="width:80px;">
            <label style="font-size:0.6rem;color:#888;display:block;margin-bottom:3px;">POINTS</label>
            <input class="cc-input" id="cc-bet-pts" type="number" value="10" min="0" max="9999">
        </div>
    </div>
    <div style="display:flex;gap:6px;">
        <button class="cc-btn" style="flex:1;background:rgba(255,193,7,0.15);border-color:#ffc107;color:#ffc107;padding:7px;" onclick="ccSubmitBet(<?=$activeId?>)">⚡ Lancer</button>
        <button class="cc-btn" style="border-color:#777;color:#888;" onclick="ccToggleSection('cc-bet')">Annuler</button>
    </div>
</div>

<!-- GESTION DU CERCLE -->
<?php if($isCreator||$isOracle||$isAdm): ?>
<div id="cc-manage" style="display:none;background:#080810;border:1px solid #1a1a2a;border-radius:8px;padding:10px 12px;margin-bottom:10px;">
    <div style="display:flex;gap:0;border-bottom:1px solid #111;margin-bottom:8px;">
        <div class="cc-tab active" id="mt-membres" onclick="ccManTab('membres')">MEMBRES</div>
        <div class="cc-tab" id="mt-inviter" onclick="ccManTab('inviter')">INVITER</div>
        <div class="cc-tab" id="mt-code" onclick="ccManTab('code')">CODE</div>
    </div>
    <!-- Membres -->
    <div id="mp-membres">
    <?php foreach($activeMembers as $m):
        $mOnline=(time()-strtotime($m['last_activity']??'2000-01-01'))<300;
        $isOM=(int)$activeCircle['oracle_id']===(int)$m['id'];
        $tc2=match($m['tier']??'free'){'admin'=>'#dc3545','premium_plus'=>'#ffc107','premium'=>'#4d90fe',default=>'#555'};
    ?>
    <div style="display:flex;align-items:center;gap:7px;padding:4px 0;border-bottom:1px solid #0d0d0d;">
        <span style="width:6px;height:6px;border-radius:50%;background:<?=$mOnline?'#28a745':'#333'?>;flex-shrink:0;"></span>
        <span style="flex:1;font-size:0.72rem;color:#ddd;"><?=htmlspecialchars($m['username'])?></span>
        <?php if($isOM): ?><span style="font-size:0.58rem;color:#a78bfa;">⚖️</span><?php endif; ?>
        <span style="font-size:0.6rem;color:<?=$tc2?>;"><?=strtoupper($m['tier']??'FREE')?></span>
        <?php if((int)$m['id']!==$userId): ?>
        <button onclick="ccRemoveMember(<?=$activeId?>,<?=(int)$m['id']?>,'<?=htmlspecialchars(addslashes($m['username']))?>')" style="background:rgba(220,53,69,0.12);border:1px solid #dc3545;color:#dc3545;border-radius:3px;padding:1px 5px;font-size:0.58rem;cursor:pointer;">✕</button>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    </div>
    <!-- Inviter -->
    <div id="mp-inviter" style="display:none;">
        <div id="cc-inv-msg" class="cc-msg"></div>
        <input class="cc-input" id="cc-inv-search" placeholder="Rechercher..." oninput="ccSearchInv(<?=$activeId?>,this.value)" style="margin-bottom:5px;" autocomplete="off">
        <div id="cc-inv-results" style="margin-bottom:5px;"></div>
        <div style="display:flex;gap:5px;">
            <input class="cc-input" id="cc-inv-name" placeholder="Nom exact..." style="flex:1;">
            <button class="cc-btn" style="background:rgba(40,167,69,0.15);border-color:#777;color:#28a745;" onclick="ccInvite(<?=$activeId?>)">Inviter</button>
        </div>
    </div>
    <!-- Code -->
    <div id="mp-code" style="display:none;text-align:center;padding:8px 0;">
        <div style="font-size:0.62rem;color:#888;margin-bottom:6px;">Code d'invitation</div>
        <div style="font-size:1.1rem;font-weight:700;color:#ffc107;letter-spacing:4px;font-family:'Courier New',monospace;background:#0a0a0a;border:1px solid #2a2200;border-radius:6px;padding:8px 16px;display:inline-block;margin-bottom:8px;"><?=htmlspecialchars($activeCircle['invite_code']??'—')?></div>
        <br>
        <button onclick="ccCopyCodeFallback('<?=htmlspecialchars($activeCircle['invite_code']??'')?>', this)" class="cc-btn" style="background:rgba(255,193,7,0.1);border-color:#ffc107;color:#ffc107;">📋 Copier</button>
    </div>
</div>
<?php endif; ?>

<?php endif; // activeCircle ?>

<!-- Liste des autres cercles (si plusieurs) -->
<?php if (count($circles) > 1): ?>
<div style="font-size:0.6rem;color:#888;letter-spacing:1px;margin-bottom:6px;margin-top:4px;">AUTRES CERCLES</div>
<?php foreach($circles as $c):
    if((int)$c['id']===$activeId) continue;
    $name=htmlspecialchars($c['name']); $cId=(int)$c['id'];
?>
<div style="display:flex;align-items:center;justify-content:space-between;padding:5px 8px;background:#0a0a12;border:1px solid #1a1a2a;border-radius:5px;margin-bottom:4px;">
    <span style="font-size:0.72rem;color:#aaa;"><?=$name?></span>
    <div style="display:flex;gap:4px;">
        <button onclick="openChatForCircle(<?=$cId?>)" style="background:rgba(13,202,240,0.1);border:1px solid rgba(13,202,240,0.3);color:#0dcaf0;border-radius:4px;padding:2px 7px;font-size:0.6rem;font-weight:700;cursor:pointer;">💬 Mur</button>
        <button onclick="ccSwitchCircle(<?=$cId?>)" style="background:rgba(253,126,20,0.12);border:1px solid rgba(253,126,20,0.4);color:#fd7e14;border-radius:4px;padding:2px 7px;font-size:0.6rem;font-weight:700;cursor:pointer;">Activer</button>
    </div>
</div>
<?php endforeach; ?>
<?php endif; ?>

<!-- Quitter / Rejoindre autre cercle -->
<div style="display:flex;gap:6px;margin-top:8px;padding-top:8px;border-top:1px solid #111;">
    <?php if($canCreate): ?>
    <button class="cc-btn" style="flex:1;background:rgba(253,126,20,0.1);border-color:rgba(253,126,20,0.3);color:#fd7e14;text-align:center;padding:6px;" onclick="ccToggleSection('cc-new-circle')">+ Créer un cercle</button>
    <?php endif; ?>
    <button class="cc-btn" style="flex:1;background:rgba(13,202,240,0.06);border-color:rgba(13,202,240,0.2);color:#0dcaf0;text-align:center;padding:6px;" onclick="ccToggleSection('cc-join')">Rejoindre avec code</button>
    <?php if($activeCircle && !$isCreator): ?>
    <button class="cc-btn" style="background:rgba(220,53,69,0.08);border-color:rgba(220,53,69,0.25);color:#dc3545;padding:6px;" onclick="ccLeave(<?=$activeId?>,'<?=htmlspecialchars(addslashes($activeCircle['name']))?>')">Quitter</button>
    <?php endif; ?>
</div>

<!-- Formulaire créer (caché) -->
<div id="cc-new-circle" style="display:none;margin-top:8px;background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px 12px;">
    <div id="cc-new-msg" class="cc-msg"></div>
    <input class="cc-input" id="cc-new-name" placeholder="Nom du nouveau cercle..." maxlength="50" autocomplete="off" style="margin-bottom:8px;">
    <div style="display:flex;gap:5px;">
        <button class="cc-btn" style="flex:1;background:rgba(253,126,20,0.2);border-color:#fd7e14;color:#fd7e14;padding:6px;" onclick="ccCreate()">🔵 Créer</button>
        <button class="cc-btn" style="border-color:#777;color:#888;" onclick="ccToggleSection('cc-new-circle')">Annuler</button>
    </div>
</div>

<!-- Formulaire rejoindre (caché) -->
<div id="cc-join" style="display:none;margin-top:8px;background:#080810;border:1px solid #1a1a2a;border-radius:7px;padding:10px 12px;">
    <div id="cc-join-msg" class="cc-msg"></div>
    <input class="cc-input" id="cc-join-code" placeholder="Code d'invitation..." maxlength="10" autocomplete="off"
           style="text-transform:uppercase;font-family:'Courier New',monospace;font-size:0.85rem;letter-spacing:3px;text-align:center;margin-bottom:8px;">
    <div style="display:flex;gap:5px;">
        <button class="cc-btn" style="flex:1;background:rgba(13,202,240,0.12);border-color:#0dcaf0;color:#0dcaf0;padding:6px;" onclick="ccJoin()">Rejoindre</button>
        <button class="cc-btn" style="border-color:#777;color:#888;" onclick="ccToggleSection('cc-join')">Annuler</button>
    </div>
</div>

<?php endif; ?>


