{% extends "indy_hub/base.html" %}
{% load i18n %}
{% load static %}

{% block page_title %}{% trans "ESI" %}{% endblock page_title %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'indy_hub/css/page_headers.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/components.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/index.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/token_management.css' %}">
{% endblock extra_css %}

{% block content %}
<div class="container-fluid py-4">
    {% url 'indy_hub:index' as overview_url %}
    {% include "indy_hub/partials/page_header.html" with icon_class="fas fa-key" title=_("ESI") subtitle=_("Authorize the scopes Indy Hub needs for each character and corporation.") back_url=overview_url back_label=_("Back to Overview") %}

    {% if corp_role_warnings %}
        {% for warning in corp_role_warnings %}
            <div class="alert alert-{{ warning.level }}" role="alert">
                {{ warning.message }}
            </div>
        {% endfor %}
    {% endif %}

    <section class="dashboard-section mb-4">
        <header class="section-heading">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                <div>
                    <h3 class="section-title">{% trans "Characters" %}</h3>
                    <p class="text-muted small mb-0">{% trans "Coverage per character." %}</p>
                </div>
                <div>
                    <a href="{% url 'indy_hub:authorize_all' %}?force=1&next={{ request.get_full_path|urlencode }}" class="btn btn-primary">
                        <i class="fas fa-user-plus me-1"></i>{% trans "Add character" %}
                    </a>
                </div>
            </div>
        </header>
        <div class="card focus-card">
            <div class="table-responsive">
            <table class="table table-hover mb-0 align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width: 64px;"></th>
                        <th>{% trans "Character" %}</th>
                        <th class="text-center">{% trans "Status" %}</th>
                    </tr>
                </thead>
                <tbody>
                    {% for char in characters %}
                        <tr>
                            <td>
                                <img
                                    src="https://images.evetech.net/characters/{{ char.character_id }}/portrait?size=64"
                                    alt="{{ char.name }}"
                                    class="rounded-circle"
                                    width="40"
                                    height="40"
                                    loading="lazy"
                                    onerror="this.style.display='none';">
                            </td>
                            <td class="fw-semibold">{{ char.name }}</td>
                            <td class="text-center">
                                {% if char.has_all_scopes %}
                                    <span class="badge bg-success-subtle text-success"><i class="fas fa-check me-1"></i>{% trans "All active" %}</span>
                                {% else %}
                                    <span class="badge bg-warning-subtle text-warning"><i class="fas fa-exclamation-triangle me-1"></i>{% trans "Missing scopes" %}</span>
                                    <div class="small text-muted">
                                        {% blocktrans with missing=char.missing_scopes|join:", " %}Missing: {{ missing }}{% endblocktrans %}
                                    </div>
                                {% endif %}
                            </td>
                        </tr>
                    {% empty %}
                        <tr>
                            <td colspan="3" class="text-center text-muted py-4">{% trans "No characters found." %}</td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
            </div>
        </div>

        <div class="card focus-card mt-4">
            <div class="card-body p-4">
                <h6 class="text-uppercase text-muted fw-bold mb-3">{% trans "Character scopes required by Indy Hub" %}</h6>
                <div class="d-flex flex-wrap gap-2">
                    {% for scope in required_character_scopes_display %}
                        <span class="scope-badge">{{ scope }}</span>
                    {% empty %}
                        <span class="text-muted small">{% trans "No scopes defined." %}</span>
                    {% endfor %}
                </div>
            </div>
        </div>
    </section>

    {% if can_manage_corp_bp_requests %}
        <section class="dashboard-section mb-4">
            <header class="section-heading">
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
                    <div>
                        <h3 class="section-title">{% trans "Corporations" %}</h3>
                        <p class="text-muted small mb-0">{% trans "Coverage for director tokens." %}</p>
                    </div>
                    <div>
                        {% if corp_all_auth_url %}
                            <a href="{{ corp_all_auth_url }}" class="btn btn-outline-primary">
                                <i class="fas fa-building me-1"></i>{% trans "Add corp " %}
                            </a>
                        {% else %}
                            <span class="badge bg-secondary-subtle text-secondary">{% trans "Unavailable" %}</span>
                        {% endif %}
                    </div>
                </div>
            </header>
            <div class="card focus-card">
                <div class="table-responsive">
                <table class="table table-hover mb-0 align-middle">
                    <thead class="table-light">
                        <tr>
                            <th>{% trans "Corporation" %}</th>
                            <th class="text-center">{% trans "Status" %}</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for corp in corporations %}
                            <tr>
                                <td>
                                    <div class="d-flex align-items-center gap-3">
                                        <img
                                            src="https://images.evetech.net/corporations/{{ corp.corporation_id }}/logo?size=64"
                                            alt="{{ corp.corporation_name }}"
                                            class="rounded"
                                            width="40"
                                            height="40"
                                            loading="lazy"
                                            onerror="this.style.display='none';">
                                        <div>
                                            <div class="fw-semibold">{{ corp.corporation_name }}</div>
                                        </div>
                                    </div>
                                </td>
                                <td class="text-center">
                                    {% if corp.roles_unavailable %}
                                        <span class="badge bg-warning-subtle text-warning"><i class="fas fa-exclamation-triangle me-1"></i>{% trans "Roles unavailable" %}</span>
                                        <div class="small text-muted">{% trans "ESI roles check failed; scopes unverified." %}</div>
                                    {% elif corp.has_all_scopes %}
                                        <span class="badge bg-success-subtle text-success"><i class="fas fa-check me-1"></i>{% trans "All active" %}</span>
                                        <div class="small text-muted">{% trans "Director token ready" %}</div>
                                    {% else %}
                                        <span class="badge bg-warning-subtle text-warning"><i class="fas fa-exclamation-triangle me-1"></i>{% trans "Missing scopes" %}</span>
                                        <div class="small text-muted">
                                            {% blocktrans with missing=corp.missing_scopes|join:", " %}Missing: {{ missing }}{% endblocktrans %}
                                        </div>
                                    {% endif %}
                                </td>
                            </tr>
                        {% empty %}
                            <tr>
                                <td colspan="2" class="text-center text-muted py-4">{% trans "No corporation access detected." %}</td>
                            </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card focus-card mt-4">
            <div class="card-body p-4">
                <h6 class="text-uppercase text-muted fw-bold mb-3">{% trans "Corporation scopes required by Indy Hub" %}</h6>
                <div class="d-flex flex-wrap gap-2">
                    {% for scope in required_corporation_scopes %}
                        <span class="scope-badge">{{ scope }}</span>
                    {% empty %}
                        <span class="text-muted small">{% trans "No scopes defined." %}</span>
                    {% endfor %}
                </div>
            </div>
        </div>
        </section>
    {% endif %}
</div>
{% endblock content %}

{% block extra_javascript %}
{{ block.super }}
{% if token_management_live_refresh_needed and token_management_live_refresh_url %}
<script>
(function () {
    function runLiveRefresh() {
        var refreshUrl = "{{ token_management_live_refresh_url }}";
        var currentHash = "{{ token_management_live_hash|default:''|escapejs }}";
        var url = refreshUrl + (refreshUrl.indexOf('?') === -1 ? '?' : '&') +
            'current_hash=' + encodeURIComponent(currentHash);

        fetch(url, {
            method: 'GET',
            credentials: 'same-origin',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(function (response) {
                if (!response.ok) {
                    return null;
                }
                return response.json();
            })
            .then(function (payload) {
                if (!payload || !payload.updated || !payload.has_changes) {
                    return;
                }
                var nextUrl = new URL(window.location.href);
                nextUrl.searchParams.set('tm_live', '1');
                window.location.replace(nextUrl.toString());
            })
            .catch(function () {
                // Keep initial fast-rendered UI if live refresh fails.
            });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', runLiveRefresh, { once: true });
    } else {
        runLiveRefresh();
    }
})();
</script>
{% endif %}
{% endblock extra_javascript %}
