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

{% block page_title %}{% trans "Sell Materials to Hub" %}{% 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/blueprints.css' %}">
<link rel="stylesheet" href="{% static 'indy_hub/css/material_exchange.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-stretch justify-content-between gap-3">
                <div class="d-flex flex-column h-100">
                    <h2 class="h3 mb-1">
                        <i class="fas fa-hand-holding-usd me-2"></i>
                        {% trans "Sell Materials to Hub" %}
                    </h2>
                    <p class="description">{% trans "Sell your materials to the Hub" %}</p>
                    <div class="mt-auto">
                        <span class="badge rounded-pill bg-info-subtle text-info border fs-6">
                            <i class="fas fa-tags me-1"></i>{% trans "Pricing Formula" %}:
                            {% if config.sell_markup_base == 'sell' %}
                                {% trans "Jita Sell Price" %}
                            {% else %}
                                {% trans "Jita Buy Price" %}
                            {% endif %}
                            {% if config.sell_markup_percent > 0 %}
                                +{{ config.sell_markup_percent }}%
                            {% elif config.sell_markup_percent < 0 %}
                                {{ config.sell_markup_percent }}%
                            {% else %}
                                ({% trans "no markup" %})
                            {% endif %}
                        </span>
                    </div>
                </div>
                <div class="d-flex gap-2 align-self-start">
                    <a href="{% url 'indy_hub:material_exchange_index' %}" class="btn btn-outline-light">
                        <i class="fas fa-arrow-left me-1"></i>{% trans "Back to Hub" %}
                    </a>
                </div>
            </div>
            <i class="fas fa-hand-holding-usd header-bg"></i>
        </div>

        {% if assets_refreshing %}
        <div class="d-flex flex-column align-items-center justify-content-center py-5">
            <svg width="56" height="56" viewBox="0 0 24 24" aria-hidden="true" class="text-info">
                <g stroke="currentColor" fill="none" stroke-width="1" stroke-linecap="round">
                    <circle cx="12" cy="12" r="10">
                        <animate attributeName="stroke-dasharray" dur="1.5s" calcMode="spline" values="0 150;42 150;42 150;42 150" keyTimes="0;0.475;0.95;1" keySplines="0.42,0,0.58,1;0.42,0,0.58,1;0.42,0,0.58,1" repeatCount="indefinite" />
                        <animate attributeName="stroke-dashoffset" dur="1.5s" calcMode="spline" values="0;-16;-59;-59" keyTimes="0;0.475;0.95;1" keySplines="0.42,0,0.58,1;0.42,0,0.58,1;0.42,0,0.58,1" repeatCount="indefinite" />
                    </circle>
                    <animateTransform attributeName="transform" type="rotate" dur="2s" values="0 12 12;360 12 12" repeatCount="indefinite" />
                </g>
            </svg>
            <div class="mt-3 text-muted">{% trans "Loading your asset inventory." %}</div>
        </div>
        {% endif %}

        <div class="{% if assets_refreshing %}d-none{% endif %}">
            <div class="me-info-bar" role="status">
                <i class="fas fa-clock" aria-hidden="true"></i>
                <div class="me-info-bar-body">
                    <div class="me-info-bar-title">
                        {% trans "Last update" %}:
                        {% if sell_last_update %}
                            {% with sell_utc=sell_last_update|timezone:"UTC" %}
                                {{ sell_utc|date:"Y-m-d H:i" }} EVE
                                <span class="text-muted">
                                    / <span class="js-local-time" data-utc="{{ sell_utc|date:'c' }}">{{ sell_utc|date:"Y-m-d H:i" }}</span> {% trans "Local" %}
                                </span>
                            {% endwith %}
                        {% else %}
                            {% trans "Never" %}
                        {% endif %}
                    </div>
                    <div class="me-info-bar-sub">
                        {% if sell_next_refresh_minutes == 0 %}
                            {% trans "Auto-refresh will run on the next page open." %}
                        {% elif sell_next_refresh_minutes %}
                            {% blocktrans with minutes=sell_next_refresh_minutes %}Auto-refresh runs on page open in about {{ minutes }} minute(s).{% endblocktrans %}
                        {% else %}
                            {% trans "Auto-refresh runs on page open once data is older than 60 minutes." %}
                        {% endif %}
                    </div>
                </div>
            </div>

            <div class="me-instruction-chip" role="status">
                <i class="fas fa-exclamation-circle" aria-hidden="true"></i>
                <div>
                    <div class="me-instruction-title">{% trans "Enter the quantities you want to sell." %}</div>
                    <div class="me-instruction-sub">{% trans "Make sure you have the items in your hangar." %}</div>
                </div>
            </div>

            {% if sell_assets_progress.error == "missing_assets_scope" %}
            <div class="glass-panel p-4 mb-4">
                <div class="alert alert-danger mt-3 mb-0">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <i class="fas fa-exclamation-triangle me-2"></i>
                            {% trans "Missing assets token: add the ESI assets scope to load your assets." %}
                        </div>
                        <a class="btn btn-outline-light btn-sm" href="{% url 'indy_hub:authorize_assets' %}?next={{ request.get_full_path|urlencode }}">
                            <i class="fas fa-key me-1"></i>{% trans "Add assets token" %}
                        </a>
                    </div>
                </div>
            </div>
            {% endif %}

            {% if sell_assets_progress.error == "esi_down" %}
            <div class="alert alert-warning d-flex align-items-start gap-2 mb-3" role="status">
                <i class="fas fa-cloud-bolt mt-1" aria-hidden="true"></i>
                <div>
                    <div class="fw-semibold">{% trans "ESI is temporarily unavailable. Using cached assets." %}</div>
                    {% if sell_assets_progress.retry_after_minutes %}
                    <small class="text-muted">
                        {% blocktrans with minutes=sell_assets_progress.retry_after_minutes %}Retry in about {{ minutes }} minute(s).{% endblocktrans %}
                    </small>
                    {% endif %}
                </div>
            </div>
            {% endif %}

            {% if sell_assets_progress.error == "no_assets_fetched" %}
            <div class="alert alert-warning d-flex align-items-start gap-2 mb-3" role="status">
                <i class="fas fa-info-circle mt-1" aria-hidden="true"></i>
                <div>
                    <div class="fw-semibold">{% trans "Assets refresh completed, but no items were returned." %}</div>
                    <small class="text-muted">{% trans "Try again later or verify your assets scope." %}</small>
                </div>
            </div>
            {% endif %}
        </div>

        {% if materials %}
        <div class="row g-4">
            <div class="col-lg-8">
                <div class="glass-panel p-4">
                    <h5 class="mb-4">
                        <i class="fas fa-warehouse me-2"></i>
                        {% trans "Your Materials at" %} {{ config.structure_name }}
                    </h5>
                    {% if character_tabs %}
                    <div class="me-character-tabs mb-3">
                        {% if character_tabs|length > 1 %}
                        <div class="d-flex flex-wrap align-items-center gap-3 p-3 rounded-3 bg-body-tertiary border">
                            <img
                                src="{% if active_character_tab_data %}{{ active_character_tab_data.portrait_url }}{% else %}https://images.evetech.net/characters/{{ character_tabs.0.id }}/portrait?size=128{% endif %}"
                                alt="{% if active_character_tab_data %}{{ active_character_tab_data.name }}{% else %}{{ character_tabs.0.name }}{% endif %}"
                                class="rounded-circle flex-shrink-0"
                                width="64"
                                height="64">
                            <div class="flex-grow-1">
                                <div class="small text-body-secondary">{% trans "Selected character" %}</div>
                                <div class="h5 mb-0 text-body d-flex align-items-center gap-2 flex-wrap">
                                    <span>{% if active_character_tab_data %}{{ active_character_tab_data.name }}{% else %}{{ character_tabs.0.name }}{% endif %}</span>
                                    <span class="badge rounded-pill bg-secondary">{% if active_character_tab_data %}{{ active_character_tab_data.item_count }}{% else %}{{ character_tabs.0.item_count }}{% endif %}</span>
                                </div>
                            </div>
                            <div class="ms-auto w-100 w-md-auto">
                                <label for="sellCharacterSelect" class="form-label small text-body-secondary mb-1">{% trans "Switch character" %}</label>
                                <div class="input-group input-group-sm">
                                    <span class="input-group-text"><i class="fas fa-user"></i></span>
                                    <select
                                        id="sellCharacterSelect"
                                        class="form-select"
                                        onchange="if (this.value) { window.location.href = this.value; }"
                                        aria-label="{% trans 'Select character' %}">
                                        {% for tab in character_tabs %}
                                        <option value="{{ tab.url }}" {% if active_character_tab == tab.id %}selected{% endif %}>
                                            {{ tab.name }} ({{ tab.item_count }})
                                        </option>
                                        {% endfor %}
                                    </select>
                                </div>
                            </div>
                        </div>
                        {% else %}
                        <ul class="nav nav-pills flex-wrap gap-2">
                            {% for tab in character_tabs %}
                            <li class="nav-item">
                                <a class="nav-link {% if active_character_tab == tab.id %}active{% endif %}" href="{{ tab.url }}">
                                    {{ tab.name }}
                                    <span class="badge rounded-pill bg-secondary ms-1">{{ tab.item_count }}</span>
                                </a>
                            </li>
                            {% endfor %}
                        </ul>
                        {% endif %}
                    </div>
                    {% endif %}
                    <form method="post" id="sellForm">
                        {% csrf_token %}
                        <div class="d-flex align-items-stretch gap-3 mb-3">
                            <div class="d-flex flex-column justify-content-center" role="radiogroup" aria-label="{% trans 'Search mode' %}">
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="sellSearchMode" id="sellSearchModeItem" value="item" checked>
                                    <label class="form-check-label" for="sellSearchModeItem">{% trans "Item" %}</label>
                                </div>
                                <div class="form-check">
                                    <input class="form-check-input" type="radio" name="sellSearchMode" id="sellSearchModeCategory" value="category">
                                    <label class="form-check-label" for="sellSearchModeCategory">{% trans "Category" %}</label>
                                </div>
                            </div>
                            <div class="input-group">
                                <span class="input-group-text"><i class="fas fa-search"></i></span>
                                <input
                                    type="text"
                                    id="sellSearchInput"
                                    class="form-control"
                                    placeholder="{% trans 'Search by item or category' %}"
                                    aria-label="{% trans 'Search by item or category' %}">
                            </div>
                        </div>
                        <div class="table-responsive">
                            <table class="table table-hover stock-table align-middle">
                                <thead>
                                    <tr>
                                        <th class="stock-col-icon"></th>
                                        <th>{% trans "Item" %}</th>
                                        <th class="text-end">{% trans "You Own" %}</th>
                                        <th class="text-end">{% trans "Unit Price" %}</th>
                                        <th class="text-center stock-col-qty">{% trans "Quantity" %}</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for item in materials %}
                                    <tr class="stock-row"
                                        data-type-id="{{ item.type_id }}"
                                        data-type-name="{{ item.type_name }}"
                                        data-group-name="{{ item.group_name|default:'' }}"
                                        data-unit-price="{{ item.buy_price_from_member|floatformat:2 }}"
                                        data-max-qty="{{ item.user_quantity }}">
                                        <td>
                                            <img
                                                src="{{ item.image_url }}"
                                                alt="{{ item.type_name }}"
                                                class="item-icon">
                                        </td>
                                        <td>
                                            <div class="fw-semibold text-body">{{ item.type_name }}</div>
                                            <div class="small text-body-secondary">{{ item.group_name|default:_('Other') }}</div>
                                        </td>
                                        <td class="text-end">
                                            <span class="badge bg-success">{{ item.user_quantity|intcomma }}</span>
                                        </td>
                                        <td class="text-end text-success fw-semibold">
                                            {{ item.buy_price_from_member|floatformat:2|intcomma }} ISK
                                        </td>
                                        <td class="text-center">
                                            <div class="qty-cell">
                                                <div class="qty-input-row">
                                                    <input
                                                        type="number"
                                                        name="qty_{{ item.type_id }}"
                                                        id="qty-{{ item.type_id }}"
                                                        class="form-control qty-input"
                                                        min="0"
                                                        max="{{ item.user_quantity }}"
                                                        value="0"
                                                        data-type-id="{{ item.type_id }}"
                                                        data-max="{{ item.user_quantity }}">
                                                    <div class="qty-btns" role="group" aria-label="{% trans 'Quantity shortcuts' %}">
                                                        <button type="button" class="btn btn-secondary btn-sm qty-btn" data-action="zero" title="{% trans 'Zero' %}" aria-label="{% trans 'Zero' %}">
                                                            <i class="fas fa-ban" aria-hidden="true"></i>
                                                        </button>
                                                        <button type="button" class="btn btn-secondary btn-sm qty-btn" data-action="max">{% trans "Max" %}</button>
                                                    </div>
                                                </div>
                                                <div class="qty-error" id="error-{{ item.type_id }}">
                                                    {% trans "Max:" %} {{ item.user_quantity|intcomma }}
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                        <div id="sellSearchEmpty" class="alert alert-warning mt-3 d-none mb-0">
                            <i class="fas fa-search me-2"></i>
                            {% trans "No matching items for your search." %}
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="invoice-panel">
                    <div class="glass-panel p-4">
                        <h5 class="mb-3">
                            <i class="fas fa-receipt me-2"></i>{% trans "Sell Summary" %}
                        </h5>
                        <div id="invoiceContent">
                            <div class="empty-invoice">
                                <i class="fas fa-hand-holding-usd fa-3x mb-3 opacity-25"></i>
                                <p class="mb-0">{% trans "Enter quantities to see your payout" %}</p>
                            </div>
                        </div>
                        <div id="invoiceItems" class="d-none">
                            <div id="itemsList"></div>
                            <div class="invoice-total">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="fw-bold">{% trans "Total Payout" %}</span>
                                    <span class="h4 mb-0 text-success" id="totalAmount">0 ISK</span>
                                </div>
                                <button type="submit" form="sellForm" class="btn btn-success w-100 mt-3">
                                    <i class="fas fa-paper-plane me-2"></i>{% trans "Create Sell Order" %}
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        {% else %}
        {% if not assets_refreshing %}
        <div class="glass-panel p-4">
            <div class="alert alert-warning mb-0">
                <i class="fas fa-exclamation-triangle me-2"></i>
                {% trans "No materials available for selling. Please contact an admin." %}
            </div>
        </div>
        {% endif %}
        {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const cleanUrl = new URL(window.location.href);
    if (cleanUrl.searchParams.get('refreshed') === '1') {
        cleanUrl.searchParams.delete('refreshed');
        window.history.replaceState({}, document.title, cleanUrl.toString());
    }

    const qtyInputs = document.querySelectorAll('.qty-input');
    const sellSearchInput = document.getElementById('sellSearchInput');
    const sellSearchModeInputs = document.querySelectorAll('input[name="sellSearchMode"]');
    const stockRows = document.querySelectorAll('.stock-row');

    const sellSearchPlaceholderByMode = {
        item: '{% trans "Search item" %}',
        category: '{% trans "Search category" %}'
    };

    function updateSellSearchPlaceholder() {
        if (!sellSearchInput) {
            return;
        }
        const selectedMode = document.querySelector('input[name="sellSearchMode"]:checked')?.value || 'item';
        const placeholder = sellSearchPlaceholderByMode[selectedMode] || sellSearchPlaceholderByMode.item;
        sellSearchInput.placeholder = placeholder;
        sellSearchInput.setAttribute('aria-label', placeholder);
    }

    function applySellFilter() {
        if (!sellSearchInput) {
            return;
        }

        const query = (sellSearchInput.value || '').trim().toLowerCase();
        const selectedMode = document.querySelector('input[name="sellSearchMode"]:checked')?.value || 'item';
        let visibleCount = 0;

        stockRows.forEach(row => {
            const typeName = (row.dataset.typeName || '').toLowerCase();
            const groupName = (row.dataset.groupName || '').toLowerCase();
            const matches = !query || (selectedMode === 'category' ? groupName.includes(query) : typeName.includes(query));
            row.classList.toggle('d-none', !matches);
            if (matches) {
                visibleCount += 1;
            }
        });

        const emptyState = document.getElementById('sellSearchEmpty');
        if (emptyState) {
            emptyState.classList.toggle('d-none', visibleCount > 0);
        }
    }

    if (sellSearchInput) {
        sellSearchInput.addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
            }
        });
        sellSearchInput.addEventListener('input', applySellFilter);
        sellSearchModeInputs.forEach(input => input.addEventListener('change', () => {
            updateSellSearchPlaceholder();
            applySellFilter();
        }));
        updateSellSearchPlaceholder();
        applySellFilter();
    }

    document.addEventListener('click', function(event) {
        const button = event.target.closest('.qty-btn');
        if (!button) {
            return;
        }
        const row = button.closest('tr');
        if (!row) {
            return;
        }
        const input = row.querySelector('.qty-input');
        if (!input) {
            return;
        }
        const action = button.dataset.action;
        if (action === 'zero') {
            input.value = 0;
        } else if (action === 'max') {
            input.value = input.dataset.max || 0;
        }
        updateInvoice();
    });

    function formatNumber(num) {
        return new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(num);
    }

    function formatWholeISK(num) {
        return new Intl.NumberFormat('en-US', {
            minimumFractionDigits: 0,
            maximumFractionDigits: 0
        }).format(num);
    }

    function toCents(value) {
        const numeric = Number.parseFloat(value);
        if (!Number.isFinite(numeric)) {
            return 0;
        }
        return Math.round(numeric * 100);
    }

    function checkQuantityLimit(input) {
        const qty = parseInt(input.value) || 0;
        const max = parseInt(input.dataset.max);
        const typeId = input.dataset.typeId;
        const errorDiv = document.getElementById('error-' + typeId);

        if (qty > max) {
            input.classList.add('is-invalid');
            if (errorDiv) {
                errorDiv.style.display = 'block';
            }
            return false;
        } else {
            input.classList.remove('is-invalid');
            if (errorDiv) {
                errorDiv.style.display = 'none';
            }
            return true;
        }
    }

    function updateInvoice() {
        const selectedItems = [];
        let totalCents = 0;

        qtyInputs.forEach(input => {
            const qty = parseInt(input.value) || 0;
            const row = input.closest('tr');

            // Check limit but don't auto-correct during typing
            checkQuantityLimit(input);

            if (qty > 0) {
                const typeId = input.dataset.typeId;
                const typeName = row.dataset.typeName;
                const unitPrice = parseFloat(row.dataset.unitPrice);
                const max = parseInt(input.dataset.max);

                // Use actual qty or max, whichever is lower for calculation
                const effectiveQty = Math.min(qty, max);
                const unitPriceCents = toCents(row.dataset.unitPrice);
                const subtotalCents = unitPriceCents * effectiveQty;
                const subtotal = subtotalCents / 100;

                selectedItems.push({
                    name: typeName,
                    qty: effectiveQty,
                    unitPrice: unitPrice,
                    subtotal: subtotal
                });

                totalCents += subtotalCents;
                row.classList.add('selected');
            } else {
                row.classList.remove('selected');
            }
        });

        // Match server-side `MaterialExchangeSellOrder.total_price`: ceil to whole ISK.
        const total = Math.ceil(totalCents / 100);

        const emptyInvoice = document.getElementById('invoiceContent');
        const invoiceItems = document.getElementById('invoiceItems');
        const itemsList = document.getElementById('itemsList');
        const totalAmount = document.getElementById('totalAmount');

        if (selectedItems.length === 0) {
            emptyInvoice.classList.remove('d-none');
            invoiceItems.classList.add('d-none');
        } else {
            emptyInvoice.classList.add('d-none');
            invoiceItems.classList.remove('d-none');

            let itemsHTML = '';
            selectedItems.forEach(item => {
                itemsHTML += `
                    <div class="invoice-item">
                        <div class="d-flex justify-content-between mb-1">
                            <strong>${item.name}</strong>
                            <span class="text-success fw-semibold">${formatNumber(item.subtotal)} ISK</span>
                        </div>
                        <div class="d-flex justify-content-between small text-muted">
                            <span>${item.qty.toLocaleString()} × ${formatNumber(item.unitPrice)} ISK</span>
                        </div>
                    </div>
                `;
            });

            itemsList.innerHTML = itemsHTML;
            totalAmount.textContent = formatWholeISK(total) + ' ISK';
        }
    }

    qtyInputs.forEach(input => {
        input.addEventListener('input', function() {
            updateInvoice();
        });

        input.addEventListener('blur', function() {
            // Auto-correct on blur
            const qty = parseInt(this.value) || 0;
            const max = parseInt(this.dataset.max);
            if (qty > max) {
                this.value = max;
                updateInvoice();
            }
        });
    });

    // Prevent form submission if any quantity exceeds stock
    const sellForm = document.getElementById('sellForm');
    if (sellForm) {
        sellForm.addEventListener('submit', function(e) {
            let hasError = false;
            const disabledForSubmit = [];
            qtyInputs.forEach(input => {
                const qty = parseInt(input.value) || 0;
                const max = parseInt(input.dataset.max);
                if (qty <= 0) {
                    input.disabled = true;
                    disabledForSubmit.push(input);
                    return;
                }
                if (qty > max) {
                    hasError = true;
                    input.value = max; // Auto-correct
                }
            });

            if (hasError) {
                e.preventDefault();
                disabledForSubmit.forEach(input => {
                    input.disabled = false;
                });
                alert('{% trans "Some quantities exceeded what you own and have been adjusted." %}');
                updateInvoice();
                return false;
            }
        });
    }

    // Initial update (only if invoice elements exist)
    const hasInvoice = document.getElementById('invoiceContent') && document.getElementById('invoiceItems');
    if (hasInvoice) {
        updateInvoice();
    }

    // Live asset refresh progress (per character)
    {% if assets_refreshing %}
    const statusUrl = '{% url "indy_hub:material_exchange_sell_assets_refresh_status" %}';
    console.log('Asset polling enabled. Current assets_refreshing:', {{ assets_refreshing|lower }});
    const lastUpdateNode = document.querySelector('.js-local-time[data-utc]');
    const initialLastUpdate = lastUpdateNode ? lastUpdateNode.getAttribute('data-utc') : null;

    async function pollAssetsProgress() {
        try {
            const resp = await fetch(statusUrl, { headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            if (!resp.ok) {
                return;
            }
            const data = await resp.json();
            console.log('Poll status response:', data);
            const total = parseInt(data.total || 0);
            const done = parseInt(data.done || 0);
            const error = data.error || null;
            const serverLastUpdate = data.last_update || null;

            if (data.running) {
                console.log('Task still running, will poll again in 1s');
                setTimeout(pollAssetsProgress, 1000);
                return;
            }

            // When finished, hide the loading alert and reload to show updated state
            if (data.finished && (!error || error === 'timeout' || error === 'no_assets_fetched')) {
                console.log('Task finished successfully! Reloading page with refreshed=1');
                // Find and hide the assets loading alert
                const alerts = document.querySelectorAll('.alert-warning');
                alerts.forEach(alert => {
                    if (alert.textContent.includes('Loading your asset inventory')) {
                        alert.style.display = 'none';
                    }
                });

                // Guard against loops if the page was already reloaded
                const url = new URL(window.location.href);
                if (url.searchParams.get('refreshed') !== '1') {
                    const initialTime = initialLastUpdate ? Date.parse(initialLastUpdate) : null;
                    const serverTime = serverLastUpdate ? Date.parse(serverLastUpdate) : null;
                    const hasNewTimestamp = serverTime && (!initialTime || serverTime > initialTime);
                    url.searchParams.set('refreshed', '1');
                    setTimeout(
                        () => window.location.replace(url.toString()),
                        hasNewTimestamp ? 300 : 1200
                    );
                }
            } else {
                console.log('Task not yet finished or has error. finished:', data.finished, 'error:', error, 'total:', total, 'done:', done);
            }
        } catch (e) {
            console.error('Poll error:', e);
        }
    }

    pollAssetsProgress();
    {% else %}
    console.log('Asset polling DISABLED - assets_refreshing is False');
    {% endif %}
});
</script>
{% endblock content %}

{% block extra_javascript %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.js-local-time[data-utc]').forEach(function(node) {
        const utcValue = node.getAttribute('data-utc');
        if (!utcValue) {
            return;
        }
        const date = new Date(utcValue);
        if (Number.isNaN(date.getTime())) {
            return;
        }
        const formatted = new Intl.DateTimeFormat(undefined, {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            hour12: false
        }).format(date);
        node.textContent = formatted.replace(/\//g, '-');
    });
});
</script>
{% endblock extra_javascript %}
