{% extends 'layouts/base.html' %}

{% block title %}Packages{% endblock %}

{% block content %}
<div class="packages-container" style="    padding: 21px;">
    <div class="page-header">
        <div>
            <h1 class="page-title">Packages</h1>
            <p class="page-subtitle">
                Choose the plan that best fits your team and subscribe securely through Stripe.
            </p>
            {% if active_package_id %}
            <p class="page-subtitle">
                Current subscription active{% if remaining_days is not none %} with {{ remaining_days }} day{{ 's' if
                remaining_days != 1 else '' }} remaining{% endif %}.
                {% if active_expires_at %}Expires on {{ active_expires_at.strftime('%Y-%m-%d') }}.{% endif %}
            </p>
            {% endif %}
        </div>
    </div>

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

    <div id="packagesFeedback" class="toast hidden"></div>

    <div class="packages-grid">
        {% for package in packages %}
        <article class="package-card" data-package-id="{{ package.id }}">
            <div class="package-card-header">
                <h3 class="package-title">{{ package.title }}</h3>
            </div>
            {% if package.is_active %}
            <div class="package-badge">
                <span class="badge badge-success">Subscribed</span>
            </div>
            {% endif %}
            <p class="package-description">{{ package.description or 'No description provided.' }}</p>
            <div class="package-meta">
                <div class="meta-item">
                    <span class="meta-label">Contacts</span>
                    <span class="meta-value">{{ package.no_of_contacts }}</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Call Minutes</span>
                    <span class="meta-value">{{ package.no_of_mins }}</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Validity</span>
                    <span class="meta-value">30 days</span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">File Limit</span>
                    <span class="meta-value">
                        {% if package.file_limit %}
                        {{ package.file_limit }} files
                        {% else %}
                        Unlimited
                        {% endif %}
                    </span>
                </div>
                <div class="meta-item">
                    <span class="meta-label">Price</span>
                    <span class="meta-value">{{ package.price_display }}</span>
                </div>
            </div>
            {% if package.is_active %}
            <div class="package-remaining">
                <i class="fa-light fa-hourglass-half"></i>
                <span>
                    Subscription active{% if package.remaining_days is not none %}, {{ package.remaining_days }} day{{
                    's' if package.remaining_days != 1 else '' }} remaining{% endif %}.
                </span>
            </div>
            {% endif %}
            <div class="package-footer">
                <!-- <div class="package-price">
                    {{ package.price_display }}
                </div> -->
                <button class="btn btn-primary subscribe-btn" data-package-id="{{ package.id }}" {% if package.is_active
                    %} disabled title="You have already subscribed to this package." style="cursor: not-allowed;" {%
                    endif %}>
                    <i class="fa-light fa-credit-card"></i>
                    <span>
                        {% if package.is_active %}
                        Subscribed
                        {% else %}
                        Subscribe
                        {% endif %}
                    </span>
                </button>
            </div>
        </article>
        {% else %}
        <div class="empty-state">
            <i class="fa-light fa-box-open"></i>
            <p>No packages found.</p>
        </div>
        {% endfor %}
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    (function () {
        const feedback = document.getElementById('packagesFeedback');

        function showFeedback(message, tone = 'success') {
            if (!feedback) return;
            feedback.textContent = message;
            feedback.classList.remove('hidden', 'error');
            if (tone === 'error') {
                feedback.classList.add('error');
            } else {
                feedback.classList.remove('error');
            }
            clearTimeout(feedback._timeout);
            feedback._timeout = setTimeout(() => feedback.classList.add('hidden'), 3500);
        }

        document.querySelectorAll('.subscribe-btn').forEach(button => {
            button.addEventListener('click', async () => {
                if (button.disabled) {
                    return;
                }

                const packageId = button.dataset.packageId;
                button.disabled = true;
                button.classList.add('loading');

                try {
                    const response = await fetch(`{{ url_for('company.subscribe_package', package_id=0) }}`.replace('0', packageId), {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({})
                    });
                    const result = await response.json();

                    if (!response.ok || !result.success || !result.checkout_url) {
                        throw new Error(result.error || 'Unable to start checkout.');
                    }

                    window.location.href = result.checkout_url;
                } catch (error) {
                    console.error(error);
                    showFeedback(error.message || 'Unable to start checkout. Please try again later.', 'error');
                } finally {
                    button.disabled = false;
                    button.classList.remove('loading');
                }
            });
        });
    })();
</script>
{% endblock %}