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

{% block page_title %}{{ scope_title }}{% 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/jobs.css' %}">
{% endblock extra_css %}

{% block content %}
<div class="container-fluid py-4">
    <div class="page-header mb-4">
        <div class="d-flex flex-wrap align-items-center justify-content-between gap-3">
            <div>
                <h2 class="h3 mb-1">
                    <i class="fas fa-industry me-2"></i>
                    {{ scope_title }}
                </h2>
                <p class="description">{{ scope_description }}</p>
            </div>
            <div class="d-flex flex-wrap align-items-center gap-2">
                <a href="{{ back_to_overview_url }}" class="btn btn-outline-light">
                    <i class="fas fa-arrow-left me-1"></i>{% trans "Back to Overview" %}
                </a>
                <button type="button" class="btn btn-light text-primary" data-refresh-jobs onclick="refreshJobs()">
                    <i class="fas fa-sync-alt me-1"></i>{% trans "Refresh Data" %}
                </button>
            </div>
        </div>
    </div>

    {% if slot_overview_summary %}
        <div class="slot-overview-card mb-4">
            <div class="card-body">
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-2 slot-overview-header">
                    <div class="slot-overview-title">
                        {% trans "Industry Slots Overview" %}
                    </div>
                    <button class="btn btn-outline-secondary btn-sm slot-overview-toggle"
                            type="button"
                            data-bs-toggle="collapse"
                            data-bs-target="#slotOverviewPanel"
                            aria-expanded="false"
                            aria-controls="slotOverviewPanel">
                        <i class="fas fa-bars me-1"></i>{% trans "Details" %}
                    </button>
                </div>

                <div class="row g-3 slot-overview-summary">
                    <div class="col-6 col-lg-3">
                        <div class="slot-overview-summary-card">
                            <div class="slot-overview-summary-value">{{ slot_overview_summary.characters }}</div>
                            <div class="slot-overview-summary-label">{% trans "Characters" %}</div>
                        </div>
                    </div>
                    <div class="col-6 col-lg-3">
                        <div class="slot-overview-summary-card">
                            <div class="slot-overview-summary-value">
                                {% if slot_overview_summary.manufacturing.total %}
                                    {{ slot_overview_summary.manufacturing.available }} / {{ slot_overview_summary.manufacturing.total }}
                                {% else %}
                                    —
                                {% endif %}
                            </div>
                            <div class="slot-overview-summary-label">{% trans "Mfg" %}</div>
                        </div>
                    </div>
                    <div class="col-6 col-lg-3">
                        <div class="slot-overview-summary-card">
                            <div class="slot-overview-summary-value">
                                {% if slot_overview_summary.research.total %}
                                    {{ slot_overview_summary.research.available }} / {{ slot_overview_summary.research.total }}
                                {% else %}
                                    —
                                {% endif %}
                            </div>
                            <div class="slot-overview-summary-label">{% trans "Res" %}</div>
                        </div>
                    </div>
                    <div class="col-6 col-lg-3">
                        <div class="slot-overview-summary-card">
                            <div class="slot-overview-summary-value">
                                {% if slot_overview_summary.reactions.total %}
                                    {{ slot_overview_summary.reactions.available }} / {{ slot_overview_summary.reactions.total }}
                                {% else %}
                                    —
                                {% endif %}
                            </div>
                            <div class="slot-overview-summary-label">{% trans "React" %}</div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="collapse" id="slotOverviewPanel">
                <div class="slot-overview-details">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0 align-middle slot-overview-table">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 64px;"></th>
                                    <th>{% trans "Character" %}</th>
                                    <th class="text-center">{% trans "Manufacturing" %}</th>
                                    <th class="text-center">{% trans "Research" %}</th>
                                    <th class="text-center">{% trans "Reactions" %}</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for char in slot_overview_rows %}
                                    <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.manufacturing.total is not None %}
                                                <div class="slot-overview-cell">
                                                    <div class="slot-overview-value">{{ char.manufacturing.available }} / {{ char.manufacturing.total }}</div>
                                                    <div class="progress slot-overview-progress" role="progressbar" aria-valuenow="{{ char.manufacturing.percent_used }}" aria-valuemin="0" aria-valuemax="100">
                                                        <div class="progress-bar" style="width: {{ char.manufacturing.percent_used }}%;"></div>
                                                    </div>
                                                </div>
                                            {% else %}
                                                <span class="text-muted">—</span>
                                            {% endif %}
                                        </td>
                                        <td class="text-center">
                                            {% if char.research.total is not None %}
                                                <div class="slot-overview-cell">
                                                    <div class="slot-overview-value">{{ char.research.available }} / {{ char.research.total }}</div>
                                                    <div class="progress slot-overview-progress" role="progressbar" aria-valuenow="{{ char.research.percent_used }}" aria-valuemin="0" aria-valuemax="100">
                                                        <div class="progress-bar" style="width: {{ char.research.percent_used }}%;"></div>
                                                    </div>
                                                </div>
                                            {% else %}
                                                <span class="text-muted">—</span>
                                            {% endif %}
                                        </td>
                                        <td class="text-center">
                                            {% if char.reactions.total is not None %}
                                                <div class="slot-overview-cell">
                                                    <div class="slot-overview-value">{{ char.reactions.available }} / {{ char.reactions.total }}</div>
                                                    <div class="progress slot-overview-progress" role="progressbar" aria-valuenow="{{ char.reactions.percent_used }}" aria-valuemin="0" aria-valuemax="100">
                                                        <div class="progress-bar" style="width: {{ char.reactions.percent_used }}%;"></div>
                                                    </div>
                                                </div>
                                            {% else %}
                                                <span class="text-muted">—</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    {% if char.skills_missing %}
                                        <tr class="table-light">
                                            <td></td>
                                            <td colspan="4" class="small text-muted">
                                                <div class="d-flex flex-wrap align-items-center gap-2">
                                                    <span>{% blocktrans with scope=skills_scope %}Missing scope: {{ scope }}{% endblocktrans %}</span>
                                                    <a href="{% url 'indy_hub:authorize_all' %}?force=1&next={{ request.get_full_path|urlencode }}" class="btn btn-primary btn-sm ms-auto">
                                                        <i class="fas fa-user-plus me-1"></i>{% trans "Update" %}
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    {% endif %}
                                {% empty %}
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-4">{% trans "No characters found." %}</td>
                                    </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div class="slot-overview-legend text-muted small">
                        {% trans "Legend:" %} <span class="slot-overview-legend-label">{% trans "Available / Total" %}</span> · {% trans "Progress bar shows slots in use (filled = busy)." %}
                    </div>
                </div>
            </div>
        </div>
    {% endif %}

    <div class="row g-3 mb-4">
        <div class="col-12">
            {# Corporate guidance now lives on token management page #}
            <form method="get" class="row g-3 align-items-end">
                <input type="hidden" name="scope" value="{{ scope }}">
                <div class="col-lg-3">
                    <label class="form-label text-muted fw-bold">{% trans 'Search' %}</label>
                    <input type="text" name="search" value="{{ current_filters.search }}" class="form-control"
                        id="jobSearch" placeholder="{% trans 'Job, blueprint, owner...' %}">
                </div>
                <div class="col-lg-2">
                    <label class="form-label text-muted fw-bold">{% trans 'Status' %}</label>
                    <select name="status" class="form-select" id="statusFilter">
                        <option value="">{% trans 'All Status' %}</option>
                        {% for s in statuses %}
                        <option value="{{ s }}" {% if current_filters.status == s %}selected{% endif %}>{{ s|title }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-lg-2">
                    <label class="form-label text-muted fw-bold">{% trans 'Activity' %}</label>
                    <select name="activity" class="form-select" id="activityFilter">
                        <option value="">{% trans 'All Activities' %}</option>
                        {% for aid,name in activities %}
                        <option value="{{ aid }}" {% if current_filters.activity == aid %}selected{% endif %}>{{ name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-lg-3">
                    <label class="form-label text-muted fw-bold">{{ owner_label }}</label>
                    <select name="owner" class="form-select" id="ownerFilter">
                        <option value="">{% if is_corporation_scope %}{% trans 'All Corporations' %}{% else %}{% trans 'All Characters' %}{% endif %}</option>
                        {% for owner_id, owner_name in owner_options %}
                        <option value="{{ owner_id }}" {% if current_filters.owner|stringformat:'s' == owner_id|stringformat:'s' %}selected{% endif %}>{{ owner_name }}</option>
                        {% endfor %}
                    </select>
                </div>
                <div class="col-lg-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="fas fa-filter me-1"></i>{% trans 'Apply Filters' %}
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="stats-card">
                <div class="card-body text-center">
                    <div class="h4 text-info mb-1">{{ statistics.total|default:0 }}</div>
                    <small class="text-muted fw-bold">{% trans 'Total Jobs' %}</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="card-body text-center">
                    <div class="h4 text-warning mb-1">{{ statistics.active|default:0 }}</div>
                    <small class="text-muted fw-bold">{% trans 'Active Jobs' %}</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="card-body text-center">
                    <div class="h4 text-success mb-1">{{ statistics.completed|default:0 }}</div>
                    <small class="text-muted fw-bold">{% trans 'Completed' %}</small>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stats-card">
                <div class="card-body text-center">
                    <div class="h4 text-secondary mb-1">{{ owner_count|default:0 }}</div>
                    <small class="text-muted fw-bold">{{ owner_label }}</small>
                </div>
            </div>
        </div>
    </div>

    <div class="job-groups">
        {% if job_groups %}
            {% for group in job_groups %}
            <section class="job-group-section mb-5">
                <div class="d-flex flex-wrap align-items-start justify-content-between gap-3 mb-3">
                    <div class="d-flex align-items-center gap-3">
                        <span class="d-inline-flex align-items-center justify-content-center rounded-circle bg-body-secondary text-primary"
                            style="width:48px;height:48px;">
                            <i class="{{ group.icon }}"></i>
                        </span>
                        <div>
                            <h3 class="h5 mb-1">{{ group.title }}</h3>
                            <p class="text-muted small mb-0">{{ group.subtitle }}</p>
                        </div>
                    </div>
                    <span class="badge text-uppercase fw-semibold {{ group.badge_variant }} px-3 py-2">{{ group.chip }}</span>
                </div>
                <div class="row g-4">
                    {% for job in group.jobs %}
                    <div class="col-xl-4 col-lg-6">
                        <div class="card h-100 shadow-sm border-0 job-card">
                            <div class="card-body d-flex flex-column gap-3">
                                <div class="d-flex justify-content-between gap-3 flex-wrap">
                                    <div class="d-flex gap-3 align-items-center" style="min-width: 0;">
                                        {% if job.icon_url %}
                                        <img src="{{ job.icon_url }}" alt="{{ job.blueprint_type_name }}" class="rounded flex-shrink-0"
                                            style="width:48px;height:48px;object-fit:cover;" loading="lazy"
                                            onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                        {% endif %}
                                        <span class="fallback fs-3 text-secondary flex-shrink-0" style="display:none;"><i class="fas fa-industry"></i></span>
                                        <div style="min-width: 0;">
                                            <h4 class="h6 mb-1 text-truncate">{{ job.blueprint_type_name|default:job.blueprint_type_id }}</h4>
                                            <p class="text-muted small mb-0"><i class="{{ owner_icon }} me-1"></i>{{ job.display_owner_name }}</p>
                                        </div>
                                    </div>
                                    <span class="badge {{ group.badge_variant }} align-self-start px-3 py-2 flex-shrink-0">{{ group.chip }}</span>
                                </div>
                                <div class="d-flex flex-wrap gap-2 small">
                                    <span class="badge bg-light text-dark border">{{ job.runs }} {% trans 'runs' %}</span>
                                    {% if job.successful_runs %}
                                    <span class="badge bg-light text-dark border">{{ job.successful_runs }} {% trans 'successful' %}</span>
                                    {% endif %}
                                    <span class="badge bg-light text-dark border">{{ job.status_label }}</span>
                                    {% if job.output_name %}
                                    <span class="badge bg-light text-dark border">{{ job.output_name }}</span>
                                    {% endif %}
                                </div>
                                {% with progress=job.progress_percent|default:0 %}
                                {% with progress_numeric=progress|add:0 %}
                                <div class="job-progress-panel" data-progress="{{ progress_numeric }}">
                                    <div class="progress gradient-progress {% if job.is_completed %}progress-state-complete{% elif progress_numeric >= 75 %}progress-state-late{% elif progress_numeric >= 40 %}progress-state-mid{% elif progress_numeric > 0 %}progress-state-early{% else %}progress-state-idle{% endif %}">
                                        <div class="progress-bar {% if job.is_completed %}progress-bar-complete{% elif progress_numeric >= 75 %}progress-bar-late{% elif progress_numeric >= 40 %}progress-bar-mid{% elif progress_numeric > 0 %}progress-bar-early{% else %}progress-bar-idle{% endif %}{% if job.is_completed %} progress-bar-striped{% endif %}"
                                            role="progressbar"
                                            aria-valuenow="{{ progress_numeric }}" aria-valuemin="0"
                                            aria-valuemax="100"
                                            style="width: {{ progress_numeric }}%;">
                                            <span class="visually-hidden">{{ progress|floatformat:0 }}%</span>
                                        </div>
                                        <span class="progress-label">{{ progress|floatformat:0 }}%</span>
                                    </div>
                                    <small class="text-muted d-block mt-1"><i class="fas fa-hourglass-half me-1"></i>{{ job.display_eta|default:'--:--:--' }}</small>
                                </div>
                                {% endwith %}
                                {% endwith %}
                                {% if job.research_details %}
                                {% with details=job.research_details %}
                                <div class="d-flex flex-column small bg-light rounded-3 px-3 py-2">
                                    <span class="text-muted text-uppercase fw-semibold mb-1">{% trans 'Research levels' %}</span>
                                    {% if details.base != None and details.target != None %}
                                    <span class="fw-semibold">{{ details.attribute }} {{ details.base }} -> {{ details.target }} / {{ details.max }}</span>
                                    {% else %}
                                    <span class="text-muted">{% trans 'Research level data unavailable' %}</span>
                                    {% endif %}
                                    {% if details.increments %}
                                    <span class="text-muted">
                                        {% blocktrans count run_count=details.increments %}
                                            {{ run_count }} run scheduled
                                        {% plural %}
                                            {{ run_count }} runs scheduled
                                        {% endblocktrans %}
                                    </span>
                                    {% endif %}
                                </div>
                                {% endwith %}
                                {% endif %}
                                {% if job.copy_details %}
                                <div class="d-flex flex-column small bg-light rounded-3 px-3 py-2">
                                    <span class="text-muted text-uppercase fw-semibold mb-1">{% trans 'Copy output' %}</span>
                                    <span class="fw-semibold">
                                        {% blocktrans with runs=job.copy_details.runs %}
                                        {{ runs }} copies
                                        {% endblocktrans %}
                                    </span>
                                    {% if job.copy_details.licensed_runs %}
                                    <span class="text-muted">
                                        {% blocktrans with licensed=job.copy_details.licensed_runs %}
                                        {{ licensed }} licensed runs
                                        {% endblocktrans %}
                                    </span>
                                    {% endif %}
                                </div>
                                {% endif %}
                                {% if group.key == 'invention' and job.probability_percent != None %}
                                <div class="d-flex flex-column small bg-light rounded-3 px-3 py-2">
                                    <span class="text-muted text-uppercase fw-semibold mb-1">{% trans 'Success chance' %}</span>
                                    <span class="fw-semibold">{{ job.probability_percent }}%</span>
                                </div>
                                {% endif %}
                                {% if group.key == 'reactions' %}
                                <div class="d-flex flex-column small bg-light rounded-3 px-3 py-2">
                                    <span class="text-muted text-uppercase fw-semibold mb-1">{% trans 'Reaction facility' %}</span>
                                    <span class="fw-semibold">{{ job.location_name|default:job.station_id }}</span>
                                </div>
                                {% endif %}
                            </div>
                            <div class="card-footer bg-transparent border-0 d-flex justify-content-between small text-muted">
                                                </form>
                                    {% if job.is_completed %}
                                    <i class="fas fa-flag-checkered me-1"></i>{{ job.display_end_date }}
                                    {% else %}
                                    <i class="fas fa-stopwatch me-1"></i>{{ job.display_end_date }}
                                    {% endif %}
                                </span>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </section>
            {% endfor %}
        {% else %}
        <div class="card border-0 shadow-sm">
            <div class="card-body text-center py-5">
                <i class="fas fa-clipboard-list-check fa-2x text-muted mb-3"></i>
                <h3 class="h6">{% trans 'No industry jobs found.' %}</h3>
                <p class="text-muted small mb-0">{% trans 'Start a new job in-game and refresh to see it here.' %}</p>
            </div>
        </div>
        {% endif %}
    </div>

    <div class="d-flex flex-wrap justify-content-between align-items-center mt-4 gap-2">
        <form method="get" class="d-flex align-items-center gap-2 mb-0">
            <label for="perPage" class="form-label mb-0 text-muted small">{% trans 'Per page' %}</label>
            <select name="per_page" id="perPage" class="form-select form-select-sm w-auto" onchange="this.form.submit()">
                {% for n in per_page_options %}
                <option value="{{ n }}" {% if current_filters.per_page|stringformat:'s' == n|stringformat:'s' %}selected{% endif %}>{{ n }}</option>
                {% endfor %}
            </select>
            <input type="hidden" name="scope" value="{{ scope }}">
            <input type="hidden" name="page" value="{{ jobs.number }}">
            <input type="hidden" name="search" value="{{ current_filters.search }}">
            <input type="hidden" name="status" value="{{ current_filters.status }}">
            <input type="hidden" name="activity" value="{{ current_filters.activity }}">
            <input type="hidden" name="owner" value="{{ current_filters.owner }}">
            <input type="hidden" name="order" value="{{ current_filters.order }}">
            <input type="hidden" name="sort" value="{{ current_filters.sort }}">
        </form>

        {% if jobs.has_other_pages %}
        <nav aria-label="{% trans 'Jobs pagination' %}">
            <ul class="pagination pagination-sm justify-content-center mb-0 flex-wrap">
                {% if jobs.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ jobs.previous_page_number }}&per_page={{ jobs.paginator.per_page }}&search={{ current_filters.search }}&status={{ current_filters.status }}&activity={{ current_filters.activity }}&owner={{ current_filters.owner }}&order={{ current_filters.order }}&sort={{ current_filters.sort }}&scope={{ scope }}" aria-label="{% trans 'Previous' %}">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                {% endif %}
                {% for num in jobs.paginator.page_range %}
                    {% if num == jobs.number %}
                    <li class="page-item active"><span class="page-link">{{ num }}</span></li>
                    {% elif num >= jobs.number|add:'-2' and num <= jobs.number|add:'2' %}
                    <li class="page-item"><a class="page-link" href="?page={{ num }}&per_page={{ jobs.paginator.per_page }}&search={{ current_filters.search }}&status={{ current_filters.status }}&activity={{ current_filters.activity }}&owner={{ current_filters.owner }}&order={{ current_filters.order }}&sort={{ current_filters.sort }}&scope={{ scope }}">{{ num }}</a></li>
                    {% elif num == 1 or num == jobs.paginator.num_pages %}
                    <li class="page-item"><a class="page-link" href="?page={{ num }}&per_page={{ jobs.paginator.per_page }}&search={{ current_filters.search }}&status={{ current_filters.status }}&activity={{ current_filters.activity }}&owner={{ current_filters.owner }}&order={{ current_filters.order }}&sort={{ current_filters.sort }}&scope={{ scope }}">{{ num }}</a></li>
                    {% if num < jobs.number|add:'-2' or num > jobs.number|add:'2' %}
                    <li class="page-item disabled"><span class="page-link">...</span></li>
                    {% endif %}
                    {% endif %}
                {% endfor %}
                {% if jobs.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ jobs.next_page_number }}&per_page={{ jobs.paginator.per_page }}&search={{ current_filters.search }}&status={{ current_filters.status }}&activity={{ current_filters.activity }}&owner={{ current_filters.owner }}&order={{ current_filters.order }}&sort={{ current_filters.sort }}&scope={{ scope }}" aria-label="{% trans 'Next' %}">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}
    </div>
</div>
{% endblock content %}

{% block extra_javascript %}
<script src="{% static 'indy_hub/js/jobs.js' %}"></script>
<script src="{% static 'indy_hub/js/personal_job_list.js' %}"></script>
{% endblock extra_javascript %}
