@extends('layouts.member')

@section('title', 'Dashboard Membre')
@section('page-title', 'Mon Dashboard')

@section('content')
@php
    $needsSubscription = session('needs_subscription', false) || !(isset($user) ? $user->subscription_paid : (auth()->check() ? auth()->user()->subscription_paid : false));
    $subscriptionAmount = \App\Models\Setting::get('subscription_price', 5000);
@endphp

@if($needsSubscription)
    <div class="alert alert-info border-0 rounded-3 p-3 mb-4">
        <div class="d-flex align-items-center">
            <i class="bi bi-shield-lock me-2 fs-4 text-primary"></i>
            <div class="flex-grow-1">
                <strong>Abonnement MLM requis</strong>
                <p class="mb-1 small text-muted">Payez votre abonnement pour débloquer le Réseau, Commissions, Classements, Badges, Fidélité et Pool.</p>
                <p class="mb-0 small">Montant: <strong>{{ number_format($subscriptionAmount, 0, ',', ' ') }} XOF</strong></p>
            </div>

            @if(!$needsSubscription && isset($user) && $user->subscription_paid)
                <div class="alert alert-success border-0 rounded-3 p-3 mb-4">
                    <div class="d-flex align-items-center">
                        <i class="bi bi-check-circle-fill me-2 fs-4 text-success"></i>
                        <div class="flex-grow-1">
                            <strong>Abonnement MLM Actif</strong>
                            <p class="mb-0 small text-muted">Toutes les fonctionnalités MLM sont débloquées.</p>
                        </div>
                        <a href="{{ route('subscription.pdf') }}" class="btn btn-sm btn-outline-success rounded-2 ms-3" target="_blank">
                            <i class="bi bi-file-pdf me-1"></i>Télécharger mon certificat
                        </a>
                    </div>
                </div>
            @endif

            <button type="button" class="btn btn-primary btn-sm rounded-2 ms-3" onclick="openSubscriptionPayment()">
                <i class="bi bi-credit-card me-1"></i>Choisir le paiement
            </button>
        </div>
    </div>

    <div id="subscriptionPaymentSection" class="card shadow-sm border-0 rounded-3 mb-4" style="display: none;">
        <div class="card-body">
            <div class="d-flex align-items-center mb-3">
                <i class="bi bi-wallet2 text-primary fs-4 me-2"></i>
                <div>
                    <strong>Montant à payer</strong>
                    <div class="text-muted">{{ number_format($subscriptionAmount, 0, ',', ' ') }} XOF</div>
                </div>
            </div>

            <x-payment-method-selector 
                :amount="$subscriptionAmount"
                :email="auth()->user()->email ?? ''"
                :name="auth()->user()->name ?? ''"
                :phone="auth()->user()->phone ?? ''"
                :redirectUrl="route('payment.mobile-money.callback')"
                :showMobileMoney="true"
                :wallet="$wallet"
            />

            <form id="subscriptionCardForm" action="{{ route('member.subscription.pay') }}" method="POST" class="d-none">
                @csrf
            </form>

            <div class="d-flex justify-content-end gap-2">
                <button type="button" class="btn btn-outline-secondary" onclick="document.getElementById('subscriptionPaymentSection').style.display='none'">Annuler</button>
                <button type="button" class="btn btn-primary" id="subscriptionPayAction" onclick="submitSubscriptionPayment()">
                    <i class="bi bi-lock-fill me-1"></i>Valider et payer
                </button>
            </div>
        </div>
    </div>
@endif
<!-- KPI Stats Cards - Modern Design -->
<div class="row g-4 mb-4">
    <!-- Wallet Card -->
    <div class="col-lg-3 col-md-6 col-sm-12">
        <div class="stat-card modern shadow-sm border-0 rounded-3">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div class="flex-grow-1">
                    <p class="text-muted small fw-500 mb-1">💰 Portefeuille</p>
                    <h3 class="mb-1 text-success fw-700">{{ number_format($wallet->balance ?? 0, 0, ',', ' ') }} <span class="fs-6">XOF</span></h3>
                </div>
                <div class="stat-icon bg-success-light rounded-circle p-3">
                    <i class="bi bi-wallet2 text-success fs-5"></i>
                </div>
            </div>
            <p class="small text-muted mb-2">
                <i class="bi bi-hourglass-split text-warning"></i> 
                <strong>{{ number_format($wallet->pending ?? 0, 0, ',', ' ') }} XOF</strong> en attente
            </p>
            <a href="{{ route('member.wallet.index') }}" class="btn btn-sm btn-outline-success w-100 rounded-2">
                <i class="bi bi-arrow-right me-1"></i> Voir détails
            </a>
        </div>
    </div>

    <!-- Commissions Card -->
    <div class="col-lg-3 col-md-6 col-sm-12">
        <div class="stat-card modern shadow-sm border-0 rounded-3">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div class="flex-grow-1">
                    <p class="text-muted small fw-500 mb-1">📊 Commissions</p>
                    <h3 class="mb-1 text-primary fw-700">{{ number_format($totalCommissions ?? 0, 0, ',', ' ') }} <span class="fs-6">XOF</span></h3>
                </div>
                <div class="stat-icon bg-primary-light rounded-circle p-3">
                    <i class="bi bi-cash-stack text-primary fs-5"></i>
                </div>
            </div>
            <p class="small text-muted mb-2">
                <i class="bi bi-clock text-warning"></i> 
                <strong>{{ number_format($pendingCommissions ?? 0, 0, ',', ' ') }} XOF</strong> en attente
            </p>
            <a href="{{ route('member.commissions') }}" class="btn btn-sm btn-outline-primary w-100 rounded-2">
                <i class="bi bi-arrow-right me-1"></i> Voir l'historique
            </a>
        </div>
    </div>

    <!-- Network Card -->
    <div class="col-lg-3 col-md-6 col-sm-12">
        <div class="stat-card modern shadow-sm border-0 rounded-3">
            <div class="d-flex justify-content-between align-items-start mb-3">
                <div class="flex-grow-1">
                    <p class="text-muted small fw-500 mb-1">👥 Mon Réseau</p>
                    <h3 class="mb-1 text-info fw-700">{{ ($directReferrals ?? 0) + ($level2Referrals ?? 0) }}</h3>
                </div>
                <div class="stat-icon bg-info-light rounded-circle p-3">
                    <i class="bi bi-people text-info fs-5"></i>
                </div>
            </div>
            <p class="small text-muted mb-1">
                <i class="bi bi-check-circle text-success"></i> 
                <strong>{{ $activeDirectReferrals ?? 0 }}</strong> filleuls actifs (Niveau 1)
            </p>
            <p class="small text-muted mb-2">
                <i class="bi bi-check-circle text-info"></i> 
                <strong>{{ $activeLevel2Referrals ?? 0 }}</strong> filleuls actifs (Niveau 2)
            </p>
            <a href="{{ route('member.network') }}" class="btn btn-sm btn-outline-info w-100 rounded-2">
                <i class="bi bi-arrow-right me-1"></i> Consulter le réseau
            </a>
        </div>
    </div>

    <!-- Rank Card -->
    <div class="col-lg-3 col-md-6 col-sm-12">
        <div class="stat-card modern shadow-sm border-0 rounded-3 text-center">
            <div class="mb-3">
                <p class="text-muted small fw-500 mb-2">🏆 Mon Rang</p>
                <span class="badge bg-{{ $currentRank['color'] ?? 'secondary' }} fs-5 px-4 py-2 rounded-pill">
                    {{ $currentRank['name'] ?? 'Non classé' }}
                </span>
            </div>
            @if($nextRank ?? false)
            <p class="small text-muted mb-2">
                <i class="bi bi-target"></i> 
                Prochain: <strong>{{ $nextRank['name'] ?? '' }}</strong>
                @if(($nextRank['bonus'] ?? 0) > 0)
                    <span class="badge bg-success-subtle text-success ms-1">+{{ number_format($nextRank['bonus'], 0, ',', ' ') }} FCFA</span>
                @endif
            </p>
            @php
                $remainingDirect = $nextRank['remaining_referrals'] ?? max(0, ($nextRank['min'] ?? 0) - ($activeDirectReferrals ?? 0));
                $remainingTeam = $nextRank['remaining_team'] ?? 0;
            @endphp
            <small class="text-warning d-block">
                @if($remainingDirect > 0)
                    {{ $remainingDirect }} filleuls directs restants
                @endif
                @if($remainingTeam > 0)
                    <br>{{ $remainingTeam }} membres d'équipe restants
                @endif
            </small>
            <small class="text-muted d-block mt-1">
                ({{ $activeDirectReferrals ?? 0 }} directs + {{ $activeLevel2Referrals ?? 0 }} niveau 2 = {{ $totalTeamSize ?? 0 }} total)
            </small>
            @else
            <p class="small text-success mb-0">
                <i class="bi bi-star-fill me-1"></i>
                <strong>Rang maximum atteint!</strong>
            </p>
            @endif
        </div>
    </div>
</div>

<!-- Main Content Row -->
<div class="row g-4 mb-4">
    <!-- Shop Sharing Card -->
    <div class="col-lg-6">
        <div class="card modern shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-gradient-primary text-white rounded-top-3 border-0">
                <h5 class="mb-0">
                    <i class="bi bi-shop me-2"></i>Ma Boutique Personnalisée
                </h5>
            </div>
            <div class="card-body">
                <p class="text-muted small mb-3">
                    🔗 Partagez ce lien unique pour gagner des commissions sur chaque vente!
                </p>
                
                <!-- Shop URL Copy -->
                <div class="mb-3">
                    <label class="form-label small fw-600">Lien de ma boutique</label>
                    <div class="input-group rounded-2 overflow-hidden">
                        <span class="input-group-text bg-light border-0">
                            <i class="bi bi-link-45deg"></i>
                        </span>
                        <input 
                            type="text" 
                            class="form-control border-0 bg-light" 
                            value="{{ $shopUrl ?? url('shop/' . ($user->username ?? $user->id)) }}" 
                            readonly 
                            id="shopUrlInput1"
                        >
                        <button 
                            class="btn btn-primary border-0" 
                            onclick="copyShopUrl('shopUrlInput1')"
                            title="Copier le lien"
                        >
                            <i class="bi bi-clipboard"></i>
                        </button>
                    </div>
                </div>

                <!-- Member Code Copy -->
                <div class="mb-4">
                    <label class="form-label small fw-600">Mon code parrain</label>
                    <div class="input-group rounded-2 overflow-hidden">
                        <span class="input-group-text bg-light border-0">
                            <i class="bi bi-hash"></i>
                        </span>
                        <input 
                            type="text" 
                            class="form-control border-0 bg-light text-center fw-bold" 
                            value="{{ $user->member_code ?? $user->id }}" 
                            readonly 
                            id="memberCodeInput"
                        >
                        <button 
                            class="btn btn-outline-primary border-0" 
                            onclick="copyShopUrl('memberCodeInput')"
                            title="Copier le code"
                        >
                            <i class="bi bi-clipboard"></i>
                        </button>
                    </div>
                </div>

                <!-- Social Share Buttons -->
                <div class="row g-2">
                    <div class="col">
                        <a 
                            href="https://wa.me/?text={{ urlencode((config('app.name') ?? 'Découvrez') . ' ' . ($shopUrl ?? url('shop'))) }}" 
                            target="_blank" 
                            rel="noopener" 
                            class="btn btn-success w-100 rounded-2"
                            title="Partager sur WhatsApp"
                        >
                            <i class="bi bi-whatsapp"></i>
                            <span class="d-none d-sm-inline ms-1">WhatsApp</span>
                        </a>
                    </div>
                    <div class="col">
                        <a 
                            href="https://www.facebook.com/sharer/sharer.php?u={{ urlencode($shopUrl ?? url('shop')) }}" 
                            target="_blank" 
                            rel="noopener" 
                            class="btn btn-primary w-100 rounded-2"
                            title="Partager sur Facebook"
                        >
                            <i class="bi bi-facebook"></i>
                            <span class="d-none d-sm-inline ms-1">Facebook</span>
                        </a>
                    </div>
                    <div class="col">
                        <a 
                            href="https://t.me/share/url?url={{ urlencode($shopUrl ?? url('shop')) }}&text=Découvrez%20ma%20boutique!" 
                            target="_blank" 
                            rel="noopener" 
                            class="btn btn-info w-100 rounded-2"
                            title="Partager sur Telegram"
                        >
                            <i class="bi bi-telegram"></i>
                            <span class="d-none d-sm-inline ms-1">Telegram</span>
                        </a>
                    </div>
                </div>

                <hr class="my-3">
                <small class="text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    💎 Commission: <strong>{{ \App\Models\Setting::where('key', 'shop_commission_percentage')->value('value') ?? '15' }}%</strong> 
                    sur chaque vente générée par votre lien
                </small>
            </div>
        </div>
    </div>

    <!-- AMM Progress Card -->
    <div class="col-lg-6">
        <div class="card modern shadow-sm border-0 rounded-3 h-100">
            <div class="card-header bg-gradient-warning text-dark rounded-top-3 border-0">
                <h5 class="mb-0">
                    <i class="bi bi-cart-check me-2"></i>Achat Mensuel Minimum (AMM)
                    @if($ammExempted ?? false)
                        <span class="badge bg-success ms-2">Exonéré</span>
                    @endif
                </h5>
            </div>
            <div class="card-body">
                @if($ammExempted ?? false)
                    <div class="alert alert-success border-0 rounded-2 mb-3 py-2">
                        <i class="bi bi-gift me-2"></i>
                        <strong>🎉 Félicitations !</strong> Vous êtes exonéré de l'AMM.
                        <div class="mt-1 p-2 bg-white bg-opacity-25 rounded">
                            <i class="bi bi-shield-check me-1 text-success"></i>
                            <span class="text-dark">Vous pouvez recevoir des commissions jusqu'au <strong class="text-success">{{ \Carbon\Carbon::parse(auth()->user()->amm_exemption_until)->translatedFormat('d F Y') }}</strong></span>
                        </div>
                    </div>
                @else
                    <p class="text-muted small mb-3">
                        ✅ Complétez votre AMM chaque mois pour activer vos commissions
                    </p>
                @endif

                <!-- Progress Stats -->
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-600">Progression ce mois</span>
                        <strong class="text-primary">
                            {{ number_format($monthlyPurchases ?? 0, 0, ',', ' ') }} / 
                            {{ number_format($ammRequired ?? 50000, 0, ',', ' ') }} XOF
                        </strong>
                    </div>
                    <div class="progress rounded-pill" style="height: 28px; background-color: #f0f0f0;">
                        <div 
                            class="progress-bar {{ ($ammProgress ?? 0) >= 100 ? 'bg-success' : 'bg-warning' }} rounded-pill fw-bold d-flex align-items-center justify-content-center text-white" 
                            style="width: {{ min(100, $ammProgress ?? 0) }}%"
                        >
                            @if(($ammProgress ?? 0) > 5)
                                {{ number_format(min(100, $ammProgress ?? 0), 0) }}%
                            @endif
                        </div>
                    </div>
                </div>

                <!-- Détail des sources AMM -->
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <div class="bg-light rounded-2 p-2 text-center">
                            <small class="text-muted d-block">Achats personnels</small>
                            <strong class="text-primary">{{ number_format($ammPersonalPurchases ?? 0, 0, ',', ' ') }} XOF</strong>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="bg-light rounded-2 p-2 text-center">
                            <small class="text-muted d-block">Ventes boutique</small>
                            <strong class="text-success">{{ number_format($ammShopSales ?? 0, 0, ',', ' ') }} XOF</strong>
                        </div>
                    </div>
                </div>

                <!-- Status Alert -->
                @if($ammCompleted ?? false)
                    <div class="alert alert-success border-0 rounded-2 mb-3 py-2">
                        <i class="bi bi-check-circle me-2"></i>
                        <strong>✨ AMM complétée!</strong> Vos commissions sont <strong>ACTIVES</strong>.
                        @if($ammActiveUntil ?? false)
                            <div class="mt-1 p-2 bg-white bg-opacity-25 rounded">
                                <i class="bi bi-calendar-event me-1 text-success"></i>
                                <span class="text-dark">Vous pouvez recevoir des commissions jusqu'au <strong class="text-success">{{ $ammActiveUntil }}</strong></span>
                            </div>
                        @endif
                    </div>
                @elseif(!($ammExempted ?? false))
                    <div class="alert alert-warning border-0 rounded-2 mb-3 py-2">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        <strong>Attention:</strong> Il vous reste 
                        <span class="fw-bold text-danger">
                            {{ number_format(max(0, ($ammRequired ?? 50000) - ($monthlyPurchases ?? 0)), 0, ',', ' ') }} XOF
                        </span> 
                        à acheter pour activer vos commissions.
                        @if(($ammDaysRemaining ?? 0) > 0)
                            <br><small class="text-muted">{{ $ammDaysRemaining }} jours restants ce mois.</small>
                        @endif
                    </div>
                @endif

                <!-- AMM mois suivant payé en avance -->
                @if($ammNextMonthPaid ?? false)
                    <div class="alert alert-info border-0 rounded-2 mb-3 py-2">
                        <i class="bi bi-calendar-check me-2"></i>
                        <strong>🚀 Super !</strong> Votre AMM du mois prochain est déjà validée !
                        @if($ammAdvancePaidUntil ?? false)
                            <div class="mt-1 p-2 bg-white bg-opacity-25 rounded">
                                <i class="bi bi-shield-check me-1 text-primary"></i>
                                <span class="text-dark">Vous pouvez recevoir des commissions jusqu'au <strong class="text-primary">{{ $ammAdvancePaidUntil }}</strong></span>
                            </div>
                        @endif
                    </div>
                @endif

                <!-- CTA Buttons -->
                <div class="d-flex gap-2">
                    <a 
                        href="{{ route('member.products') }}" 
                        class="btn btn-primary flex-fill rounded-2 fw-600"
                    >
                        <i class="bi bi-bag-plus me-2"></i>
                        {{ ($ammCompleted ?? false) ? 'Acheter plus' : 'Faire un achat maintenant' }}
                    </a>
                    
                    {{-- Bouton avance: visible uniquement si achats personnels >= AMM requis --}}
                    @if(!($ammNextMonthPaid ?? false) && ($ammCanPayAdvance ?? false))
                        <button 
                            type="button" 
                            class="btn btn-outline-success rounded-2"
                            onclick="openAdvanceAmmModal()"
                            title="Payer l'AMM du mois prochain en avance"
                        >
                            <i class="bi bi-calendar-plus"></i>
                        </button>
                    @endif
                </div>
                
                {{-- Message explicatif si AMM complétée via ventes boutique mais pas assez d'achats perso pour avance --}}
                @if(($ammCompleted ?? false) && !($ammCanPayAdvance ?? false) && !($ammNextMonthPaid ?? false))
                    <small class="text-info d-block mt-2">
                        <i class="bi bi-info-circle me-1"></i>
                        Pour payer l'AMM du mois prochain en avance, vos achats personnels doivent atteindre {{ number_format($ammRequired ?? 50000, 0, ',', ' ') }} XOF.
                    </small>
                @endif
                
                <small class="text-muted d-block mt-2 text-center">
                    <i class="bi bi-info-circle me-1"></i>
                    L'AMM se réinitialise le 1er de chaque mois à 00h00
                </small>
            </div>
        </div>
    </div>
</div>

<!-- Modal pour AMM en avance -->
<div class="modal fade" id="advanceAmmModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-3">
            <div class="modal-header bg-success text-white rounded-top-3">
                <h5 class="modal-title"><i class="bi bi-calendar-plus me-2"></i>Payer l'AMM en avance</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Vous souhaitez valider votre AMM du <strong>mois prochain</strong> en avance ?</p>
                <p class="text-muted small">
                    En payant maintenant, vos commissions resteront actives même si vous n'atteignez pas le seuil AMM le mois prochain.
                </p>
                <div class="alert alert-info">
                    <strong>Montant requis :</strong> {{ number_format($ammRequired ?? 50000, 0, ',', ' ') }} XOF
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
                <a href="{{ route('member.products') }}?amm_advance=1" class="btn btn-success">
                    <i class="bi bi-cart-plus me-2"></i>Faire un achat pour le mois prochain
                </a>
            </div>
        </div>
    </div>
</div>

<!-- Commissions Table & Network Sidebar -->
<div class="row g-4">
    <!-- Recent Commissions Table -->
    <div class="col-lg-8">
        <div class="card modern shadow-sm border-0 rounded-3">
            <div class="card-header bg-white border-bottom d-flex justify-content-between align-items-center rounded-top-3">
                <h5 class="mb-0">
                    <i class="bi bi-clock-history me-2"></i>Commissions Récentes (Top 5)
                </h5>
                <a href="{{ route('member.commissions') }}" class="btn btn-sm btn-outline-primary rounded-2">
                    <i class="bi bi-list me-1"></i>Voir tout
                </a>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-modern mb-0">
                        <thead class="table-light">
                            <tr class="border-bottom">
                                <th class="fw-600 small text-muted">Type</th>
                                <th class="fw-600 small text-muted">Niveau</th>
                                <th class="fw-600 small text-muted">Montant</th>
                                <th class="fw-600 small text-muted">Statut</th>
                                <th class="fw-600 small text-muted text-end">Date</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($recentCommissions ?? [] as $commission)
                            <tr class="border-bottom-light hover-highlight">
                                <td>
                                    <span class="badge bg-opacity-10 fw-600 {{ $commission->type == 'sale' ? 'bg-info text-info' : 'bg-success text-success' }} rounded-pill">
                                        {{ $commission->type == 'sale' ? 'Vente' : 'Bonus' }}
                                    </span>
                                </td>
                                <td class="small">
                                    {{ $commission->level ? '📊 Niveau ' . $commission->level : '—' }}
                                </td>
                                <td>
                                    <strong class="text-success fs-6">
                                        +{{ number_format($commission->amount ?? 0, 0, ',', ' ') }}
                                    </strong>
                                </td>
                                <td>
                                    @php
                                        $statusBadges = [
                                            'paid' => ['success', '✓ Payée'],
                                            'approved' => ['info', '⏳ Approuvée'],
                                            'pending' => ['warning', '⌛ En attente'],
                                            'rejected' => ['danger', '✗ Rejetée']
                                        ];
                                        $status = $statusBadges[$commission->status] ?? ['secondary', ucfirst($commission->status)];
                                    @endphp
                                    <span class="badge bg-{{ $status[0] }} rounded-pill">{{ $status[1] }}</span>
                                </td>
                                <td class="text-end text-muted small">
                                    {{ $commission->created_at?->format('d/m/Y') ?? '—' }}
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="5" class="text-center text-muted py-5">
                                    <div>
                                        <i class="bi bi-inbox fs-2 d-block mb-2 opacity-50"></i>
                                        <p class="small">Aucune commission pour le moment</p>
                                        <small class="text-muted">Commencez à vendre ou parrainer pour gagner des commissions</small>
                                    </div>
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                @if(($recentCommissions ?? collect())->count() > 0)
                <div class="card-footer bg-light border-top py-2">
                    <small class="text-muted">Affichage: {{ count($recentCommissions ?? []) }} de {{ $totalCommissionCount ?? 'N/A' }} commissions</small>
                </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Sidebar: Network + Ranks -->
    <div class="col-lg-4">
        <!-- Network Summary Card -->
        <div class="card modern shadow-sm border-0 rounded-3 mb-4">
            <div class="card-header bg-white border-bottom rounded-top-3">
                <h5 class="mb-0">
                    <i class="bi bi-diagram-3 me-2"></i>Mon Réseau MLM
                </h5>
            </div>
            <div class="card-body">
                <!-- Level 1 -->
                <div class="mb-3 pb-3 border-bottom-light">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-600">
                            <i class="bi bi-person-fill text-primary me-2"></i>Niveau 1 (Directs)
                        </span>
                        <strong class="text-primary fs-5">{{ $directReferrals ?? 0 }}</strong>
                    </div>
                    <small class="text-success d-block mb-2">
                        <i class="bi bi-check-circle me-1"></i>{{ $activeDirectReferrals ?? 0 }} actifs
                    </small>
                    <div class="progress rounded-pill" style="height: 6px;">
                        <div 
                            class="progress-bar bg-primary" 
                            style="width: {{ min(100, (($directReferrals ?? 0) * 5)) }}%"
                        ></div>
                    </div>
                </div>

                <!-- Level 2 -->
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-600">
                            <i class="bi bi-people-fill text-info me-2"></i>Niveau 2 (Indirects)
                        </span>
                        <strong class="text-info fs-5">{{ $level2Referrals ?? 0 }}</strong>
                    </div>
                    <div class="progress rounded-pill" style="height: 6px;">
                        <div 
                            class="progress-bar bg-info" 
                            style="width: {{ min(100, (($level2Referrals ?? 0) * 2)) }}%"
                        ></div>
                    </div>
                </div>

                <!-- Action Button -->
                <a href="{{ route('member.network') }}" class="btn btn-outline-primary w-100 rounded-2 mt-3">
                    <i class="bi bi-diagram-3 me-1"></i> Voir mon réseau complet
                </a>
            </div>
        </div>

        <!-- Ranks & Bonuses Card -->
        <div class="card modern shadow-sm border-0 rounded-3">
            <div class="card-header bg-white border-bottom rounded-top-3">
                <h5 class="mb-0">
                    <i class="bi bi-trophy me-2"></i>Primes de Rang
                </h5>
            </div>
            <div class="card-body p-0">
                <ul class="list-group list-group-flush">
                    @php
                        // Icônes par défaut selon le niveau
                        $defaultIcons = ['🥉', '🥈', '🥇', '💎', '👑', '🏆'];
                        // Couleurs Bootstrap par défaut
                        $defaultColors = ['warning', 'secondary', 'danger', 'info', 'dark', 'primary'];
                    @endphp
                    @forelse($allRanks as $index => $rank)
                    @php
                        $rankIcon = $rank->badge_icon ?? ($defaultIcons[$index] ?? '🏅');
                        $rankColorClass = $defaultColors[$index] ?? 'secondary';
                    @endphp
                    <li class="list-group-item d-flex justify-content-between align-items-center {{ ($currentRank['name'] ?? '') === $rank->name ? 'bg-light border-start border-primary border-4' : '' }} py-2">
                        <div class="small">
                            <span class="badge me-2" style="background-color: {{ $rank->badge_color ?? '#6c757d' }}">{{ $rankIcon }}</span>
                            <strong>{{ $rank->name }}</strong>
                            <span class="text-muted ms-1">({{ $rank->min_direct_referrals }}+)</span>
                        </div>
                        <small class="text-muted fw-600">
                            +{{ number_format($rank->bonus_amount, 0, ',', ' ') }} XOF
                        </small>
                    </li>
                    @empty
                    <li class="list-group-item text-center text-muted py-3">
                        <i class="bi bi-info-circle me-1"></i>Aucun rang configuré
                    </li>
                    @endforelse
                </ul>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
/**
 * Show toast notification
 * @param {string} message - Notification message
 * @param {string} type - Type of toast (success, info, warning, danger)
 */
function showToast(message, type = 'success') {
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type} border-0 rounded-3`;
    toast.setAttribute('role', 'alert');
    toast.setAttribute('aria-live', 'assertive');
    toast.setAttribute('aria-atomic', 'true');
    
    const icons = {
        'success': 'bi-check-circle',
        'info': 'bi-info-circle',
        'warning': 'bi-exclamation-triangle',
        'danger': 'bi-x-circle'
    };
    
    toast.innerHTML = `
        <div class="d-flex w-100">
            <div class="toast-body d-flex align-items-center">
                <i class="bi ${icons[type] || 'bi-check'} me-2 fs-5"></i>
                <span>${message}</span>
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast, { delay: 3000 });
    bsToast.show();
    
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

/**
 * Create toast container if it doesn't exist
 * @returns {HTMLElement} Toast container
 */
function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
    return container;
}

/**
 * Copy shop URL or code to clipboard
 * @param {string} elementId - ID of the input element to copy
 */
function copyShopUrl(elementId) {
    const input = document.getElementById(elementId);
    
    if (!input) {
        console.error(`Element with ID "${elementId}" not found`);
        showToast('Erreur: Élément introuvable', 'danger');
        return;
    }
    
    // Copy using Clipboard API (modern way)
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(input.value)
            .then(() => {
                const type = elementId.includes('Code') ? 'Code parrain' : 'Lien de boutique';
                showToast(`${type} copié avec succès! 📋`, 'success');
            })
            .catch(err => {
                console.error('Erreur de copie:', err);
                fallbackCopy(input);
            });
    } else {
        // Fallback for older browsers
        fallbackCopy(input);
    }
}

/**
 * Fallback copy method for older browsers
 * @param {HTMLElement} input - Input element to copy
 */
function fallbackCopy(input) {
    try {
        input.select();
        input.setSelectionRange(0, 99999); // For mobile
        document.execCommand('copy');
        showToast('Texte copié! 📋', 'info');
    } catch (err) {
        console.error('Erreur de copie fallback:', err);
        showToast('Erreur lors de la copie', 'danger');
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Example: You can add more initialization code here
    console.log('Dashboard loaded successfully');
});
</script>

<style>
    .stat-card {
        transition: all 0.3s ease;
        background: #fff;
        padding: 1.5rem;
    }
    
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1) !important;
    }
    
    .stat-icon {
        width: 50px;
        height: 50px;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }
    
    .bg-success-light {
        background-color: rgba(40, 167, 69, 0.1);
    }
    
    .bg-primary-light {
        background-color: rgba(0, 123, 255, 0.1);
    }
    
    .bg-info-light {
        background-color: rgba(23, 162, 184, 0.1);
    }
    
    .bg-gradient-primary {
        background: linear-gradient(135deg, #0d6efd 0%, #0054ca 100%) !important;
    }
    
    .bg-gradient-warning {
        background: linear-gradient(135deg, #ffc107 0%, #e0a800 100%) !important;
    }
    
    .card.modern {
        border: 1px solid #f0f0f0;
        transition: all 0.3s ease;
    }
    
    .card.modern:hover {
        border-color: #e0e0e0;
    }
    
    .table-modern tbody tr {
        transition: background-color 0.2s ease;
    }
    
    .table-modern tbody tr:hover {
        background-color: #f8f9fa !important;
    }
    
    .border-bottom-light {
        border-bottom: 1px solid #f0f0f0 !important;
    }
    
    .rounded-2 {
        border-radius: 0.5rem;
    }
    
    .rounded-3 {
        border-radius: 1rem;
    }
    
    .fw-600 {
        font-weight: 600;
    }
    
    .fw-700 {
        font-weight: 700;
    }
    
    .opacity-50 {
        opacity: 0.5;
    }
    
    .hover-highlight:hover {
        background-color: #f8f9fa;
    }

    @media (max-width: 768px) {
        .stat-card {
            padding: 1rem;
        }
        
        .stat-icon {
            width: 40px;
            height: 40px;
        }
        
        h3 {
            font-size: 1.5rem;
        }
    }
</style>
@endpush
@push('scripts')
<script>
    const subscriptionAmount = {{ $subscriptionAmount }};

    function openSubscriptionPayment() {
        const section = document.getElementById('subscriptionPaymentSection');
        if (section) {
            section.style.display = 'block';
            if (typeof togglePaymentFields === 'function') {
                togglePaymentFields();
            }
        }
    }

    function resetSubscriptionButton() {
        const payBtn = document.getElementById('subscriptionPayAction');
        if (payBtn) {
            payBtn.disabled = false;
            payBtn.innerHTML = '<i class="bi bi-lock-fill me-1"></i>Valider et payer';
        }
    }

    async function submitSubscriptionPayment() {
        const payBtn = document.getElementById('subscriptionPayAction');
        if (payBtn) {
            payBtn.disabled = true;
            payBtn.innerHTML = '<i class="bi bi-arrow-repeat me-1"></i>Traitement...';
        }

        const methodInput = document.querySelector('#subscriptionPaymentSection input[name="payment_method"]:checked');
        const paymentMethod = methodInput ? methodInput.value : 'card';

        // Paiement via Wallet
        if (paymentMethod === 'wallet') {
            try {
                const response = await fetch("{{ route('wallet.pay.subscription') }}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({})
                });

                const data = await response.json();

                if (!data.success) {
                    throw new Error(data.message || 'Erreur lors du paiement');
                }

                alert(data.message || 'Abonnement activé avec succès !');
                if (data.redirect_url) {
                    window.location.href = data.redirect_url;
                } else {
                    window.location.reload();
                }
            } catch (error) {
                console.error('Wallet subscription error', error);
                alert('Erreur: ' + error.message);
                resetSubscriptionButton();
            }
            return;
        }

        // Paiement par carte
        if (paymentMethod !== 'mobile_money') {
            document.getElementById('subscriptionCardForm')?.submit();
            return;
        }

        // Paiement Mobile Money
        const mmCountry = document.getElementById('mm_country')?.value;
        const mmNetwork = document.getElementById('mm_network')?.value;
        const mmPhone = document.getElementById('mm_phone')?.value;
        const mmAuthCode = document.getElementById('mm_authorization_code')?.value;

        if (!mmCountry || !mmNetwork || !mmPhone) {
            alert('Veuillez renseigner le pays, le réseau et le numéro Mobile Money.');
            resetSubscriptionButton();
            return;
        }

        const txRef = 'SUB-MM-' + Date.now();
        const payload = {
            tx_ref: txRef,
            amount: subscriptionAmount,
            country: mmCountry,
            network: mmNetwork,
            phone_number: mmPhone,
            email: '{{ auth()->user()->email ?? '' }}',
            fullname: '{{ auth()->user()->name ?? '' }}',
            payment_type: 'plan',
            redirect_url: "{{ route('payment.mobile-money.callback') }}"
        };

        if (mmAuthCode) {
            payload.authorization_code = mmAuthCode;
        }

        try {
            const response = await fetch("{{ route('payment.mobile-money.initiate') }}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                },
                body: JSON.stringify(payload)
            });

            const data = await response.json();

            if (!data.success) {
                throw new Error(data.message || 'Erreur lors de l\'initiation du paiement');
            }

            const mmData = data.data || {};

            if (mmData.redirect_url) {
                window.location.href = mmData.redirect_url;
                return;
            }

            if (mmData.qr_code) {
                displaySubscriptionQr(mmData.qr_code, mmData.redirect_url || null);
                return;
            }

            window.location.href = "{{ route('payment.mobile-money.callback') }}?tx_ref=" + (mmData.tx_ref || txRef);
        } catch (error) {
            console.error('Mobile money subscription error', error);
            alert('Erreur: ' + error.message);
            resetSubscriptionButton();
        }
    }

    function displaySubscriptionQr(qrCodeBase64, redirectUrl) {
        const modal = document.createElement('div');
        modal.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);display:flex;align-items:center;justify-content:center;z-index:9999;';
        modal.innerHTML = `
            <div style="background:white;padding:30px;border-radius:12px;text-align:center;max-width:460px;width:90%;box-shadow:0 10px 40px rgba(0,0,0,0.3);">
                <h4 style="margin-bottom:10px;">Scannez pour payer</h4>
                <p style="color:#666;margin-bottom:20px;">Ouvrez votre application Mobile Money pour confirmer</p>
                <img src="${qrCodeBase64}" alt="QR Code" style="max-width:260px;margin:10px auto;display:block;border:2px solid #0d6efd;border-radius:8px;">
                <div style="margin-top:15px;display:flex;justify-content:center;gap:10px;flex-wrap:wrap;">
                    ${redirectUrl ? `<a href="${redirectUrl}" target="_blank" style="padding:10px 18px;background:#0d6efd;color:white;text-decoration:none;border-radius:6px;">Ouvrir l'application</a>` : ''}
                    <button onclick="this.closest('div[style*=\'position:fixed\']').remove();resetSubscriptionButton();" style="padding:10px 18px;background:#6c757d;color:white;border:none;border-radius:6px;cursor:pointer;">Fermer</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
    }

    /**
     * Open advance AMM modal
     */
    function openAdvanceAmmModal() {
        const modal = new bootstrap.Modal(document.getElementById('advanceAmmModal'));
        modal.show();
    }
</script>
@endpush
@endsection

