{% extends "base.html" %}

{% block title %}Pricing Plans{% endblock %}

{% block content %}
<h2 style="margin-bottom: 30px;">Pricing Plans</h2>

{% if success %}
<div class="alert alert-success">{{ success }}</div>
{% endif %}

{% if error %}
<div class="alert alert-error">{{ error }}</div>
{% endif %}

<div style="text-align: center; margin-bottom: 40px;">
    <h3 style="margin-bottom: 15px; color: var(--color-text);">Choose Your Plan</h3>
    <p style="color: var(--color-muted); font-size: 16px; max-width: 600px; margin: 0 auto;">Select the perfect tier for your AI service needs. All plans include access to all providers, rotations, and autoselection features.</p>
    {% if wallet_balance is not none %}
    <div style="margin-top: 15px; display: inline-flex; align-items: center; gap: 10px; background: var(--bg-panel); border: 1px solid #28a745; border-radius: 8px; padding: 10px 20px;">
        <i class="fas fa-wallet" style="color: #4ade80;"></i>
        <span style="color: var(--color-muted);">Wallet balance:</span>
        <span style="color: #4ade80; font-weight: bold; font-size: 18px;">{{ currency_symbol }}{{ "%.2f"|format(wallet_balance) }}</span>
        <a href="{{ url_for(request, '/dashboard/wallet') }}" style="color: var(--color-link); font-size: 13px; text-decoration: none;">Top Up</a>
    </div>
    {% endif %}
</div>

<!-- Paid Tiers -->
{% set paid_tiers = tiers | selectattr('is_default', 'equalto', False) | list %}
<div class="pricing-grid" data-count="{{ paid_tiers|length }}">
    {% for tier in paid_tiers %}
    <div class="pricing-card {% if tier.is_recommended %}recommended{% endif %}">
        {% if tier.is_recommended %}
        <div style="background: var(--color-link); color: white; padding: 8px 15px; border-radius: 20px; text-align: center; margin-bottom: 20px; font-weight: bold; text-transform: uppercase; font-size: 12px;">
            Recommended
        </div>
        {% endif %}

        <div style="text-align: center; margin-bottom: 25px;">
            <h3 style="margin: 0 0 15px 0; color: var(--color-text);">{{ tier.name }}</h3>
            <div style="font-size: 32px; font-weight: bold; color: #4ade80; margin-bottom: 5px;">
                {{ currency_symbol }}{{ "%.2f"|format(tier.price_monthly) }}
            </div>
            <div style="color: var(--color-muted);">per month</div>
            {% if tier.price_yearly > 0 %}
            <div style="color: #4ade80; font-size: 12px; margin-top: 5px;">
                Save {{ ((1 - tier.price_yearly / (tier.price_monthly * 12)) * 100)|round|int }}% with annual billing
            </div>
            {% endif %}
        </div>

        {% if tier.description %}
        <p style="color: var(--color-muted); font-size: 14px; text-align: center; margin-bottom: 20px; line-height: 1.5;">{{ tier.description }}</p>
        {% endif %}

        <ul style="list-style: none; padding: 0; margin: 0 0 25px 0;">
            <li style="margin-bottom: 10px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 10px;"></i>
                {% if tier.max_requests_per_day == -1 %}
                Unlimited requests per day
                {% elif tier.max_requests_per_day == 0 %}
                No requests permitted
                {% else %}
                {{ "{:,}".format(tier.max_requests_per_day) }} requests per day
                {% endif %}
            </li>
            <li style="margin-bottom: 10px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 10px;"></i>
                {% if tier.max_requests_per_month == -1 %}
                Unlimited requests per month
                {% elif tier.max_requests_per_month == 0 %}
                No requests permitted
                {% else %}
                {{ "{:,}".format(tier.max_requests_per_month) }} requests per month
                {% endif %}
            </li>
            <li style="margin-bottom: 10px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 10px;"></i>
                {% if tier.max_providers == -1 %}
                Unlimited providers
                {% elif tier.max_providers == 0 %}
                No providers permitted
                {% else %}
                Up to {{ tier.max_providers }} providers
                {% endif %}
            </li>
            <li style="margin-bottom: 10px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 10px;"></i>
                {% if tier.max_rotations == -1 %}
                Unlimited rotations
                {% elif tier.max_rotations == 0 %}
                No rotations permitted
                {% else %}
                Up to {{ tier.max_rotations }} rotations
                {% endif %}
            </li>
            <li style="margin-bottom: 10px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 10px;"></i>
                {% if tier.max_autoselections == -1 %}
                Unlimited autoselections
                {% elif tier.max_autoselections == 0 %}
                No autoselections permitted
                {% else %}
                Up to {{ tier.max_autoselections }} autoselections
                {% endif %}
            </li>
        </ul>

        <div style="text-align: center;">
            {% if current_tier and current_tier.id == tier.id %}
            <button class="btn btn-secondary" disabled style="width: 100%; padding: 12px;">
                <i class="fas fa-check me-2"></i>Current Plan
            </button>
            {% else %}
            <button class="btn upgrade-btn" onclick="subscribeToTier({{ tier.id }}, '{{ tier.name }}', {{ tier.price_monthly }})" style="width: 100%; padding: 12px;">
                <i class="fas fa-arrow-up me-2"></i>Upgrade Now
            </button>
            {% endif %}
        </div>
    </div>
    {% endfor %}
</div>

<!-- Free Tier -->
<div style="max-width: 500px; margin: 0 auto;">
    <div style="background: var(--bg-panel); border: 2px solid var(--color-border); border-radius: 8px; padding: 30px; text-align: center;">
        <h3 style="margin: 0 0 15px 0; color: var(--color-text);">Free Tier</h3>
        <div style="font-size: 36px; font-weight: bold; color: #4ade80; margin-bottom: 10px;">Free Forever</div>
        <p style="color: var(--color-muted); margin-bottom: 20px;">Perfect for testing and personal use</p>

        <ul style="list-style: none; padding: 0; margin: 0 0 25px 0; text-align: left; max-width: 300px; margin-left: auto; margin-right: auto;">
            {% set free_tier = tiers|selectattr('is_default', 'equalto', True)|first %}
            {% if free_tier %}
            <li style="margin-bottom: 8px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 8px;"></i>
                {% if free_tier.max_requests_per_day == -1 %}
                Unlimited requests per day
                {% elif free_tier.max_requests_per_day is not none %}
                {{ "{:,}".format(free_tier.max_requests_per_day) }} requests per day
                {% else %}
                Limited requests per day
                {% endif %}
            </li>
            <li style="margin-bottom: 8px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 8px;"></i>
                {% if free_tier.max_requests_per_month == -1 %}
                Unlimited requests per month
                {% elif free_tier.max_requests_per_month is not none %}
                {{ "{:,}".format(free_tier.max_requests_per_month) }} requests per month
                {% else %}
                Limited requests per month
                {% endif %}
            </li>
            <li style="margin-bottom: 8px; color: var(--color-text);">
                <i class="fas fa-check" style="color: #4ade80; margin-right: 8px;"></i>
                {% if free_tier.max_providers == -1 %}
                Unlimited providers
                {% elif free_tier.max_providers is not none %}
                Up to {{ free_tier.max_providers }} providers
                {% else %}
                Limited providers
                {% endif %}
            </li>
            {% endif %}
        </ul>

        {% if not current_tier or current_tier.is_default %}
        <button class="btn btn-secondary" disabled style="width: 100%; padding: 12px;">
            <i class="fas fa-check me-2"></i>You are on the Free Plan
        </button>
        {% else %}
        <button class="btn btn-danger" onclick="downgradeToFree()" style="width: 100%; padding: 12px;">
            <i class="fas fa-arrow-down me-2"></i>Downgrade to Free
        </button>
        {% endif %}
    </div>
</div>

<!-- Payment Methods -->
{% if enabled_gateways|length > 0 %}
<div style="background: var(--bg-panel); border: 2px solid var(--color-border); border-radius: 8px; padding: 25px; margin-top: 40px; text-align: center;">
    <h4 style="margin: 0 0 20px 0; color: var(--color-text);">Secure Payment Methods</h4>
    <div style="display: flex; justify-content: center; align-items: center; gap: 30px; flex-wrap: wrap;">
        {% for gateway in enabled_gateways %}
        <div style="text-align: center;">
            {% if gateway == 'paypal' %}
            <i class="fab fa-paypal fa-3x" style="color: var(--color-link); margin-bottom: 8px;"></i>
            <div style="color: var(--color-muted); font-size: 14px;">PayPal</div>
            {% elif gateway == 'stripe' %}
            <i class="fab fa-stripe fa-3x" style="color: #4ade80; margin-bottom: 8px;"></i>
            <div style="color: var(--color-muted); font-size: 14px;">Stripe</div>
            {% elif gateway == 'bitcoin' %}
            <i class="fab fa-bitcoin fa-3x" style="color: #f39c12; margin-bottom: 8px;"></i>
            <div style="color: var(--color-muted); font-size: 14px;">Bitcoin</div>
            {% elif gateway == 'ethereum' or gateway == 'eth' %}
            <i class="fab fa-ethereum fa-3x" style="color: #6f42c1; margin-bottom: 8px;"></i>
            <div style="color: var(--color-muted); font-size: 14px;">ETH</div>
            {% elif gateway == 'usdt' %}
            <i class="fas fa-dollar-sign fa-3x" style="color: #17a2b8; margin-bottom: 8px;"></i>
            <div style="color: var(--color-muted); font-size: 14px;">USDT</div>
            {% elif gateway == 'usdc' %}
            <i class="fas fa-coins fa-3x" style="color: var(--color-link); margin-bottom: 8px;"></i>
            <div style="color: var(--color-muted); font-size: 14px;">USDC</div>
            {% endif %}
        </div>
        {% endfor %}
    </div>
    <p style="color: var(--color-muted); font-size: 14px; margin-top: 15px;">All transactions are secure and encrypted</p>
</div>
{% endif %}
{% endblock %}

{% block extra_css %}
<style>
.pricing-grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    gap: 20px;
    margin-bottom: 40px;
}

.pricing-grid[data-count="1"] .pricing-card {
    max-width: 400px;
    width: 100%;
}

.pricing-grid[data-count="2"] .pricing-card {
    max-width: 380px;
    flex: 1 1 300px;
}

.pricing-grid[data-count="3"] .pricing-card {
    max-width: 340px;
    flex: 1 1 280px;
}

.pricing-grid .pricing-card {
    flex: 1 1 280px;
    max-width: 400px;
}

.pricing-card {
    background: var(--bg-panel);
    border: 2px solid var(--color-border);
    border-radius: 8px;
    padding: 25px;
}

.pricing-card.recommended {
    border-color: var(--color-link);
    box-shadow: 0 0 20px var(--shadow);
}

.upgrade-btn {
    background: var(--color-primary);
}
</style>
{% endblock %}

{% block extra_js %}
<script>
const WALLET_BALANCE = {{ wallet_balance|default(0)|float }};
const CURRENCY_SYMBOL = '{{ currency_symbol }}';
const HAS_STRIPE_CARD = {{ has_stripe_card|tojson }};

async function subscribeToTier(tierId, tierName, tierPrice) {
    // Build a smart confirmation message
    let msg = `Upgrade to <strong>${tierName}</strong> for <strong>${CURRENCY_SYMBOL}${tierPrice.toFixed(2)}/mo</strong>?`;

    if (WALLET_BALANCE >= tierPrice) {
        msg += `<br><br><span style="color:#4ade80;"><i class="fas fa-wallet me-1"></i>Your wallet balance (${CURRENCY_SYMBOL}${WALLET_BALANCE.toFixed(2)}) covers this. No card needed.</span>`;
    } else if (HAS_STRIPE_CARD) {
        const shortage = tierPrice - WALLET_BALANCE;
        msg += `<br><br><span style="color:#ffc107;"><i class="fas fa-credit-card me-1"></i>Your wallet is ${CURRENCY_SYMBOL}${shortage.toFixed(2)} short — your saved card will be charged ${CURRENCY_SYMBOL}${tierPrice.toFixed(2)}.</span>`;
    } else {
        msg += `<br><br><span style="color:#f87171;"><i class="fas fa-exclamation-triangle me-1"></i>Your wallet balance (${CURRENCY_SYMBOL}${WALLET_BALANCE.toFixed(2)}) is insufficient and no card is saved.</span><br><a href="/dashboard/wallet" style="color:#4a9eff;">Top up wallet</a> or <a href="/dashboard/billing/add-method" style="color:#4a9eff;">add a card</a> first.`;
    }

    const ok = await showConfirm(msg, 'Upgrade Plan', undefined, undefined, true);
    if (!ok) return;

    const btn = document.querySelector(`button[onclick*="subscribeToTier(${tierId}"]`);
    if (btn) { btn.disabled = true; btn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Processing…'; }

    fetch(`/dashboard/subscribe/${tierId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            const msg = encodeURIComponent(result.message || 'Plan upgraded successfully!');
            window.location.href = `/dashboard/pricing?success=${msg}`;
        } else if (result.error === 'insufficient_funds') {
            showToast(
                `Insufficient funds. Wallet: ${CURRENCY_SYMBOL}${(result.wallet_balance||0).toFixed(2)}, needed: ${CURRENCY_SYMBOL}${(result.required||0).toFixed(2)}. ` +
                `<a href="/dashboard/wallet" style="color:#4a9eff;">Top up</a> or <a href="/dashboard/billing/add-method" style="color:#4a9eff;">add a card</a>.`,
                'danger'
            );
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-arrow-up me-2"></i>Upgrade Now'; }
        } else {
            showToast(result.error || 'Error processing subscription', 'danger');
            if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-arrow-up me-2"></i>Upgrade Now'; }
        }
    })
    .catch(() => {
        showToast('Error processing subscription', 'danger');
        if (btn) { btn.disabled = false; btn.innerHTML = '<i class="fas fa-arrow-up me-2"></i>Upgrade Now'; }
    });
}

async function downgradeToFree() {
    const ok = await showConfirm('Downgrade to the free tier? Your current plan remains active until the end of the billing period.', 'Downgrade Plan');
    if (!ok) return;

    fetch('/dashboard/subscribe/free', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' }
    })
    .then(r => r.json())
    .then(result => {
        if (result.success) {
            const msg = encodeURIComponent(result.message || 'Downgraded to free plan');
            window.location.href = `/dashboard/pricing?success=${msg}`;
        } else {
            showToast(result.error || 'Error processing downgrade', 'danger');
        }
    })
    .catch(() => showToast('Error processing downgrade', 'danger'));
}

function showToast(message, type) {
    const toastContainer = document.createElement('div');
    toastContainer.className = 'position-fixed top-0 end-0 p-3';
    toastContainer.style.zIndex = '9999';
    toastContainer.innerHTML = `
        <div class="toast show" role="alert" style="min-width: 300px; background:#16213e; border:1px solid #0f3460; border-radius:8px; box-shadow:0 4px 12px rgba(0,0,0,0.4);">
            <div class="toast-header" style="background:${type==='success'?'#1a3a2e':type==='danger'?'#3a1a1a':'#1a2a3a'}; color:${type==='success'?'#4ade80':type==='danger'?'#f87171':'#60a5fa'}; border-bottom:1px solid #0f3460; border-radius:8px 8px 0 0; padding:10px 15px; display:flex; align-items:center; justify-content:space-between;">
                <strong><i class="fas fa-${type==='success'?'check-circle':type==='danger'?'exclamation-circle':'info-circle'} me-2"></i>Notification</strong>
                <button onclick="this.closest('.position-fixed').remove()" style="background:none;border:none;color:inherit;cursor:pointer;font-size:16px;">×</button>
            </div>
            <div class="toast-body" style="padding:12px 15px; color:#e0e0e0;">${message}</div>
        </div>
    `;
    document.body.appendChild(toastContainer);
    setTimeout(() => { if (toastContainer.parentNode) toastContainer.remove(); }, 7000);
}
</script>
{% endblock %}
