{% extends 'base.html' %}
{% load i18n %}
{% load static %}

{% block extra_css %}
<link href="{% static 'css/dist/styles.css' %}" rel="stylesheet">
<style>[x-cloak] { display: none !important; }</style>
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto"
     x-data="jobsManager()"
     x-init="init()">

    <!-- Header -->
    <div class="flex items-center justify-between mb-4">
        <h1 class="text-2xl font-bold text-gray-800">{% trans "Jobs" %}</h1>
        <div class="flex items-center gap-3 text-sm">
            <span class="inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium
                {% if scheduler_running %}bg-green-100 text-green-700{% else %}bg-red-100 text-red-700{% endif %}">
                <span class="w-2 h-2 rounded-full inline-block
                    {% if scheduler_running %}bg-green-500{% else %}bg-red-500{% endif %}"></span>
                {% if scheduler_running %}{% trans "Scheduler running" %}{% else %}{% trans "Scheduler stopped" %}{% endif %}
            </span>
            <span class="text-gray-400 text-xs">{% trans "Max concurrent:" %} <strong>{{ site_settings.max_concurrent_screenshot_jobs }}</strong></span>
            <a href="{% url 'site-settings' %}" class="text-blue-500 hover:underline text-xs">{% trans "Change" %}</a>
        </div>
    </div>

    {% if messages %}
    <div class="mb-4 space-y-2">
        {% for message in messages %}
        <div class="rounded-md px-4 py-3 text-sm
            {% if message.tags == 'success' %}bg-green-50 text-green-800 border border-green-200
            {% elif message.tags == 'error' %}bg-red-50 text-red-800 border border-red-200
            {% else %}bg-blue-50 text-blue-800 border border-blue-200{% endif %}">
            {{ message }}
        </div>
        {% endfor %}
    </div>
    {% endif %}

    <!-- Stats Row -->
    <div class="grid grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
        {% for stat in job_type_stats %}
        <div class="bg-white rounded-lg shadow p-4">
            <div class="flex items-center justify-between mb-3">
                <h2 class="text-sm font-semibold text-gray-600 flex items-center gap-1.5">
                    <svg class="w-4 h-4 {{ stat.icon_color }}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="{{ stat.icon_path }}"/>
                    </svg>
                    {{ stat.label }}
                </h2>
            </div>
            <div class="flex gap-3 text-center flex-wrap">
                <a href="?tab={{ stat.id }}&status=all" class="flex-1 hover:bg-gray-50 rounded p-1 min-w-0">
                    <div class="text-xl font-bold text-gray-700">{{ stat.total }}</div>
                    <div class="text-xs text-gray-400">{% trans "Total" %}</div>
                </a>
                {% if stat.pending is not None %}
                <a href="?tab={{ stat.id }}&status=pending" class="flex-1 hover:bg-gray-50 rounded p-1 min-w-0">
                    <div class="text-xl font-bold text-yellow-500">{{ stat.pending }}</div>
                    <div class="text-xs text-gray-400">{% trans "Pending" %}</div>
                </a>
                {% endif %}
                {% if stat.processing is not None %}
                <a href="?tab={{ stat.id }}&status=processing" class="flex-1 hover:bg-gray-50 rounded p-1 min-w-0">
                    <div class="text-xl font-bold text-blue-500">{{ stat.processing }}</div>
                    <div class="text-xs text-gray-400">{% trans "Running" %}</div>
                </a>
                {% endif %}
                {% if stat.completed is not None %}
                <a href="?tab={{ stat.id }}&status=completed" class="flex-1 hover:bg-gray-50 rounded p-1 min-w-0">
                    <div class="text-xl font-bold text-green-500">{{ stat.completed }}</div>
                    <div class="text-xs text-gray-400">{% trans "Done" %}</div>
                </a>
                {% endif %}
                {% if stat.failed is not None %}
                <a href="?tab={{ stat.id }}&status=failed" class="flex-1 hover:bg-gray-50 rounded p-1 min-w-0">
                    <div class="text-xl font-bold text-red-500">{{ stat.failed }}</div>
                    <div class="text-xs text-gray-400">{% trans "Failed" %}</div>
                </a>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- Tab + Filter Bar -->
    <div class="bg-white rounded-lg shadow mb-0 rounded-b-none border-b-0">
        <div class="flex items-center justify-between px-4 pt-3 pb-0">
            <!-- Tabs (driven by job registry) -->
            <div class="flex gap-1">
                {% for tab_info in job_type_tabs %}
                <a href="?tab={{ tab_info.id }}&status=all"
                   class="px-4 py-2 text-sm font-medium rounded-t-md border-b-2 transition-colors
                       {% if tab_info.is_active %}border-blue-500 text-blue-600 bg-white{% else %}border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50{% endif %}">
                    {{ tab_info.label }}
                    <span class="ml-1 px-1.5 py-0.5 text-xs rounded-full
                        {% if tab_info.is_active %}bg-blue-100 text-blue-600{% else %}bg-gray-100 text-gray-500{% endif %}">
                        {{ tab_info.count }}
                    </span>
                </a>
                {% endfor %}
                <a href="?tab=scheduler"
                   class="px-4 py-2 text-sm font-medium rounded-t-md border-b-2 transition-colors
                       {% if tab == 'scheduler' %}border-blue-500 text-blue-600 bg-white{% else %}border-transparent text-gray-500 hover:text-gray-700 hover:bg-gray-50{% endif %}">
                    {% trans "Scheduler" %}
                    <span class="ml-1 px-1.5 py-0.5 text-xs rounded-full
                        {% if tab == 'scheduler' %}bg-blue-100 text-blue-600{% else %}bg-gray-100 text-gray-500{% endif %}">
                        {{ scheduled_jobs|length }}
                    </span>
                </a>
            </div>

            <!-- Status filter pills (from registry status_choices) -->
            {% if status_choices %}
            <div class="flex gap-1.5 pb-1">
                {% for value, label in status_choices %}
                <a href="?tab={{ tab }}&status={{ value }}"
                   style="padding:.3rem .8rem;border-radius:9999px;font-size:.8rem;font-weight:500;text-decoration:none;display:inline-block;white-space:nowrap;
                   {% if status_filter == value %}
                       {% if value == 'all' %}background:#1f2937;color:#fff;
                       {% elif value == 'pending' %}background:#d97706;color:#fff;
                       {% elif value == 'processing' %}background:#2563eb;color:#fff;
                       {% elif value == 'completed' %}background:#16a34a;color:#fff;
                       {% elif value == 'failed' %}background:#dc2626;color:#fff;
                       {% else %}background:#374151;color:#fff;{% endif %}
                   {% else %}
                       {% if value == 'all' %}background:#f3f4f6;color:#374151;
                       {% elif value == 'pending' %}background:#fef3c7;color:#92400e;
                       {% elif value == 'processing' %}background:#eff6ff;color:#1e40af;
                       {% elif value == 'completed' %}background:#f0fdf4;color:#166534;
                       {% elif value == 'failed' %}background:#fff1f2;color:#991b1b;
                       {% else %}background:#f3f4f6;color:#374151;{% endif %}
                   {% endif %}">
                    {{ label }}
                </a>
                {% endfor %}
            </div>
            {% endif %}
        </div>
    </div>

    <!-- Bulk action toolbar -->
    <div class="border border-blue-200 border-t-0 px-4 py-2 flex items-center gap-3"
         style="background:#eff6ff;min-height:42px;">
        <span x-show="selectedIds.length === 0" style="font-size:.8rem;color:#6b7280;">
            ☑ {% trans "Use the checkbox in the header row to select all, or check individual rows — then use bulk actions here" %}
        </span>
        <div x-show="selectedIds.length > 0" class="flex items-center gap-3 w-full">
            <span style="font-size:.85rem;font-weight:600;color:#1d4ed8;" x-text="`${selectedIds.length} {% trans 'selected' %}`"></span>
            <div class="flex gap-2">
                <button @click="bulkAction('retry')"
                    style="background:#1d4ed8;color:#fff;padding:.3rem .85rem;border-radius:.25rem;font-size:.8rem;cursor:pointer;font-weight:500;">
                    ↺ {% trans "Retry" %}
                </button>
                <button @click="bulkAction('fail')" x-show="'fail' in bulkActionsMap"
                    style="background:#d97706;color:#fff;padding:.3rem .85rem;border-radius:.25rem;font-size:.8rem;cursor:pointer;font-weight:500;">
                    ✕ {% trans "Mark Failed" %}
                </button>
                <button @click="if(confirm('{% trans "Delete selected items?" %}')) bulkAction('delete')"
                    style="background:#dc2626;color:#fff;padding:.3rem .85rem;border-radius:.25rem;font-size:.8rem;cursor:pointer;font-weight:500;">
                    🗑 {% trans "Delete" %}
                </button>
            </div>
            <button @click="clearSelection()" style="margin-left:auto;font-size:.75rem;color:#3b82f6;background:none;border:none;cursor:pointer;text-decoration:underline;">{% trans "Clear" %}</button>
        </div>
    </div>

    <!-- Hidden bulk-action form -->
    <form id="bulk-form" method="post" style="display:none">
        {% csrf_token %}
        <input type="hidden" name="action" id="bulk-action-input">
        <input type="hidden" name="ids" id="bulk-ids-input">
        <input type="hidden" name="tab" value="{{ tab }}">
        <input type="hidden" name="status_filter" value="{{ status_filter }}">
    </form>

    <!-- List Panel -->
    <div class="bg-white rounded-lg shadow rounded-t-none border-t-0 overflow-hidden">

        {% if tab == 'scheduler' %}
        <!-- Scheduler Jobs -->
        <div class="px-4 pt-3 pb-2 flex items-center gap-2">
          <label class="text-xs text-gray-500">{% trans "Filter" %}:</label>
          <select x-model="schedulerFilter"
            class="text-xs rounded border border-gray-200 px-2 py-1 text-gray-700 bg-white shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-300">
            <option value="all">{% trans "All functions" %}</option>
            <template x-for="name in schedulerJobTypes" :key="name">
              <option :value="name" x-text="name"></option>
            </template>
          </select>
          <span class="text-xs text-gray-400" x-show="schedulerFilter !== 'all'">
            (<span x-text="filteredScheduledJobs.length"></span> {% trans "job(s)" %})
          </span>
        </div>
        {% if scheduled_jobs %}
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
                    <tr>
                        <th class="px-4 py-3 text-left">{% trans "Job ID" %}</th>
                        <th class="px-4 py-3 text-left">{% trans "Function" %}</th>
                        <th class="px-4 py-3 text-left">{% trans "Trigger" %}</th>
                        <th class="px-4 py-3 text-left">{% trans "Next Run" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    <template x-for="job in filteredScheduledJobs" :key="job.id">
                      <tr class="hover:bg-gray-50">
                        <td class="px-4 py-3 font-mono text-gray-500" style="font-size:.8rem;" x-text="job.id"></td>
                        <td class="px-4 py-3 font-medium" style="font-size:.85rem;" x-text="job.name"></td>
                        <td class="px-4 py-3 text-gray-400" style="font-size:.85rem;" x-text="job.trigger"></td>
                        <td class="px-4 py-3 text-gray-400 whitespace-nowrap" style="font-size:.85rem;" x-text="job.next_run || '\u2014'"></td>
                      </tr>
                    </template>
                </tbody>
            </table>
        </div>
        <div x-show="filteredScheduledJobs.length === 0"
             class="px-6 py-8 text-center text-gray-400 text-sm">
          {% trans "No jobs match this filter." %}
        </div>
        {% else %}
        <div class="px-6 py-12 text-center text-gray-400 text-sm">{% trans "No scheduled jobs." %}</div>
        {% endif %}

        {% else %}
        <!-- Unified job table (all registered types) -->
        {% if page_rows %}
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
                    <tr>
                        <th class="px-3 py-3 w-8">
                            <input type="checkbox" class="rounded text-blue-600"
                                   @change="toggleAll($event.target.checked, allIds)"
                                   :checked="allIds.length > 0 && selectedIds.length === allIds.length">
                        </th>
                        <th class="px-3 py-3 text-left">ID</th>
                        <th class="px-3 py-3 text-left">{{ current_tab_config.title_label }}</th>
                        {% if 'source_url' in current_tab_config.columns %}<th class="px-3 py-3 text-left">{% trans "Source URL" %}</th>{% endif %}
                        {% if 'status' in current_tab_config.columns %}<th class="px-3 py-3 text-left">{% trans "Status" %}</th>{% endif %}
                        {% if 'retry' in current_tab_config.columns %}<th class="px-3 py-3 text-left">{% trans "Retries" %}</th>{% endif %}
                        {% if 'error' in current_tab_config.columns %}<th class="px-3 py-3 text-left">{% trans "Error" %}</th>{% endif %}
                        {% if 'size' in current_tab_config.columns %}<th class="px-3 py-3 text-left">{% trans "Size" %}</th>{% endif %}
                        <th class="px-3 py-3 text-left">{% trans "Updated" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    {% for row in page_rows %}
                    <tr class="hover:bg-gray-50" :class="{'bg-blue-50': selectedIds.includes('{{ row.id }}') }">
                        <td class="px-3 py-2">
                            <input type="checkbox" class="rounded text-blue-600"
                                   value="{{ row.id }}"
                                   @change="toggle('{{ row.id }}')"
                                   :checked="selectedIds.includes('{{ row.id }}')">
                        </td>
                        <td class="px-3 py-2 font-mono text-gray-400" style="font-size:.75rem;">{{ row.id|truncatechars:12 }}</td>
                        <td class="px-3 py-2 max-w-xs">
                            {% if row.detail_url and row.detail_url != '#' %}
                            <a href="{{ row.detail_url }}" class="text-blue-600 hover:underline block truncate max-w-xs" style="font-size:.85rem;" title="{{ row.title }}">
                                {{ row.title|truncatechars:55 }}
                            </a>
                            {% else %}
                            <span class="text-gray-700 block truncate max-w-xs" style="font-size:.85rem;">{{ row.title|truncatechars:55 }}</span>
                            {% endif %}
                        </td>
                        {% if 'source_url' in current_tab_config.columns %}
                        <td class="px-3 py-2 max-w-xs">
                            <a href="{{ row.extra.source_url }}" target="_blank" rel="noopener"
                               class="text-gray-400 hover:text-blue-500 block truncate max-w-xs" style="font-size:.8rem;" title="{{ row.extra.source_url }}">
                                {{ row.extra.source_url|truncatechars:50 }}
                            </a>
                        </td>
                        {% endif %}
                        {% if 'status' in current_tab_config.columns %}
                        <td class="px-3 py-2">
                            <span style="display:inline-flex;align-items:center;padding:.15rem .55rem;border-radius:9999px;font-size:.75rem;font-weight:500;
                                {% if row.status == 'completed' %}background:#dcfce7;color:#166534;
                                {% elif row.status == 'failed' %}background:#fee2e2;color:#991b1b;
                                {% elif row.status == 'processing' %}background:#dbeafe;color:#1e40af;
                                {% else %}background:#fef9c3;color:#854d0e;{% endif %}">
                                {{ row.status }}
                            </span>
                        </td>
                        {% endif %}
                        {% if 'retry' in current_tab_config.columns %}
                        <td class="px-3 py-2 text-gray-500" style="font-size:.85rem;">
                            {% if row.retry is not None %}{{ row.retry }}/{{ row.retry_max }}{% else %}<span class="text-gray-300">—</span>{% endif %}
                        </td>
                        {% endif %}
                        {% if 'error' in current_tab_config.columns %}
                        <td class="px-3 py-2 text-gray-500" style="font-size:.85rem;">
                            {% if row.error %}
                            <button type="button"
                                    @click="showError('{{ row.id }}', `{{ row.error|escapejs }}`)"
                                    style="text-align:left;color:#ef4444;text-decoration:underline;text-decoration-style:dotted;cursor:pointer;background:none;border:none;font-size:.85rem;max-width:18rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;"
                                    title="{{ row.error }}">
                                {{ row.error|truncatechars:60 }}
                            </button>
                            {% else %}<span class="text-gray-300">—</span>{% endif %}
                        </td>
                        {% endif %}
                        {% if 'size' in current_tab_config.columns %}
                        <td class="px-3 py-2 text-gray-500" style="font-size:.85rem;">
                            {% if row.extra.formatted_size %}{{ row.extra.formatted_size }}{% else %}<span class="text-gray-300">—</span>{% endif %}
                        </td>
                        {% endif %}
                        <td class="px-3 py-2 text-gray-400 whitespace-nowrap" style="font-size:.8rem;">{{ row.updated_at|timesince }} {% trans "ago" %}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="px-6 py-12 text-center text-gray-400 text-sm">{% trans "No items match this filter." %}</div>
        {% endif %}

        {% comment %}pages table removed — unified table above handles all types{% endcomment %}
        {% if False %}
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
                    <tr>
                        <th class="px-3 py-3 w-8">
                            <input type="checkbox" class="rounded text-blue-600"
                                   @change="toggleAll($event.target.checked, allIds)"
                                   :checked="allIds.length > 0 && selectedIds.length === allIds.length">
                        </th>
                        <th class="px-3 py-3 text-left">ID</th>
                        <th class="px-3 py-3 text-left">{% trans "Title / URL" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Status" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Retries" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Error" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Updated" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    {% for pg in page_obj.object_list %}
                    <tr class="hover:bg-gray-50" :class="{'bg-blue-50': selectedIds.includes('{{ pg.id }}') }">
                        <td class="px-3 py-2">
                            <input type="checkbox" class="rounded text-blue-600"
                                   value="{{ pg.id }}"
                                   @change="toggle('{{ pg.id }}')"
                                   :checked="selectedIds.includes('{{ pg.id }}')">
                        </td>
                        <td class="px-3 py-2 font-mono text-gray-400" style="font-size:.75rem;">{{ pg.id }}</td>
                        <td class="px-3 py-2 max-w-xs">
                            <a href="{% url 'page-detail' pg.pk %}"
                               class="text-blue-600 hover:underline block truncate max-w-xs"
                               style="font-size:.85rem;"
                               title="{{ pg.url }}">
                                {{ pg.title|default:pg.url|truncatechars:55 }}
                            </a>
                        </td>
                        <td class="px-3 py-2">
                            <span style="display:inline-flex;align-items:center;padding:.15rem .55rem;border-radius:9999px;font-size:.75rem;font-weight:500;
                                {% if pg.process_status == 'completed' %}background:#dcfce7;color:#166534;
                                {% elif pg.process_status == 'failed' %}background:#fee2e2;color:#991b1b;
                                {% elif pg.process_status == 'processing' %}background:#dbeafe;color:#1e40af;
                                {% else %}background:#fef9c3;color:#854d0e;{% endif %}">
                                {{ pg.process_status }}
                            </span>
                        </td>
                        <td class="px-3 py-2 text-gray-500" style="font-size:.85rem;">{{ pg.retry_count }}/3</td>
                        <td class="px-3 py-2 text-gray-500" style="font-size:.85rem;">
                            {% if pg.error_message %}
                            <button type="button"
                                    @click="showError('{{ pg.id }}', `{{ pg.error_message|escapejs }}`)"
                                    style="text-align:left;color:#ef4444;text-decoration:underline;text-decoration-style:dotted;cursor:pointer;background:none;border:none;font-size:.85rem;max-width:18rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display:block;"
                                    title="{{ pg.error_message }}">
                                {{ pg.error_message|truncatechars:60 }}
                            </button>
                            {% else %}<span class="text-gray-300">—</span>{% endif %}
                        </td>
                        <td class="px-3 py-2 text-gray-400 whitespace-nowrap" style="font-size:.8rem;">{{ pg.updated_at|timesince }} {% trans "ago" %}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="px-6 py-12 text-center text-gray-400 text-sm">{% trans "No pages match this filter." %}</div>
        {% endif %}

        {% comment %}image_imports table removed — unified table above handles all types{% endcomment %}
        {% if False %}<!-- image_imports -->
        {% if page_obj.object_list %}
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-gray-50 text-xs text-gray-500 uppercase tracking-wide">
                    <tr>
                        <th class="px-3 py-3 w-8">
                            <input type="checkbox" class="rounded text-blue-600"
                                   @change="toggleAll($event.target.checked, allIds)"
                                   :checked="allIds.length > 0 && selectedIds.length === allIds.length">
                        </th>
                        <th class="px-3 py-3 text-left">ID</th>
                        <th class="px-3 py-3 text-left">{% trans "Filename" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Source URL" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Status" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Size" %}</th>
                        <th class="px-3 py-3 text-left">{% trans "Updated" %}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    {% for imp in page_obj.object_list %}
                    <tr class="hover:bg-gray-50" :class="{'bg-blue-50': selectedIds.includes('{{ imp.id }}') }">
                        <td class="px-3 py-2">
                            <input type="checkbox" class="rounded text-blue-600"
                                   value="{{ imp.id }}"
                                   @change="toggle('{{ imp.id }}')"
                                   :checked="selectedIds.includes('{{ imp.id }}')">
                        </td>
                        <td class="px-3 py-2 font-mono text-gray-400" style="font-size:.7rem;">{{ imp.id|truncatechars:12 }}</td>
                        <td class="px-3 py-2 max-w-xs">
                            <a href="{{ imp.download_url }}" class="text-blue-600 hover:underline block truncate max-w-xs" style="font-size:.85rem;" title="{{ imp.name }}">
                                {{ imp.name|truncatechars:40 }}
                            </a>
                        </td>
                        <td class="px-3 py-2 max-w-xs">
                            <a href="{{ imp.source_url }}" target="_blank" rel="noopener"
                               class="text-gray-400 hover:text-blue-500 block truncate max-w-xs" style="font-size:.8rem;" title="{{ imp.source_url }}">
                                {{ imp.source_url|truncatechars:50 }}
                            </a>
                        </td>
                        <td class="px-3 py-2">
                            {% if imp.size > 0 %}
                            <span style="display:inline-flex;align-items:center;padding:.15rem .55rem;border-radius:9999px;font-size:.75rem;font-weight:500;background:#dcfce7;color:#166534;">
                                {% trans "done" %}
                            </span>
                            {% else %}
                            <span style="display:inline-flex;align-items:center;padding:.15rem .55rem;border-radius:9999px;font-size:.75rem;font-weight:500;background:#fef9c3;color:#854d0e;">
                                {% trans "pending" %}
                            </span>
                            {% endif %}
                        </td>
                        <td class="px-3 py-2 text-gray-500" style="font-size:.85rem;">
                            {% if imp.size > 0 %}{{ imp.formatted_size }}{% else %}<span class="text-gray-300">—</span>{% endif %}
                        </td>
                        <td class="px-3 py-2 text-gray-400 whitespace-nowrap" style="font-size:.8rem;">{{ imp.updated_at|timesince }} {% trans "ago" %}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
        {% else %}
        <div class="px-6 py-12 text-center text-gray-400 text-sm">{% trans "No image imports match this filter." %}</div>
        {% endif %}
        {% endif %}
        {% endif %}

        <!-- Pagination -->
        {% if page_obj.has_other_pages %}
        <div class="px-4 py-3 border-t border-gray-100 flex items-center justify-between text-sm">
            <span class="text-gray-500 text-xs">
                {% trans "Showing" %} {{ page_obj.start_index }}–{{ page_obj.end_index }}
                {% trans "of" %} {{ page_obj.paginator.count }}
            </span>
            <div class="flex gap-1">
                {% if page_obj.has_previous %}
                <a href="?tab={{ tab }}&status={{ status_filter }}&page={{ page_obj.previous_page_number }}"
                   class="px-2.5 py-1 rounded text-xs bg-gray-100 hover:bg-gray-200 text-gray-600">‹ {% trans "Prev" %}</a>
                {% endif %}
                {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                    <span class="px-2.5 py-1 rounded text-xs font-medium" style="background:#1d4ed8;color:#fff">{{ num }}</span>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <a href="?tab={{ tab }}&status={{ status_filter }}&page={{ num }}"
                       class="px-2.5 py-1 rounded text-xs bg-gray-100 hover:bg-gray-200 text-gray-600">{{ num }}</a>
                    {% endif %}
                {% endfor %}
                {% if page_obj.has_next %}
                <a href="?tab={{ tab }}&status={{ status_filter }}&page={{ page_obj.next_page_number }}"
                   class="px-2.5 py-1 rounded text-xs bg-gray-100 hover:bg-gray-200 text-gray-600">{% trans "Next" %} ›</a>
                {% endif %}
            </div>
        </div>
        {% endif %}
    </div>

    <!-- Error Detail Modal -->
    <div x-show="errorModal.open" x-cloak
         class="fixed inset-0 z-50 flex items-center justify-center"
         @keydown.escape.window="errorModal.open = false">
        <div class="absolute inset-0 bg-black/40" @click="errorModal.open = false"></div>
        <div class="relative bg-white rounded-xl shadow-2xl w-full max-w-2xl mx-4 overflow-hidden">
            <div class="flex items-center justify-between px-5 py-4 border-b border-gray-100">
                <h3 class="text-base font-semibold text-gray-800">{% trans "Error Details" %}</h3>
                <button @click="errorModal.open = false" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                </button>
            </div>
            <div class="px-5 py-4">
                <p class="text-xs text-gray-400 mb-2">{% trans "Job ID:" %} <span class="font-mono" x-text="errorModal.id"></span></p>
                <pre class="bg-gray-900 text-red-300 text-xs p-4 rounded-lg overflow-auto max-h-80 whitespace-pre-wrap break-all font-mono" x-text="errorModal.error"></pre>
            </div>
            <div class="px-5 py-3 border-t border-gray-100 flex justify-end">
                <button @click="errorModal.open = false"
                        style="background:#6b7280;color:#fff;padding:.35rem 1rem;border-radius:.375rem;font-size:.8rem;cursor:pointer;">
                    {% trans "Close" %}
                </button>
            </div>
        </div>
    </div>

</div>

{{ all_ids|json_script:"jobs-all-ids" }}
{{ scheduled_jobs|json_script:"scheduled-jobs-data" }}
{{ bulk_actions|json_script:"bulk-actions-data" }}

<script>
function jobsManager() {
    return {
        selectedIds: [],
        allIds: JSON.parse(document.getElementById('jobs-all-ids').textContent),
        errorModal: { open: false, id: '', error: '' },
        tab: '{{ tab }}',
        scheduledJobs: JSON.parse(document.getElementById('scheduled-jobs-data')?.textContent || '[]'),
        schedulerFilter: 'all',
        bulkActionsMap: JSON.parse(document.getElementById('bulk-actions-data').textContent),
        get schedulerJobTypes() {
            return [...new Set(this.scheduledJobs.map(j => j.name))].sort();
        },
        get filteredScheduledJobs() {
            if (this.schedulerFilter === 'all') return this.scheduledJobs;
            return this.scheduledJobs.filter(j => j.name === this.schedulerFilter);
        },

        init() {},

        toggle(id) {
            const idx = this.selectedIds.indexOf(id);
            if (idx === -1) this.selectedIds.push(id);
            else this.selectedIds.splice(idx, 1);
        },

        toggleAll(checked, ids) {
            this.selectedIds = checked ? [...ids] : [];
        },

        clearSelection() {
            this.selectedIds = [];
        },

        showError(id, error) {
            this.errorModal = { open: true, id, error };
        },

        bulkAction(type) {
            if (this.selectedIds.length === 0) return;
            const actionName = this.bulkActionsMap[type];
            if (!actionName) return;
            if (type === 'delete' && !confirm(`Delete ${this.selectedIds.length} item(s)?`)) return;
            document.getElementById('bulk-action-input').value = actionName;
            document.getElementById('bulk-ids-input').value = this.selectedIds.join(',');
            document.getElementById('bulk-form').submit();
        },
    };
}
</script>
{% endblock %}
