<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Rewards - LocalLendables</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        .reward-card {
            transition: transform 0.2s ease, box-shadow 0.2s ease;
            height: 100%;
        }
        
        .reward-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .reward-image {
            height: 200px;
            object-fit: cover;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 3rem;
        }
        
        .points-badge {
            position: absolute;
            top: 10px;
            right: 10px;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: bold;
            box-shadow: 0 2px 10px rgba(40, 167, 69, 0.3);
        }
        
        .points-display {
            background: linear-gradient(135deg, #007bff, #6610f2);
            color: white;
            padding: 1rem;
            border-radius: 15px;
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .category-tab {
            margin-bottom: 2rem;
        }
        
        .category-tab .nav-link {
            border-radius: 25px;
            margin-right: 10px;
            font-weight: 500;
        }
        
        .category-tab .nav-link.active {
            background: linear-gradient(135deg, #007bff, #6610f2);
            border-color: transparent;
        }
        
        .sponsor-badge {
            background: #f8f9fa;
            color: #6c757d;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            margin-top: 5px;
        }
        
        .redeem-btn {
            background: linear-gradient(135deg, #28a745, #20c997);
            border: none;
            border-radius: 25px;
            padding: 8px 20px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .redeem-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
        }
        
        .redeem-btn:disabled {
            background: #6c757d;
            transform: none;
            box-shadow: none;
        }
    </style>
</head>
<body class="bg-light">
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container">
            <a class="navbar-brand fw-bold" href="/dashboard/{{ currentUser.id }}">
                <i class="fas fa-leaf me-2"></i>LocalLendables
            </a>
            <div class="d-flex align-items-center text-white">
                <span class="me-3">Welcome, {{ currentUser.firstName }}!</span>
                <a href="/dashboard/{{ currentUser.id }}" class="btn btn-outline-light btn-sm">
                    <i class="fas fa-home me-1"></i>Dashboard
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <!-- Points Display -->
        <div class="points-display">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <h3 class="mb-1">
                        <i class="fas fa-star me-2"></i>Your Points Balance
                    </h3>
                    <h1 class="mb-0">{{ userPoints.totalPoints }} Points</h1>
                    <small class="opacity-75">Lifetime earned: {{ userPoints.lifetimePoints }} points</small>
                </div>
                <div class="col-md-4 text-end">
                    <button class="btn btn-light" onclick="viewPointsHistory()">
                        <i class="fas fa-history me-1"></i>Points History
                    </button>
                </div>
            </div>
        </div>

        <!-- Category Tabs -->
        <ul class="nav nav-pills category-tab" role="tablist">
            <li class="nav-item">
                <a class="nav-link active" data-bs-toggle="pill" href="#all" onclick="filterRewards('all')">All Rewards</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="pill" href="#food" onclick="filterRewards('Food & Treats')">Food & Treats</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="pill" href="#cards" onclick="filterRewards('Gift Cards')">Gift Cards</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" data-bs-toggle="pill" href="#experiences" onclick="filterRewards('Experiences')">Experiences</a>
            </li>
        </ul>

        <!-- Rewards Grid -->
        <div class="row" id="rewardsGrid">
            {% for reward in rewards %}
            <div class="col-md-4 mb-4 reward-item" data-category="{{ reward.category }}">
                <div class="card reward-card">
                    <div class="position-relative">
                        {% if reward.image_url %}
                            <img src="{{ reward.image_url }}" class="card-img-top reward-image" alt="{{ reward.name }}">
                        {% else %}
                            <div class="reward-image">
                                <i class="fas fa-gift"></i>
                            </div>
                        {% endif %}
                        <div class="points-badge">{{ reward.points_cost }} pts</div>
                    </div>
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title">{{ reward.name }}</h5>
                        <p class="card-text flex-grow-1">{{ reward.description }}</p>
                        {% if reward.sponsor_name %}
                            <div class="sponsor-badge d-inline-block">
                                <i class="fas fa-handshake me-1"></i>{{ reward.sponsor_name }}
                            </div>
                        {% endif %}
                        <div class="mt-3">
                            {% if reward.quantity_available and reward.quantity_available <= 0 %}
                                <button class="btn btn-secondary redeem-btn w-100" disabled>
                                    <i class="fas fa-times me-1"></i>Out of Stock
                                </button>
                            {% elseif userPoints.totalPoints >= reward.points_cost %}
                                <button class="btn btn-success redeem-btn w-100" onclick="redeemReward({{ reward.id }}, '{{ reward.name }}', {{ reward.points_cost }})">
                                    <i class="fas fa-star me-1"></i>Redeem Now
                                </button>
                            {% else %}
                                <button class="btn btn-outline-secondary redeem-btn w-100" disabled>
                                    <i class="fas fa-lock me-1"></i>Need {{ reward.points_cost - userPoints.totalPoints }} more points
                                </button>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        {% if rewards|length == 0 %}
        <div class="text-center py-5">
            <i class="fas fa-gift fa-3x text-muted mb-3"></i>
            <h4 class="text-muted">No rewards available yet</h4>
            <p class="text-muted">Check back soon for exciting rewards!</p>
        </div>
        {% endif %}
    </div>

    <!-- Redemption Success Modal -->
    <div class="modal fade" id="redemptionModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-check-circle me-2"></i>Redemption Successful!
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body text-center" id="redemptionContent">
                    <!-- Content will be populated by JavaScript -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" onclick="printCoupon()">
                        <i class="fas fa-print me-1"></i>Print Coupon
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>
    <script>
        let currentCouponCode = '';
        let currentRewardName = '';

        function filterRewards(category) {
            const items = document.querySelectorAll('.reward-item');
            items.forEach(item => {
                if (category === 'all' || item.dataset.category === category) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        }

        async function redeemReward(rewardId, rewardName, pointsCost) {
            if (!confirm(`Redeem "${rewardName}" for ${pointsCost} points?`)) {
                return;
            }

            try {
                const response = await fetch('/api/rewards/redeem', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ rewardId })
                });

                const result = await response.json();

                if (result.success) {
                    currentCouponCode = result.couponCode;
                    currentRewardName = rewardName;
                    showRedemptionSuccess(rewardName, result.couponCode);
                    
                    // Update points display
                    location.reload();
                } else {
                    alert('Error: ' + result.error);
                }
            } catch (error) {
                console.error('Error redeeming reward:', error);
                alert('Failed to redeem reward. Please try again.');
            }
        }

        async function showRedemptionSuccess(rewardName, couponCode) {
            const modal = document.getElementById('redemptionModal');
            const content = document.getElementById('redemptionContent');
            
            // Generate QR code
            const qrCanvas = document.createElement('canvas');
            await QRCode.toCanvas(qrCanvas, couponCode, {
                width: 200,
                margin: 2,
                color: {
                    dark: '#000000',
                    light: '#FFFFFF'
                }
            });
            
            content.innerHTML = `
                <div class="reward-success">
                    <h4 class="text-success mb-3">🎉 ${rewardName}</h4>
                    <p class="mb-4">Your reward has been redeemed! Show this coupon to redeem:</p>
                    <div class="coupon-container border rounded p-4 bg-light">
                        <div class="text-center mb-3">
                            ${qrCanvas.outerHTML}
                        </div>
                        <div class="text-center">
                            <strong>Coupon Code:</strong><br>
                            <span class="h5 font-monospace text-primary">${couponCode}</span>
                        </div>
                        <hr>
                        <small class="text-muted">
                            <i class="fas fa-info-circle me-1"></i>
                            Present this QR code or coupon code to the sponsor to redeem your reward.
                            This coupon expires in 30 days.
                        </small>
                    </div>
                </div>
            `;
            
            new bootstrap.Modal(modal).show();
        }

        function printCoupon() {
            const printWindow = window.open('', '_blank');
            const couponContent = document.getElementById('redemptionContent').innerHTML;
            
            printWindow.document.write(`
                <html>
                <head>
                    <title>LocalLendables Coupon</title>
                    <style>
                        body { font-family: Arial, sans-serif; margin: 20px; }
                        .coupon-container { border: 2px solid #007bff; padding: 20px; text-align: center; }
                        .text-center { text-align: center; }
                        .text-primary { color: #007bff; }
                        .font-monospace { font-family: monospace; }
                        .h5 { font-size: 1.25rem; font-weight: 500; }
                        hr { margin: 20px 0; }
                        .text-muted { color: #6c757d; }
                    </style>
                </head>
                <body>
                    <h2 style="text-align: center; color: #28a745;">LocalLendables Reward Coupon</h2>
                    ${couponContent}
                </body>
                </html>
            `);
            
            printWindow.document.close();
            printWindow.print();
        }

        function viewPointsHistory() {
            window.open('/rewards/history', '_blank');
        }
    </script>
</body>
</html>