@extends('layouts.member')

@section('title', 'Épargne')

@push('styles')
<style>
    /* Ultra Modern Glassmorphism Design */
    body {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
        min-height: 100vh;
        font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    }

    .glass-card {
        background: rgba(255, 255, 255, 0.1);
        backdrop-filter: blur(20px);
        -webkit-backdrop-filter: blur(20px);
        border-radius: 24px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .glass-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 12px 48px rgba(0, 0, 0, 0.15);
        border-color: rgba(255, 255, 255, 0.3);
    }

    .wallet-main {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        position: relative;
        overflow: hidden;
    }

    .wallet-main::before {
        content: '';
        position: absolute;
        top: -50%;
        right: -10%;
        width: 300px;
        height: 300px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
    }

    .wallet-savings {
        background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
        position: relative;
        overflow: hidden;
    }

    .wallet-savings::before {
        content: '';
        position: absolute;
        bottom: -50%;
        left: -10%;
        width: 300px;
        height: 300px;
        background: rgba(255, 255, 255, 0.1);
        border-radius: 50%;
    }

    .wallet-locked {
        background: linear-gradient(135deg, #f59e0b 0%, #ef4444 100%);
    }

    .btn-glass {
        background: rgba(255, 255, 255, 0.15);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255, 255, 255, 0.3);
        color: white;
        padding: 12px 32px;
        border-radius: 16px;
        font-weight: 600;
        transition: all 0.3s;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .btn-glass:hover {
        background: rgba(255, 255, 255, 0.25);
        transform: translateY(-2px);
        color: white;
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
    }

    .plan-card {
        background: rgba(255, 255, 255, 0.08);
        border: 2px solid rgba(255, 255, 255, 0.15);
        border-radius: 20px;
        padding: 28px;
        text-align: center;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
        overflow: hidden;
        cursor: pointer;
    }

    .plan-card::before {
        content: '';
        position: absolute;
        inset: 0;
        background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, transparent 100%);
        opacity: 0;
        transition: opacity 0.4s;
    }

    .plan-card:hover {
        transform: scale(1.05) translateY(-8px);
        border-color: rgba(255, 255, 255, 0.4);
        box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
    }

    .plan-card:hover::before {
        opacity: 1;
    }

    .plan-card.selected {
        border-color: #06b6d4;
        box-shadow: 0 0 40px rgba(6, 182, 212, 0.5);
        transform: scale(1.05);
    }

    .plan-icon {
        font-size: 48px;
        margin-bottom: 16px;
        animation: float 3s ease-in-out infinite;
    }

    @keyframes float {
        0%, 100% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
    }

    .progress-ring {
        transform: rotate(-90deg);
    }

    .progress-ring-circle {
        transition: stroke-dashoffset 0.5s ease;
    }

    .stat-card {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 16px;
        padding: 20px;
        border: 1px solid rgba(255, 255, 255, 0.1);
    }

    .transfer-btn {
        position: relative;
        overflow: hidden;
    }

    .transfer-btn::after {
        content: '';
        position: absolute;
        inset: 0;
        background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
        transform: translateX(-100%);
    }

    .transfer-btn:hover::after {
        animation: shimmer 1s;
    }

    @keyframes shimmer {
        to { transform: translateX(100%); }
    }

    .badge-glass {
        background: rgba(255, 255, 255, 0.2);
        backdrop-filter: blur(10px);
        padding: 8px 16px;
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.3);
        font-weight: 600;
    }

    .unlock-countdown {
        font-size: 28px;
        font-weight: 700;
        font-variant-numeric: tabular-nums;
        text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    }

    .modal-glass {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(20px);
        border-radius: 24px;
        border: 1px solid rgba(255, 255, 255, 0.5);
    }

    .form-control-glass {
        background: rgba(0, 0, 0, 0.3);
        border: 2px solid rgba(255, 255, 255, 0.3);
        border-radius: 12px;
        color: white;
        padding: 14px 20px;
        font-weight: 500;
    }

    .form-control-glass:focus {
        background: rgba(0, 0, 0, 0.4);
        border-color: #06b6d4;
        color: white;
        box-shadow: 0 0 0 4px rgba(6, 182, 212, 0.2);
    }

    .form-control-glass::placeholder {
        color: rgba(255, 255, 255, 0.7);
    }

    .form-control-glass option {
        background: #1f2937;
        color: white;
    }

    .history-item {
        background: rgba(255, 255, 255, 0.05);
        border-radius: 16px;
        padding: 20px;
        margin-bottom: 12px;
        border: 1px solid rgba(255, 255, 255, 0.1);
        transition: all 0.3s;
    }

    .history-item:hover {
        background: rgba(255, 255, 255, 0.1);
        transform: translateX(8px);
    }

    .text-white { color: white !important; }
    .text-white-70 { color: rgba(255, 255, 255, 0.7) !important; }
</style>
@endpush

@section('content')
<div class="container-fluid py-5">
    <!-- Header -->
    <div class="row mb-5">
        <div class="col-12">
            <div class="glass-card p-4 text-white">
                <h1 class="mb-0 fw-bold" style="font-size: 42px;">💰 Wallet d'Épargne</h1>
                <p class="text-white-70 mb-0 mt-2">Faites fructifier votre argent avec nos plans d'épargne sécurisés</p>
            </div>
        </div>
    </div>

    <!-- Wallets Display -->
    <div class="row g-4 mb-5">
        <!-- Main Wallet -->
        <div class="col-md-6">
            <div class="glass-card wallet-main p-5 text-white" style="min-height: 280px;">
                <div class="d-flex justify-content-between align-items-start mb-4">
                    <div>
                        <h5 class="fw-bold text-uppercase letter-spacing-1 mb-1 opacity-75">Wallet Principal</h5>
                        <p class="mb-0 opacity-50">Disponible immédiatement</p>
                    </div>
                    <span class="badge-glass">💳 ACTIF</span>
                </div>
                
                <div class="mb-4">
                    <div class="h1 fw-bold mb-0" style="font-size: 48px;">{{ number_format($wallet->balance, 0, ',', ' ') }}</div>
                    <div class="text-white-70 fw-semibold">XOF</div>
                </div>

                <button class="btn btn-glass w-100 transfer-btn" onclick="showTransferModal('to_savings')">
                    <i class="fas fa-arrow-right me-2"></i> Transférer vers Épargne
                </button>
            </div>
        </div>

        <!-- Savings Wallet -->
        <div class="col-md-6">
            <div class="glass-card {{ $savingsWallet->is_locked ? 'wallet-locked' : 'wallet-savings' }} p-5 text-white" style="min-height: 280px;">
                <div class="d-flex justify-content-between align-items-start mb-4">
                    <div>
                        <h5 class="fw-bold text-uppercase letter-spacing-1 mb-1 opacity-75">Wallet Épargne</h5>
                        <p class="mb-0 opacity-50">
                            @if($savingsWallet->is_locked)
                                🔒 Bloqué jusqu'au {{ \Carbon\Carbon::parse($savingsWallet->unlock_at)->format('d/m/Y') }}
                            @else
                                🔓 Débloqué
                            @endif
                        </p>
                    </div>
                    @if($savingsWallet->is_locked)
                        <span class="badge-glass">🔒 {{ $savingsWallet->lock_duration_months }} MOIS</span>
                    @else
                        <span class="badge-glass">✅ LIBRE</span>
                    @endif
                </div>
                
                <div class="mb-4">
                    <div class="h1 fw-bold mb-0" style="font-size: 48px;">{{ number_format($savingsWallet->balance, 0, ',', ' ') }}</div>
                    <div class="text-white-70 fw-semibold">XOF</div>
                </div>

                @if($savingsWallet->is_locked)
                    <div class="mb-3">
                        <div class="d-flex justify-content-between text-sm mb-2">
                            <span>Progression</span>
                            <span class="fw-bold">{{ number_format($savingsWallet->lockProgress(), 1) }}%</span>
                        </div>
                        <div class="progress" style="height: 8px; border-radius: 10px; background: rgba(255,255,255,0.2);">
                            <div class="progress-bar" style="background: linear-gradient(90deg, #06b6d4, #3b82f6); width: {{ $savingsWallet->lockProgress() }}%;"></div>
                        </div>
                        <div class="text-center mt-3">
                            <div class="unlock-countdown">⏱️ {{ $savingsWallet->daysUntilUnlock() }} jours restants</div>
                        </div>
                    </div>
                    <button class="btn btn-glass w-100 mb-2" onclick="showUnlockRequestModal()" style="background: rgba(239, 68, 68, 0.3);">
                        <i class="fas fa-unlock me-2"></i> Demander Déblocage d'Urgence
                    </button>
                @else
                    <div class="row g-2">
                        <div class="col-6">
                            <button class="btn btn-glass w-100 transfer-btn" onclick="showTransferModal('from_savings')">
                                <i class="fas fa-arrow-left me-2"></i> Transférer
                            </button>
                        </div>
                        <div class="col-6">
                            <button class="btn btn-glass w-100" onclick="showLockModal()" style="background: rgba(245, 158, 11, 0.3);">
                                <i class="fas fa-lock me-2"></i> Bloquer
                            </button>
                        </div>
                    </div>
                @endif
            </div>
        </div>
    </div>

    <!-- Stats Row -->
    <div class="row g-4 mb-5">
        <div class="col-md-3">
            <div class="stat-card text-white text-center">
                <div class="h2 mb-0 fw-bold">💵 {{ number_format($savingsWallet->total_deposited, 0, ',', ' ') }}</div>
                <div class="text-white-70 mt-2">Total Déposé</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card text-white text-center">
                <div class="h2 mb-0 fw-bold">📈 {{ number_format($savingsWallet->total_interest_earned, 0, ',', ' ') }}</div>
                <div class="text-white-70 mt-2">Intérêts Gagnés</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card text-white text-center">
                <div class="h2 mb-0 fw-bold">💎 {{ $savingsWallet->interest_rate ?? 0 }}%</div>
                <div class="text-white-70 mt-2">Taux Actuel</div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card text-white text-center">
                <div class="h2 mb-0 fw-bold">{{ $transfers->count() }}</div>
                <div class="text-white-70 mt-2">Transferts</div>
            </div>
        </div>
    </div>

    <!-- Épargnes Bloquées Actives -->
    @if($activeLocks->count() > 0)
    <div class="row mb-5">
        <div class="col-12">
            <div class="glass-card p-5">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h3 class="text-white fw-bold mb-0">🔒 Vos Épargnes Bloquées ({{ $activeLocks->count() }})</h3>
                    <span class="badge bg-warning text-dark">Total: {{ number_format($totalLockedAmount, 0, ',', ' ') }} XOF</span>
                </div>

                <div class="row g-4">
                    @foreach($activeLocks as $lock)
                    <div class="col-md-6">
                        <div class="glass-card p-4 position-relative" style="border-left: 4px solid #f59e0b;">
                            <div class="d-flex justify-content-between align-items-start mb-3">
                                <div>
                                    <h5 class="text-white fw-bold mb-1">
                                        🔒 Blocage #{{ $lock->id }}
                                    </h5>
                                    <p class="text-white-70 small mb-0">
                                        Créé le {{ $lock->created_at->format('d/m/Y à H:i') }}
                                    </p>
                                </div>
                                <span class="badge bg-warning text-dark">ACTIF</span>
                            </div>

                            <div class="row mt-3 mb-3">
                                <div class="col-6">
                                    <div class="text-white-70 small">Montant bloqué</div>
                                    <div class="h5 text-white fw-bold mb-0">{{ number_format($lock->amount, 0, ',', ' ') }} XOF</div>
                                </div>
                                <div class="col-6">
                                    <div class="text-white-70 small">Taux annuel</div>
                                    <div class="h5 text-white fw-bold mb-0">{{ $lock->interest_rate }}%</div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-6">
                                    <div class="text-white-70 small">Durée</div>
                                    <div class="h6 text-white fw-bold mb-0">{{ $lock->lock_duration_months }} mois</div>
                                </div>
                                <div class="col-6">
                                    <div class="text-white-70 small">Jours restants</div>
                                    <div class="h6 text-white fw-bold mb-0">{{ $lock->daysUntilUnlock() }} jours</div>
                                </div>
                            </div>

                            <!-- Progress bar -->
                            <div class="mb-3">
                                <div class="progress" style="height: 8px; background: rgba(255,255,255,0.1);">
                                    @php
                                        $totalDays = $lock->locked_at->diffInDays($lock->unlock_at);
                                        $elapsedDays = $lock->locked_at->diffInDays(now());
                                        $progress = $totalDays > 0 ? min(100, ($elapsedDays / $totalDays) * 100) : 100;
                                    @endphp
                                    <div class="progress-bar bg-warning" role="progressbar" 
                                         style="width: {{ $progress }}%;" 
                                         aria-valuenow="{{ $progress }}" 
                                         aria-valuemin="0" 
                                         aria-valuemax="100"></div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-6">
                                    <div class="text-white-70 small">Intérêts accumulés</div>
                                    <div class="h6 text-success fw-bold mb-0">+ {{ number_format($lock->calculateAccumulatedInterest(), 0, ',', ' ') }} XOF</div>
                                </div>
                                <div class="col-6">
                                    <div class="text-white-70 small">Total à déblocage</div>
                                    <div class="h6 text-info fw-bold mb-0">{{ number_format($lock->getTotalAtUnlock(), 0, ',', ' ') }} XOF</div>
                                </div>
                            </div>

                            <div class="alert alert-info small mb-0" style="background: rgba(59, 130, 246, 0.1); border: 1px solid rgba(59, 130, 246, 0.3);">
                                <i class="fas fa-info-circle me-2"></i>
                                <strong>Déblocage automatique:</strong> {{ $lock->unlock_at->format('d/m/Y à H:i') }}
                            </div>

                            <div class="mt-3">
                                <button class="btn btn-sm btn-outline-danger w-100" 
                                        onclick="earlyUnlock({{ $lock->id }})">
                                    <i class="fas fa-unlock me-2"></i> Déblocage anticipé (perte intérêts)
                                </button>
                            </div>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- Plans d'Épargne -->
    <div class="row mb-5">
        <div class="col-12">
            <div class="glass-card p-5">
                <h3 class="text-white fw-bold mb-4">📊 Plans d'Épargne Disponibles</h3>
                
                <div class="row g-4">
                    @foreach($plans as $plan)
                    <div class="col-md-3">
                        <div class="plan-card text-white" onclick="selectPlan({{ $plan->id }}, {{ $plan->duration_months }}, {{ $plan->interest_rate }}, {{ $plan->min_amount }})" data-plan-id="{{ $plan->id }}">
                            <div class="plan-icon">{{ $plan->icon }}</div>
                            <h4 class="fw-bold mb-2">{{ $plan->name }}</h4>
                            <div class="h2 fw-bold mb-3" style="color: #06b6d4;">{{ $plan->interest_rate }}%</div>
                            <div class="mb-3">
                                <div class="badge badge-glass mb-2">⏱️ {{ $plan->duration_months }} mois</div>
                                <div class="text-white-70 small">Min. {{ number_format($plan->min_amount, 0, ',', ' ') }} XOF</div>
                            </div>
                            <p class="small text-white-70 mb-0">{{ $plan->description }}</p>
                        </div>
                    </div>
                    @endforeach
                </div>
            </div>
        </div>
    </div>

    <!-- Historique -->
    <div class="row">
        <div class="col-12">
            <div class="glass-card p-5">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h3 class="text-white fw-bold mb-0">📜 Historique des Transferts</h3>
                    <a href="{{ route('member.savings.transfers') }}" class="btn btn-glass btn-sm">Voir tout</a>
                </div>
                
                @forelse($transfers->take(10) as $transfer)
                <div class="history-item">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <div class="text-white" style="font-size: 32px;">{{ $transfer->icon }}</div>
                        </div>
                        <div class="col">
                            <div class="text-white fw-bold">{{ ucfirst(str_replace('_', ' ', $transfer->direction)) }}</div>
                            <div class="text-white-70 small">{{ $transfer->created_at->format('d/m/Y à H:i') }}</div>
                        </div>
                        <div class="col-auto text-end">
                            <div class="text-white fw-bold h5 mb-0">{{ number_format($transfer->amount, 0, ',', ' ') }} XOF</div>
                            <div class="small">
                                @if($transfer->status === 'completed')
                                    <span class="badge bg-success">✅ Complété</span>
                                @elseif($transfer->status === 'pending')
                                    <span class="badge bg-warning">⏳ En cours</span>
                                @else
                                    <span class="badge bg-danger">❌ Échoué</span>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
                @empty
                <div class="text-center text-white-70 py-5">
                    <div style="font-size: 64px; opacity: 0.3;">📭</div>
                    <p class="mt-3">Aucun transfert pour le moment</p>
                </div>
                @endforelse
            </div>
        </div>
    </div>

    @if($unlockRequests->count() > 0)
    <!-- Demandes de Déblocage -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="glass-card p-5">
                <h3 class="text-white fw-bold mb-4">🔓 Demandes de Déblocage</h3>
                
                @foreach($unlockRequests as $request)
                <div class="history-item">
                    <div class="row align-items-center">
                        <div class="col">
                            <div class="text-white fw-bold">Montant: {{ number_format($request->amount_requested, 0, ',', ' ') }} XOF</div>
                            <div class="text-white-70 small">{{ $request->created_at->format('d/m/Y à H:i') }}</div>
                            <div class="text-white-70 small mt-1"><em>{{ $request->reason }}</em></div>
                        </div>
                        <div class="col-auto">
                            {!! $request->statusBadge !!}
                            @if($request->penalty_fee > 0)
                                <div class="small text-white-70 mt-1">Pénalité: {{ number_format($request->penalty_fee, 0, ',', ' ') }} XOF</div>
                            @endif
                        </div>
                    </div>
                </div>
                @endforeach
            </div>
        </div>
    </div>
    @endif
</div>

<!-- Modal: Transfer -->
<div class="modal fade" id="transferModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-glass" style="background: linear-gradient(135deg, rgba(102, 126, 234, 0.95), rgba(118, 75, 162, 0.95)); backdrop-filter: blur(20px);">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white fw-bold" id="transferModalTitle"></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form action="#" id="transferForm">
                    <input type="hidden" id="transferDirection" name="direction">
                    <input type="hidden" id="selectedPlanDuration" name="lock_duration">
                    
                    <div class="mb-4">
                        <label class="form-label text-white fw-semibold">Montant (XOF)</label>
                        <input type="number" class="form-control form-control-glass" id="transferAmount" name="amount" min="1000" step="100" required>
                        <small class="text-white-70" id="minAmountText"></small>
                    </div>

                    <div id="planSelectionInfo" style="display: none;">
                        <div class="alert alert-info text-dark">
                            <strong>Plan sélectionné:</strong>
                            <div id="selectedPlanInfo"></div>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-glass w-100" id="transferSubmitBtn">
                        <i class="fas fa-paper-plane me-2"></i> Effectuer le Transfert
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal: Unlock Request -->
<div class="modal fade" id="unlockRequestModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-glass" style="background: linear-gradient(135deg, rgba(239, 68, 68, 0.95), rgba(245, 158, 11, 0.95)); backdrop-filter: blur(20px);">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white fw-bold">🚨 Demande de Déblocage d'Urgence</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-warning">
                    <strong>⚠️ Attention!</strong> Un déblocage anticipé entraînera des frais de pénalité.
                </div>

                <form action="#" id="unlockRequestForm">
                    <div class="mb-4">
                        <label class="form-label text-white fw-semibold">Montant à débloquer (XOF)</label>
                        <input type="number" class="form-control form-control-glass" name="amount" min="1000" step="100" max="{{ $savingsWallet->balance }}" required>
                    </div>

                    <div class="mb-4">
                        <label class="form-label text-white fw-semibold">Raison (minimum 20 caractères)</label>
                        <textarea class="form-control form-control-glass" name="reason" rows="4" minlength="20" maxlength="500" required placeholder="Expliquez la raison de cette demande urgente..."></textarea>
                    </div>

                    <button type="submit" class="btn btn-glass w-100">
                        <i class="fas fa-unlock me-2"></i> Envoyer la Demande
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Modal: Lock Savings Wallet -->
<div class="modal fade" id="lockModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-glass" style="background: linear-gradient(135deg, rgba(245, 158, 11, 0.95), rgba(168, 85, 247, 0.95)); backdrop-filter: blur(20px);">
            <div class="modal-header border-0">
                <h5 class="modal-title text-white fw-bold">🔒 Bloquer le Wallet Épargne</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <strong>ℹ️ Info:</strong> Une fois bloqué, votre wallet d'épargne de <strong>{{ number_format($savingsWallet->balance, 0, ',', ' ') }} XOF</strong> sera indisponible jusqu'à la fin de la période de blocage choisie.
                </div>

                <form action="#" id="lockWalletForm">
                    <div class="mb-4">
                        <label class="form-label text-white fw-semibold">Durée de blocage</label>
                        <select class="form-select form-control-glass text-white" name="lock_duration" required>
                            <option value="">-- Sélectionnez une durée --</option>
                            <option value="1">1 mois</option>
                            <option value="3">3 mois</option>
                            <option value="6">6 mois</option>
                            <option value="12">12 mois</option>
                        </select>
                    </div>

                    <div class="mb-4">
                        <div class="alert alert-warning">
                            <strong>⚠️ Important:</strong> Le blocage est irréversible. Vous ne pourrez retirer des fonds qu'après la fin de la période ou en demandant un déblocage d'urgence (avec pénalités).
                        </div>
                    </div>

                    <button type="submit" class="btn btn-glass w-100">
                        <i class="fas fa-lock me-2"></i> Confirmer le Blocage
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
let selectedPlanId = null;
let selectedDuration = null;
let selectedRate = null;
let selectedMinAmount = 0;

function selectPlan(planId, duration, rate, minAmount) {
    selectedPlanId = planId;
    selectedDuration = duration;
    selectedRate = rate;
    selectedMinAmount = minAmount;
    
    document.querySelectorAll('.plan-card').forEach(card => {
        card.classList.remove('selected');
    });
    event.currentTarget.classList.add('selected');
    
    showTransferModal('to_savings', true);
}

function showTransferModal(direction, fromPlan = false) {
    if (!fromPlan) {
        selectedPlanId = null;
        selectedDuration = null;
        selectedRate = null;
        selectedMinAmount = 0;
    }

    const modal = new bootstrap.Modal(document.getElementById('transferModal'));
    const title = direction === 'to_savings' 
        ? '📥 Transférer vers Épargne' 
        : '📤 Transférer vers Wallet Principal';
    
    document.getElementById('transferModalTitle').textContent = title;
    document.getElementById('transferDirection').value = direction;
    document.getElementById('transferAmount').value = '';
    
    if (direction === 'to_savings' && selectedDuration) {
        document.getElementById('selectedPlanDuration').value = selectedDuration;
        document.getElementById('planSelectionInfo').style.display = 'block';
        document.getElementById('selectedPlanInfo').innerHTML = `
            ${selectedDuration} mois à ${selectedRate}% - Minimum ${selectedMinAmount.toLocaleString()} XOF
        `;
        document.getElementById('minAmountText').textContent = `Minimum requis: ${selectedMinAmount.toLocaleString()} XOF`;
        document.getElementById('transferAmount').min = selectedMinAmount;
    } else {
        document.getElementById('selectedPlanDuration').value = '';
        document.getElementById('planSelectionInfo').style.display = 'none';
        document.getElementById('minAmountText').textContent = 'Minimum: 1 000 XOF';
        document.getElementById('transferAmount').min = 1000;
    }
    
    modal.show();
}

function showUnlockRequestModal() {
    const modal = new bootstrap.Modal(document.getElementById('unlockRequestModal'));
    modal.show();
}

function showLockModal() {
    const modal = new bootstrap.Modal(document.getElementById('lockModal'));
    modal.show();
}

// Transfer Form
document.getElementById('transferForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const direction = document.getElementById('transferDirection').value;
    const amount = document.getElementById('transferAmount').value;
    const lockDuration = document.getElementById('selectedPlanDuration').value;
    const usePlan = direction === 'to_savings' && selectedPlanId && selectedDuration;

    if (usePlan && !lockDuration) {
        alert('❌ Veuillez sélectionner un plan d\'épargne');
        return;
    }
    
    const submitBtn = document.getElementById('transferSubmitBtn');
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Traitement...';
    
    try {
        const url = direction === 'to_savings'
            ? (usePlan ? '{{ route("member.savings.lock-plan") }}' : '{{ route("member.savings.transfer-to") }}')
            : '{{ route("member.savings.transfer-from") }}';
        
        const body = {
            amount: parseFloat(amount)
        };
        
        if (usePlan) {
            body.lock_duration = parseInt(lockDuration);
        }
        
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify(body)
        });
        
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Réponse invalide du serveur');
        }

        const data = await response.json();
        
        if (data.success) {
            alert('✅ ' + data.message);
            bootstrap.Modal.getInstance(document.getElementById('transferModal')).hide();
            location.reload();
        } else {
            alert('❌ ' + (data.message || 'Erreur lors du transfert'));
        }
    } catch (error) {
        console.error('Fetch error:', error);
        alert('❌ Erreur réseau: ' + error.message);
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-paper-plane me-2"></i> Effectuer le Transfert';
    }
});

// Early Unlock Function for Independent Blocks
function earlyUnlock(lockId) {
    if (!confirm('⚠️ Êtes-vous sûr? Le déblocage anticipé vous fera perdre tous les intérêts accumulés. Vous récupérerez uniquement votre capital initial.')) {
        return;
    }
    
    const btn = event.target.closest('button');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Déblocage...';
    
    fetch('{{ route("member.savings.early-unlock") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': '{{ csrf_token() }}'
        },
        body: JSON.stringify({
            lock_id: lockId
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ ' + data.message);
            location.reload();
        } else {
            alert('❌ ' + (data.message || 'Erreur lors du déblocage'));
            btn.disabled = false;
            btn.innerHTML = '<i class="fas fa-unlock me-2"></i> Déblocage anticipé (perte intérêts)';
        }
    })
    .catch(error => {
        alert('❌ Erreur: ' + error.message);
        btn.disabled = false;
        btn.innerHTML = '<i class="fas fa-unlock me-2"></i> Déblocage anticipé (perte intérêts)';
    });
}

// Unlock Request Form
document.getElementById('unlockRequestForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Envoi...';
    
    try {
        const response = await fetch('{{ route("member.savings.request-unlock") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                amount: formData.get('amount'),
                reason: formData.get('reason')
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('✅ ' + data.message);
            location.reload();
        } else {
            alert('❌ ' + data.message);
        }
    } catch (error) {
        alert('❌ Erreur: ' + error.message);
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-unlock me-2"></i> Envoyer la Demande';
    }
});

// Lock Wallet Form
document.getElementById('lockWalletForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> Blocage...';
    
    try {
        const response = await fetch('{{ route("member.savings.lock") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                lock_duration: formData.get('lock_duration')
            })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('✅ ' + data.message);
            location.reload();
        } else {
            alert('❌ ' + data.message);
        }
    } catch (error) {
        alert('❌ Erreur: ' + error.message);
    } finally {
        submitBtn.disabled = false;
        submitBtn.innerHTML = '<i class="fas fa-lock me-2"></i> Confirmer le Blocage';
    }
});
</script>
@endpush
