{% extends 'mastery/base.html' %}
{% load i18n %}
{% load humanize %}
{% load evelinks %}
{% load l10n %}
{% translate "Elite" as status_elite_label %}
{% translate "Almost elite" as status_almost_elite_label %}
{% translate "Can fly" as status_can_fly_label %}
{% translate "Almost fit" as status_almost_fit_label %}
{% translate "Needs training" as status_needs_training_label %}
{% translate "Fitting skill preview" as fitting_preview_label %}
{% translate "Loading preview..." as loading_preview_label %}
{% translate "Failed to load preview." as failed_preview_label %}

{% block details %}
<div class="container mt-4">
    <div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-3">
        <div>
            <h2 class="mb-1 d-flex align-items-center gap-2 flex-wrap">
                <img src="{{ fitting.ship_type_type_id|type_render_url:32 }}" class="rounded" width="32" height="32" alt="{{ fitting.ship_type.name }}">
                <span>{{ fitting.name }}</span>
                {% include 'mastery/partials/_priority_badge.html' with priority=fitting_map.priority %}
            </h2>
            <div class="text-muted d-flex align-items-center gap-2 flex-wrap">
                <span>{{ fitting.ship_type.name }}{% if doctrine %} · {% translate "Doctrine" %}: {{ doctrine.name }}{% endif %}</span>
                {% if doctrine %}{% include 'mastery/partials/_priority_badge.html' with priority=doctrine_priority %}{% endif %}
            </div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            {% if doctrine %}
            <a class="btn btn-sm btn-outline-secondary" href="{% url 'mastery:summary_doctrine_detail' doctrine.id %}?group_id={{ selected_group.id }}&activity_days={{ activity_days }}{% if include_inactive %}&include_inactive=1{% endif %}">{% translate "Back to doctrine" %}</a>
            {% endif %}
            <a class="btn btn-sm btn-outline-primary" href="{% url 'fittings:view_fit' fitting.id %}">{% translate "View fitting" %}</a>
            <button
                type="button"
                class="btn btn-sm btn-outline-info preview-fittings-btn"
                data-bs-toggle="modal"
                data-bs-target="#fittingPreviewModal"
                data-preview-url="{% url 'mastery:fitting_skills_preview' fitting.id %}"
                data-fitting-name="{{ fitting.name|escape }}"
            >
                {% translate "Preview skills" %}
            </button>
            {% if perms.mastery.manage_fittings %}
            <a class="btn btn-sm btn-outline-secondary" href="{% url 'mastery:fitting_skills' fitting.id %}">{% translate "Edit skill plan" %}</a>
            {% endif %}
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-3">
        <div class="card-body d-flex flex-wrap justify-content-between gap-2 align-items-center">
            <div class="small text-muted">{% translate "Audience group:" %} <strong>{{ selected_group.name }}</strong></div>
            <form method="get" class="d-flex flex-wrap align-items-center gap-2">
                {% if include_inactive %}<input type="hidden" name="include_inactive" value="1">{% endif %}
                <input type="hidden" name="export_mode" value="{{ export_mode }}">
                <label class="small text-muted" for="summaryGroupSwitchFitting">{% translate "Switch group" %}</label>
                <select id="summaryGroupSwitchFitting" name="group_id" class="form-select form-select-sm" style="width: 240px;">
                    {% for group in summary_groups %}
                    <option value="{{ group.id }}" {% if selected_group.id == group.id %}selected{% endif %}>{{ group.name }}</option>
                    {% endfor %}
                </select>
                <label class="small text-muted" for="summaryFittingActivityDays">{% translate "Activity days" %}</label>
                <input id="summaryFittingActivityDays" class="form-control form-control-sm" type="number" min="1" max="90" name="activity_days" value="{{ activity_days }}" style="width: 96px;">
                <button class="btn btn-sm btn-outline-primary" type="submit">{% translate "Apply" %}</button>
            </form>
        </div>
    </div>

    <div class="card border-0 shadow-sm mb-3">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span class="fw-semibold">{% translate "Character readiness" %}</span>
            <div class="d-flex align-items-center gap-2">
                <span class="small text-muted">{% translate "Avg recommended" %}</span>
                <span class="fw-semibold">{{ fitting_kpis.recommended_avg_pct }}%</span>
                <div class="progress" style="height: 6px; width: 100px;">
                    <div class="progress-bar bg-primary" role="progressbar" style="width: {{ fitting_kpis.recommended_avg_pct|unlocalize }}%"></div>
                </div>
            </div>
        </div>
        <div class="card-body">
            {% include 'mastery/partials/_summary_status_kpi_cards.html' with kpis=fitting_kpis flyable_now=fitting_kpis.flyable_now_users users_total=fitting_kpis.users_total interactive=1 %}
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-header d-flex justify-content-between align-items-center gap-2 flex-wrap">
            <div class="d-flex align-items-center gap-2">
                <span>{% translate "Member coverage" %}</span>
                <button type="button" class="btn btn-sm btn-outline-secondary kpi-filter-btn show-all-filter-btn" data-filter="all">{% translate "Show all" %}</button>
            </div>
            <a class="btn btn-sm btn-outline-primary" href="?group_id={{ selected_group.id }}&activity_days={{ activity_days }}{% if include_inactive %}&include_inactive=1{% endif %}&export_mode={{ export_mode }}&format=csv">
                <span class="fas fa-file-csv me-1" aria-hidden="true"></span>{% translate "Export CSV" %}
            </a>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-sm align-middle mb-0 mastery-summary-table">
                    <thead class="mastery-summary-thead">
                    <tr>
                        <th>{% translate "Main" %}</th>
                        {% include 'mastery/partials/_summary_status_headers.html' with include_tooltips=1 include_chars_suffix=0 status_thresholds=status_thresholds %}
                    </tr>
                    </thead>
                    <tbody>
                    {% for row in user_rows %}
                    <tr class="member-row" data-elite-count="{{ row.elite_pilots|length }}" data-almost-elite-count="{{ row.almost_elite_pilots|length }}" data-can-fly-count="{{ row.can_fly_pilots|length }}" data-almost-fit-count="{{ row.almost_fit_pilots|length }}" data-needs-training-count="{{ row.needs_training_pilots|length }}">
                        <td>
                            {% if row.main_character %}
                            <div class="d-flex align-items-center gap-2">
                                <img src="{{ row.main_character|character_portrait_url:32 }}" class="rounded-circle" width="32" height="32" alt="{{ row.main_character.character_name }}">
                                <div>
                                    <div>{{ row.main_character.character_name }}</div>
                                    <div class="small text-muted">{% blocktranslate with flyable=row.flyable_count total=row.active_count %}{{ flyable }}/{{ total }} flyable{% endblocktranslate %}</div>
                                </div>
                            </div>
                            {% else %}
                            <div>{{ row.user.username }}</div>
                            <div class="small text-muted">{% blocktranslate with flyable=row.flyable_count total=row.active_count %}{{ flyable }}/{{ total }} flyable{% endblocktranslate %}</div>
                            {% endif %}
                        </td>
                        <td>
                            {% include 'mastery/partials/_pilot_avatar_cell.html' with pilots=row.elite_pilots bucket='elite' row_user_id=row.user.id status_label=status_elite_label focus_filter='elite' focus_btn='success' fitting=fitting export_mode=export_mode selected_group=selected_group %}
                        </td>
                        <td>
                            {% include 'mastery/partials/_pilot_avatar_cell.html' with pilots=row.almost_elite_pilots bucket='almost_elite' row_user_id=row.user.id status_label=status_almost_elite_label focus_filter='almost_elite' focus_btn='primary' fitting=fitting export_mode=export_mode selected_group=selected_group %}
                        </td>
                        <td>
                            {% include 'mastery/partials/_pilot_avatar_cell.html' with pilots=row.can_fly_pilots bucket='can_fly' row_user_id=row.user.id status_label=status_can_fly_label focus_filter='can_fly_now' focus_btn='info' fitting=fitting export_mode=export_mode selected_group=selected_group %}
                        </td>
                        <td>
                            {% include 'mastery/partials/_pilot_avatar_cell.html' with pilots=row.almost_fit_pilots bucket='almost_fit' row_user_id=row.user.id status_label=status_almost_fit_label focus_filter='almost_required' focus_btn='warning' fitting=fitting export_mode=export_mode selected_group=selected_group %}
                        </td>
                        <td>
                            {% include 'mastery/partials/_pilot_avatar_cell.html' with pilots=row.needs_training_pilots bucket='needs_training' row_user_id=row.user.id status_label=status_needs_training_label focus_filter='needs_training' focus_btn='danger' fitting=fitting export_mode=export_mode selected_group=selected_group %}
                        </td>
                    </tr>
                    {% empty %}
                    <tr>
                        <td colspan="6" class="text-muted">{% translate "No active characters in the selected activity window." %}</td>
                    </tr>
                    {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="fittingPreviewModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">{{ fitting_preview_label }}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="fittingPreviewModalBody">
                <div class="text-muted">{{ loading_preview_label }}</div>
            </div>
        </div>
    </div>
</div>

<style>
    .mastery-summary-table.table-sm > :not(caption) > * > * {
        padding-top: 0.32rem;
        padding-bottom: 0.32rem;
    }

    .kpi-filter-btn {
        border-color: var(--bs-border-color-translucent, rgba(0, 0, 0, 0.15));
    }

    .kpi-filter-btn.active {
        box-shadow: inset 0 0 0 1px var(--bs-primary, #0d6efd);
        background-color: rgba(13, 110, 253, 0.08);
    }

    .show-all-filter-btn {
        color: var(--bs-body-color, #212529);
        border-color: rgba(108, 117, 125, 0.55);
    }

    .show-all-filter-btn.active {
        color: #212529 !important;
        border-color: rgba(13, 110, 253, 0.55) !important;
        background-color: rgba(13, 110, 253, 0.14) !important;
    }

    html[data-bs-theme="dark"] .show-all-filter-btn,
    body[data-bs-theme="dark"] .show-all-filter-btn,
    html[data-theme*="dark"] .show-all-filter-btn,
    body[data-theme*="dark"] .show-all-filter-btn {
        color: #f8f9fa;
        border-color: rgba(255, 255, 255, 0.45);
        background-color: rgba(255, 255, 255, 0.08);
    }

    html[data-bs-theme="dark"] .show-all-filter-btn.active,
    body[data-bs-theme="dark"] .show-all-filter-btn.active,
    html[data-theme*="dark"] .show-all-filter-btn.active,
    body[data-theme*="dark"] .show-all-filter-btn.active {
        color: #ffffff;
        background-color: rgba(13, 110, 253, 0.28);
        border-color: rgba(13, 110, 253, 0.7);
    }

    {% include 'mastery/partials/_pilot_avatar_popover_styles.html' %}

</style>

<script>
    $(document).ready(() => {
        $('[data-bs-tooltip="aa-mastery"]').tooltip();
        const rowSelector = '.member-row';

        const countAttrByFilter = {
            elite: 'eliteCount',
            almost_elite: 'almostEliteCount',
            can_fly: 'canFlyCount',
            almost_fit: 'almostFitCount',
            needs_training: 'needsTrainingCount',
        };

        const applyMemberCoverageFilter = (filterName) => {
            document.querySelectorAll(rowSelector).forEach((row) => {
                if (filterName === 'all') {
                    row.classList.remove('d-none');
                    return;
                }
                const attrName = countAttrByFilter[filterName];
                const value = Number(row.dataset[attrName] || 0);
                row.classList.toggle('d-none', value <= 0);
            });

            document.querySelectorAll('.kpi-filter-btn[data-filter]').forEach((btn) => {
                btn.classList.toggle('active', btn.dataset.filter === filterName);
            });
        };

        $(document).on('click', '.kpi-filter-btn[data-filter]', function () {
            applyMemberCoverageFilter(this.dataset.filter || 'all');
        });

        applyMemberCoverageFilter('{{ selected_member_filter|default:"all" }}');

        const modalElement = document.getElementById('fittingPreviewModal');
        if (modalElement) {
            const modalBody = document.getElementById('fittingPreviewModalBody');
            const modalTitle = modalElement.querySelector('.modal-title');
            const previewTitleLabel = '{{ fitting_preview_label|escapejs }}';
            const loadingPreviewHtml = '<div class="text-muted">{{ loading_preview_label|escapejs }}</div>';
            const failedPreviewHtml = '<div class="text-danger">{{ failed_preview_label|escapejs }}</div>';
            modalElement.addEventListener('show.bs.modal', async (event) => {
                const button = event.relatedTarget;
                if (!button) {
                    return;
                }
                modalTitle.textContent = `${previewTitleLabel} - ${button.dataset.fittingName}`;
                modalBody.innerHTML = loadingPreviewHtml;
                try {
                    const response = await fetch(button.dataset.previewUrl, {
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest'
                        }
                    });
                    modalBody.innerHTML = await response.text();
                } catch (_error) {
                    modalBody.innerHTML = failedPreviewHtml;
                }
            });
        }
    });
</script>
{% include 'mastery/partials/_pilot_popover_init_script.html' %}
{% endblock %}
