{% extends 'admin/base.html' %}
{% block title %}{{ t('plugins.title') }}{% endblock %}
{% block content %}

<div class="page-header page-header--with-action">
    <div class="page-header__content">
        <h2>🧩 {{ t('plugins.title') }}</h2>
    </div>
    {# height-keeper: the sticky bar is button-high on every page
       (posts-list standard); this page has no header action #}
    <span class="btn header-spacer" aria-hidden="true">&nbsp;</span>
</div>
<div class="page-help">{{ t('plugins.subtitle') }}</div>

{% if not core_licensed %}
<div class="settings-section">
    <p>🔑 {{ t('plugins.core_license_note') }}</p>
</div>
{% endif %}

{% if restart_in_progress %}
<div class="settings-section">
    <p>⏳ {{ t('plugins.restart_in_progress') }}</p>
</div>
<script>
/* Poll until the server is reachable again, THEN reload — a blind reload
   lands mid-restart on a connection error and scares the user. */
(function () {
    /* The restart window is live NOW: any action submitted into it gets a
       502 from the dying worker. Disable every action on the page until
       the poll below brings the fresh process back. */
    document.querySelectorAll('button, input[type="submit"], input[type="file"]')
        .forEach(function (el) { el.disabled = true; });

    function ping() {
        fetch(window.location.href, {cache: 'no-store', credentials: 'same-origin'})
            .then(function (r) {
                if (r.ok) { window.location.reload(); }
                else { setTimeout(ping, 2000); }
            })
            .catch(function () { setTimeout(ping, 2000); });
    }
    setTimeout(ping, 5000);
})();
</script>
{% elif restart_pending %}
<div class="settings-section">
    <p>🔄 {{ t('plugins.restart_required') }}</p>
    <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_restart') }}" style="display:inline">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <button type="submit" class="btn btn-primary btn-sm">{{ t('plugins.restart_now') }}</button>
    </form>
</div>
{% endif %}

{# ── Install from ZIP ──────────────────────────────────────────────── #}
<div class="settings-section">
    <h3>⬆️ {{ t('plugins.upload_title') }}</h3>
    <p class="help-text">{{ t('plugins.upload_help') }}</p>
    <p class="help-text">⚠️ {{ t('plugins.third_party_warning') }}</p>
    <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_install') }}" enctype="multipart/form-data"
          style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-top:8px;">
        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
        <input type="file" name="plugin_zip" accept=".zip" required class="form-control input-medium">
        <button type="submit" class="btn btn-primary" {% if not core_licensed %}disabled{% endif %}>{{ t('plugins.install_btn') }}</button>
    </form>
</div>

{# ── Available plugins (from the update server) ────────────────────── #}
<div class="settings-section">
    <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;">
        <h3 style="margin:0;">🧩 {{ t('plugins.available_title') }}{% if catalog %} <span class="help-text" style="font-weight:400;">({{ catalog|length }})</span>{% endif %}</h3>
        <div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
            {% if catalog|length > 3 %}
            <input type="text" id="pluginCatalogSearch" placeholder="🔍 {{ t('plugins.catalog_search') }}" autocomplete="off" class="input-medium">
            {% endif %}
            <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_catalog_refresh') }}" style="display:inline">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <button type="submit" class="btn btn-secondary btn-sm" {% if not core_licensed %}disabled{% endif %}>🔄 {{ t('plugins.catalog_refresh') }}</button>
            </form>
        </div>
    </div>
    <p class="help-text" style="margin-top:8px;">{{ t('plugins.available_help') }}</p>

    {% if not catalog %}
    <p class="help-text">{{ t('plugins.catalog_empty') }}</p>
    {% endif %}

    <div id="pluginCatalog">
    {% for c in catalog %}
    <div class="info-card plugin-catalog-card" data-catalog-name="{{ (c.name ~ ' ' ~ c.id ~ ' ' ~ c.description)|lower|e }}"
         style="margin-bottom:12px;{% if loop.index > 6 %} display:none;{% endif %}" {% if loop.index > 6 %}data-catalog-overflow="1"{% endif %}>
        <div style="display:flex; flex-wrap:wrap; align-items:center; gap:8px;">
            {% if c.icon and update_server_url %}
            <img src="{{ update_server_url }}/api/v1/plugins/icon/{{ c.id }}" alt="" width="28" height="28" style="border-radius:6px; flex-shrink:0;" loading="lazy">
            {% endif %}
            <strong>{{ c.name }}</strong>
            <span class="help-text">v{{ c.version }}</span>
            {% if c.requires_plugin_license %}
            <span class="badge-pending">🔑 {{ t('plugins.catalog_license') }}</span>
            {% else %}
            <span class="badge-confirmed">{{ t('plugins.catalog_free') }}</span>
            {% endif %}
        </div>
        {% if c.description %}
        <p class="help-text" style="margin:8px 0 0;">{{ c.description }}</p>
        {% endif %}
        {% if c.min_cms_version %}
        <p class="help-text" style="margin:4px 0 0;">{{ t('plugins.catalog_requires_cms', version=c.min_cms_version) }}</p>
        {% endif %}
        {% if c.requires_plugin_license and c.trial_days %}
        <p class="help-text" style="margin:4px 0 0;">🎁 {{ t('plugins.catalog_trial', days=c.trial_days) }}</p>
        {% endif %}
        <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_install_from_server', plugin_id=c.id) }}"
              style="display:flex; gap:8px; flex-wrap:wrap; align-items:center; margin-top:10px;">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            {% if c.requires_plugin_license %}
            <input type="text" name="license_key" class="form-control input-medium" placeholder="{{ t('plugins.license_key') }}" autocomplete="off">
            {% endif %}
            <button type="submit" class="btn btn-primary btn-sm" {% if not core_licensed %}disabled{% endif %}>⬇️ {{ t('plugins.install_from_server') }}</button>
        </form>
    </div>
    {% endfor %}
    </div>

    {% if catalog|length > 6 %}
    <button type="button" class="btn btn-secondary btn-sm" id="pluginCatalogToggle"
            data-more="{{ t('plugins.show_all', count=catalog|length) }}"
            data-less="{{ t('plugins.show_less') }}">{{ t('plugins.show_all', count=catalog|length) }}</button>
    {% endif %}
</div>

{# ── Installed plugins ─────────────────────────────────────────────── #}
<div class="settings-section">
    <div style="display:flex; align-items:center; justify-content:space-between; gap:12px; flex-wrap:wrap;">
        <h3 style="margin:0;">📦 {{ t('plugins.installed') }}{% if plugins_total %} <span class="help-text" style="font-weight:400;">({{ plugins_total }})</span>{% endif %}</h3>
        {% if plugins %}
        <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_check_updates') }}" style="display:inline">
            <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
            <button type="submit" class="btn btn-secondary btn-sm" {% if not core_licensed %}disabled{% endif %}>🔄 {{ t('plugins.check_updates') }}</button>
        </form>
        {% endif %}
    </div>

    {% if not plugins %}
    <p class="help-text">{{ t('plugins.no_plugins') }}</p>
    {% endif %}

    {% for p in plugins %}
    {% set m = p.manifest %}
    <div class="info-card" style="margin-bottom:12px;">
        <div style="display:flex; flex-wrap:wrap; align-items:center; gap:8px;">
            {% if p.has_icon %}
            <img src="{{ url_for('plugins_admin.admin_plugins_icon', plugin_id=m.id) }}" alt="" width="28" height="28" style="border-radius:6px; flex-shrink:0;">
            {% endif %}
            <strong>{{ m.name }}</strong>
            <span class="help-text">v{{ m.version }}</span>
            {% if m.author %}
            <span class="help-text">
                — {% if m.author_url %}<a href="{{ m.author_url }}" target="_blank" rel="noopener">{{ m.author }}</a>{% else %}{{ m.author }}{% endif %}
            </span>
            {% endif %}
            {% if p.status == 'active' %}
            <span class="badge-active">{{ t('plugins.status_active') }}</span>
            {% elif p.status == 'disabled' %}
            <span class="badge-inactive">{{ t('plugins.status_disabled') }}</span>
            {% elif p.status == 'needs_license' %}
            <span class="badge-pending">{{ t('plugins.status_needs_license') }}</span>
            {% elif p.status == 'needs_core_license' %}
            <span class="badge-pending">{{ t('plugins.status_needs_core_license') }}</span>
            {% elif p.status == 'pending_restart' %}
            <span class="badge-pending">{{ t('plugins.status_pending_restart') }}</span>
            {% else %}
            <span class="badge-inactive">{{ t('plugins.status_error') }}</span>
            {% endif %}
            {% if p.trial_days_left and not p.licensed %}
            <span class="badge-pending">⏳ {{ t('plugins.trial_days_left', days=p.trial_days_left) }}</span>
            {% endif %}
        </div>

        {# Description: a loaded plugin may translate it via the i18n key
           "<id>.description" (same convention as themes.desc_*); the
           manifest's static description is the fallback. #}
        {% set _desc_key = m.id ~ '.description' %}
        {% set _desc = t(_desc_key) %}
        {% if _desc != _desc_key %}
        <p class="help-text" style="margin:8px 0 0;">{{ _desc }}</p>
        {% elif m.description %}
        <p class="help-text" style="margin:8px 0 0;">{{ m.description }}</p>
        {% endif %}

        {% if p.load_error %}
        <p class="help-text" style="margin:8px 0 0; color:var(--adm-error);">⚠️ {{ p.load_error }}</p>
        {% endif %}

        {# Available update from the update server #}
        {% if p.update_info %}
        <div class="info-card" style="margin-top:12px; padding:12px; border:1px solid var(--adm-border);">
            <div style="display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
                <span class="badge-pending">⬆️ {{ t('plugins.update_available', version=p.update_info.latest_version) }}</span>
                {% if p.update_info.release_date %}
                <span class="help-text">{{ p.update_info.release_date }}</span>
                {% endif %}
            </div>
            {% if p.update_info.changelog %}
            <p class="help-text" style="margin:8px 0 0; white-space:pre-line;"><strong>{{ t('plugins.changelog') }}:</strong>
{{ p.update_info.changelog }}</p>
            {% endif %}
            <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_update', plugin_id=m.id) }}" style="margin-top:10px;">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <button type="submit" class="btn btn-primary btn-sm" {% if not core_licensed %}disabled{% endif %}>{{ t('plugins.update_now', version=p.update_info.latest_version) }}</button>
            </form>
        </div>
        {% endif %}

        {# License block — only for plugins sold with their own key #}
        {% if m.license_required and not p.load_error %}
        <div style="margin-top:12px;">
            {% if p.licensed %}
            <span class="badge-confirmed">🔑 {{ t('plugins.license_valid') }}</span>
            {% else %}
            <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_license', plugin_id=m.id) }}" style="display:flex; gap:8px; flex-wrap:wrap; align-items:center;">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <input type="text" name="license_key" class="form-control input-medium" placeholder="{{ t('plugins.license_key') }}" autocomplete="off">
                <button type="submit" class="btn btn-primary btn-sm">{{ t('plugins.activate_license') }}</button>
            </form>
            {% if p.has_stored_key %}
            <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_license_recheck', plugin_id=m.id) }}" style="margin-top:8px;">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <button type="submit" class="btn btn-secondary btn-sm">🔄 {{ t('plugins.recheck_license') }}</button>
            </form>
            {% endif %}
            {% endif %}
        </div>
        {% endif %}

        <div class="btn-group" style="margin-top:12px; display:flex; gap:8px; flex-wrap:wrap;">
            {% if not p.load_error %}
            <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_toggle', plugin_id=m.id) }}" style="display:inline">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                {% if p.enabled %}
                <button type="submit" class="btn btn-secondary btn-sm">{{ t('plugins.disable') }}</button>
                {% else %}
                <button type="submit" class="btn btn-primary btn-sm" {% if not core_licensed %}disabled{% endif %}>{{ t('plugins.enable') }}</button>
                {% endif %}
            </form>
            {% endif %}
            <form method="POST" action="{{ url_for('plugins_admin.admin_plugins_delete', plugin_id=m.id) }}" style="display:inline"
                  data-confirm="{{ t('plugins.delete_confirm') }}" data-confirm-danger data-confirm-ok="{{ t('plugins.delete') }}">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                <button type="submit" class="btn btn-danger btn-sm">{{ t('plugins.delete') }}</button>
            </form>
        </div>
    </div>
    {% endfor %}

    {% if plugins_pages and plugins_pages > 1 %}
    <div class="pagination" style="margin-top:12px;">
        {% if plugins_page > 1 %}
        <a href="{{ url_for('plugins_admin.admin_plugins', p=plugins_page-1) }}">{{ t('pagination.prev') }}</a>
        {% endif %}
        {% for pnum in range(1, plugins_pages + 1) %}
            {% if pnum == plugins_page %}
            <span class="current">{{ pnum }}</span>
            {% else %}
            <a href="{{ url_for('plugins_admin.admin_plugins', p=pnum) }}">{{ pnum }}</a>
            {% endif %}
        {% endfor %}
        {% if plugins_page < plugins_pages %}
        <a href="{{ url_for('plugins_admin.admin_plugins', p=plugins_page+1) }}">{{ t('pagination.next') }}</a>
        {% endif %}
    </div>
    {% endif %}
</div>

<script>
(function () {
    'use strict';
    var search = document.getElementById('pluginCatalogSearch');
    var toggle = document.getElementById('pluginCatalogToggle');
    var cards = Array.prototype.slice.call(
        document.querySelectorAll('.plugin-catalog-card'));
    var expanded = false;

    function apply() {
        var q = search ? search.value.trim().toLowerCase() : '';
        cards.forEach(function (card) {
            var overflow = card.hasAttribute('data-catalog-overflow');
            var match = !q ||
                (card.getAttribute('data-catalog-name') || '').indexOf(q) !== -1;
            /* While searching, the cap is lifted — a hit must never hide. */
            var show = q ? match : (expanded || !overflow);
            card.style.display = show ? '' : 'none';
        });
        if (toggle) toggle.style.display = search && search.value.trim() ? 'none' : '';
    }

    if (search) search.addEventListener('input', apply);
    if (toggle) toggle.addEventListener('click', function () {
        expanded = !expanded;
        toggle.textContent = expanded
            ? toggle.getAttribute('data-less')
            : toggle.getAttribute('data-more');
        apply();
    });
})();
</script>

{% endblock %}
