{% extends 'admin/base.html' %}

{% block title %}{{ t('dashboard.title') }}{% endblock %}

{% block content %}
<div class="dash">
    
    <!-- Greeting -->
    <div class="dash-greeting">
        <div class="dash-greeting__text">
            <h2>👋 {{ t('dashboard.greeting') }} {{ current_user.display_name or current_user.username }}!</h2>
            <p>{{ t('dashboard.welcome') }}</p>
        </div>
        <span class="dash-version" title="AliothPress">{{ t('dashboard.current_version', version=cms_version) }}</span>
    </div>
    
    <!-- Update Notification (auto-checked, only visible when update available) -->
    {% if current_user.can_access_settings() %}
    <div id="dashUpdateBanner" class="dash-update-banner">
        <div class="dash-update-banner__row">
            <div>
                <div class="dash-update-banner__title" id="dashUpdateTitle">🎉 {{ t('dashboard.update_available') }}</div>
                <div class="dash-update-banner__version" id="dashUpdateVersion"></div>
            </div>
            <button type="button" onclick="dashPerformUpdate()" class="btn btn-primary text-sm whitespace-nowrap" id="dashUpdateBtn">⬆️ {{ t('dashboard.update_now') }}</button>
        </div>
        <div id="dashUpdateChangelog" class="dash-update-banner__changelog"></div>
    </div>
    {% endif %}

    <!-- Quick Actions -->
    <div class="dash-actions">
        <a href="{{ url_for('admin_posts_new') }}" class="dash-action">📝 {{ t('dashboard.new_post') }}</a>
        <a href="{{ url_for('admin_pages_new') }}" class="dash-action">📄 {{ t('dashboard.new_page') }}</a>
        <a href="{{ url_for('admin_media_upload') }}" class="dash-action">🖼️ {{ t('dashboard.upload_image') }}</a>
    </div>
    
    <!-- Stats Grid -->
    <div class="dash-stats">
        <a href="{{ url_for('admin_posts_list') }}" class="dash-stat">
            <span class="dash-stat__icon">📝</span>
            <div class="dash-stat__value">{{ stats.total_posts }}</div>
            <div class="dash-stat__label">{{ t('dashboard.total_posts') }}</div>
        </a>
        <a href="{{ url_for('admin_posts_list') }}?status=published" class="dash-stat">
            <span class="dash-stat__icon">✅</span>
            <div class="dash-stat__value">{{ stats.published_posts }}</div>
            <div class="dash-stat__label">{{ t('dashboard.published') }}</div>
        </a>
        <a href="{{ url_for('admin_posts_list') }}?status=draft" class="dash-stat">
            <span class="dash-stat__icon">📋</span>
            <div class="dash-stat__value">{{ stats.draft_posts }}</div>
            <div class="dash-stat__label">{{ t('dashboard.drafts') }}</div>
        </a>
        <a href="{{ url_for('admin_pages_list') }}" class="dash-stat">
            <span class="dash-stat__icon">📄</span>
            <div class="dash-stat__value">{{ stats.total_pages }}</div>
            <div class="dash-stat__label">{{ t('dashboard.total_pages') }}</div>
        </a>
        <a href="{{ url_for('admin_media_library') }}" class="dash-stat">
            <span class="dash-stat__icon">🖼️</span>
            <div class="dash-stat__value">{{ stats.total_images }}</div>
            <div class="dash-stat__label">{{ t('dashboard.total_images') }}</div>
        </a>
        <a href="{{ url_for('admin_users_list') }}" class="dash-stat">
            <span class="dash-stat__icon">👥</span>
            <div class="dash-stat__value">{{ stats.total_users }}</div>
            <div class="dash-stat__label">{{ t('dashboard.total_users') }}</div>
        </a>
        <a href="{{ url_for('admin_forms_list') }}" class="dash-stat">
            <span class="dash-stat__icon">📋</span>
            <div class="dash-stat__value">{{ stats.total_forms }}</div>
            <div class="dash-stat__label">{{ t('dashboard.total_forms') }}</div>
        </a>
        {% if stats.new_submissions > 0 %}
        <a href="{{ url_for('admin_forms_list') }}" class="dash-stat dash-stat--highlight">
            <span class="dash-stat__icon">🔔</span>
            <div class="dash-stat__value">{{ stats.new_submissions }}</div>
            <div class="dash-stat__label">{{ t('dashboard.new_submissions') }}</div>
        </a>
        {% endif %}
    </div>
    
    <!-- Two Columns: Recent Posts + Recent Pages -->
    <div class="dash-grid">
        
        <!-- Recent Posts -->
        <div class="dash-section">
            <div class="dash-section__header">
                <span class="dash-section__title">📝 {{ t('dashboard.recent_posts') }}</span>
                <a href="{{ url_for('admin_posts_list') }}" class="dash-section__link">{{ t('dashboard.view_all') }} →</a>
            </div>
            {% if recent_posts %}
            <ul class="dash-list">
                {% for post in recent_posts %}
                <li class="dash-item">
                    <div class="dash-item__info">
                        <div class="dash-item__title">{{ post.title }}</div>
                        <div class="dash-item__meta">{{ post.updated_at|format_date }} · {{ post.language|upper }}</div>
                    </div>
                    <div class="dash-item__actions">
                        <span class="dash-badge dash-badge--{{ post.status }}">{{ t('common.status_' + post.status) }}</span>
                        <a href="{{ url_for('admin_posts_edit', post_id=post.id) }}" class="dash-edit-link">{{ t('dashboard.edit') }}</a>
                    </div>
                </li>
                {% endfor %}
            </ul>
            {% else %}
            <div class="dash-empty">
                {{ t('dashboard.no_posts_yet') }} <a href="{{ url_for('admin_posts_new') }}">{{ t('dashboard.create_first_post') }}</a>
            </div>
            {% endif %}
        </div>
        
        <!-- Recent Pages -->
        <div class="dash-section">
            <div class="dash-section__header">
                <span class="dash-section__title">📄 {{ t('dashboard.recent_pages') }}</span>
                <a href="{{ url_for('admin_pages_list') }}" class="dash-section__link">{{ t('dashboard.view_all') }} →</a>
            </div>
            {% if recent_pages %}
            <ul class="dash-list">
                {% for page in recent_pages %}
                <li class="dash-item">
                    <div class="dash-item__info">
                        <div class="dash-item__title">{{ page.title }}</div>
                        <div class="dash-item__meta">{{ page.updated_at|format_date }} · {{ page.language|upper }}</div>
                    </div>
                    <div class="dash-item__actions">
                        <span class="dash-badge dash-badge--{{ page.status }}">{{ t('common.status_' + page.status) }}</span>
                        <a href="{{ url_for('admin_pages_edit', page_id=page.id) }}" class="dash-edit-link">{{ t('dashboard.edit') }}</a>
                    </div>
                </li>
                {% endfor %}
            </ul>
            {% else %}
            <div class="dash-empty">
                {{ t('dashboard.no_pages_yet') }} <a href="{{ url_for('admin_pages_new') }}">{{ t('dashboard.create_first_page') }}</a>
            </div>
            {% endif %}
        </div>
    </div>
    
    <!-- Recent Form Submissions -->
    {% if recent_submissions %}
    <div class="dash-section mb-6">
        <div class="dash-section__header">
            <span class="dash-section__title">📋 {{ t('dashboard.recent_submissions') }}</span>
            <a href="{{ url_for('admin_forms_list') }}" class="dash-section__link">{{ t('dashboard.view_all') }} →</a>
        </div>
        <ul class="dash-list">
            {% for sub in recent_submissions %}
            {% set data = sub.get_data() %}
            <li class="dash-item">
                <div class="dash-item__info">
                    <div class="dash-item__title">
                        {{ sub.form.title }} — 
                        {% if data.get('name') %}{{ data.name }}{% elif data.get('email') %}{{ data.email }}{% else %}#{{ sub.id }}{% endif %}
                    </div>
                    <div class="dash-item__meta">{{ sub.created_at|format_datetime }} · {{ sub.ip_address or '' }}</div>
                </div>
                <div class="dash-item__actions">
                    <span class="dash-badge {{ 'dash-badge--published' if sub.status == 'read' else 'dash-badge--draft' }}">{{ t('common.status_' + sub.status) }}</span>
                    <a href="{{ url_for('admin_forms_submission_detail', form_id=sub.form_id, sub_id=sub.id) }}" class="dash-edit-link">{{ t('dashboard.view_submission') }}</a>
                </div>
            </li>
            {% endfor %}
        </ul>
    </div>
    {% endif %}

    <!-- Recent Activity -->
    <div class="dash-section dash-activity">
        <div class="dash-section__header">
            <span class="dash-section__title">🕐 {{ t('dashboard.recent_activity') }}</span>
            {% if current_user.can_access_settings() %}
            <a href="{{ url_for('admin_audit_log') }}" class="dash-section__link">{{ t('dashboard.view_all') }} →</a>
            {% endif %}
        </div>
        {% if recent_activity %}
        <div>
            {% for log in recent_activity %}
            <div class="dash-activity-item">
                <span class="dash-activity__dot{% if 'login' in log.action %} dash-activity__dot--login{% elif 'create' in log.action %} dash-activity__dot--create{% elif 'edit' in log.action %} dash-activity__dot--edit{% elif 'delete' in log.action %} dash-activity__dot--delete{% endif %}"></span>
                <div>
                    <div class="dash-activity__text">
                        <strong>{{ t('audit_log.action_' + log.action) }}</strong>
                        {% if log.details %} — {{ log.details|translate_detail|truncate(60) }}{% endif %}
                    </div>
                    <div class="dash-activity__time">{{ log.created_at|format_datetime }}</div>
                </div>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="dash-empty">{{ t('dashboard.no_activity') }}</div>
        {% endif %}
    </div>
    
</div>

{% if current_user.can_access_settings() %}
<script>
/* ── Translation strings (collected here to keep JS lint-clean) ── */
var _t = {
    activate_license:  '{{ t("dashboard.activate_license") }}',
    license_hint:      '{{ t("dashboard.update_license_hint") }}',
    update_confirm:    '{{ t("dashboard.update_confirm") }}',
    restart_hint:      '{{ t("dashboard.restart_hint") }}',
    restarting:        '{{ t("dashboard.restarting") }}',
    reload:            '{{ t("dashboard.reload") }}',
    update_failed:     '{{ t("dashboard.update_failed") }}',
    update_now:        '{{ t("dashboard.update_now") }}',
    connection_error:  '{{ t("dashboard.connection_error") }}'
};

/* ── Auto-check for updates on dashboard load ── */
(function() {
    fetch('{{ url_for("admin_update_check") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    }).then(function(r) { return r.json(); }).then(function(data) {
        if (data.update_available) {
            document.getElementById('dashUpdateBanner').classList.add('visible');
            document.getElementById('dashUpdateVersion').textContent = 'v' + data.current_version + ' → v' + data.latest_version;
            if (data.changelog) {
                var cl = document.getElementById('dashUpdateChangelog');
                cl.innerHTML = data.changelog;
                cl.classList.add('visible');
            }
            window._updateData = data;
            
            /* If no download_url → user has no valid license */
            if (!data.download_url) {
                var btn = document.getElementById('dashUpdateBtn');
                btn.textContent = '🔑 ' + _t.activate_license;
                btn.onclick = function() { window.location.href = '{{ url_for("admin_settings") }}#license'; };
                var hint = document.createElement('div');
                hint.className = 'dash-update-banner__hint';
                hint.textContent = _t.license_hint;
                document.getElementById('dashUpdateVersion').parentNode.appendChild(hint);
            }
        }
    }).catch(function() {
        /* Silent fail — dashboard should never break because of update check */
    });
})();

function dashPerformUpdate() {
    AdminDialog.confirm(_t.update_confirm).then(function(okc) {
    if (!okc) return;
    var btn = document.getElementById('dashUpdateBtn');
    btn.disabled = true;
    btn.textContent = '{{ t("dashboard.updating") }}';
    
    fetch('{{ url_for("admin_update_perform") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': '{{ csrf_token() }}'
        }
    }).then(function(r) { return r.json(); }).then(function(data) {
        var banner = document.getElementById('dashUpdateBanner');
        if (data.success) {
            banner.classList.add('is-success');
            document.getElementById('dashUpdateTitle').textContent = '\u2705 ' + data.message;
            document.getElementById('dashUpdateChangelog').classList.remove('visible');
            
            /* Auto-reload: server restarts in ~4s. Reloading after a FIXED
               delay is a race — the first boot after an update recompiles
               all bytecode (updater clears __pycache__) and the graceful
               stop waits for in-flight requests, so a blind reload can land
               on a still-starting server and show a proxy error page.
               Instead: run the visible countdown, then POLL until the
               server actually answers, and only then reload. Capped at
               ~2 minutes, after which we fall back to a manual button. */
            var delay = data.auto_reload_delay || 6;
            if (delay > 0) {
                btn.disabled = true;
                var remaining = delay;
                document.getElementById('dashUpdateVersion').textContent = _t.restarting.replace('{seconds}', remaining);
                btn.textContent = '\u23F3 ' + remaining + 's';
                var pollDeadline = Date.now() + 120000;
                function pollThenReload() {
                    document.getElementById('dashUpdateVersion').textContent = _t.restarting.replace('{seconds}', '...');
                    fetch(window.location.pathname, { method: 'GET', cache: 'no-store', credentials: 'same-origin' })
                        .then(function(r) {
                            /* Any real HTTP answer below 500 (200, or a 30x
                               already followed to the login page) means the
                               app is up; 502/503 from the proxy means keep
                               waiting. */
                            if (r.status < 500) { location.reload(); return; }
                            throw new Error('not up yet');
                        })
                        .catch(function() {
                            if (Date.now() < pollDeadline) {
                                setTimeout(pollThenReload, 2000);
                            } else {
                                /* Server took unusually long — hand control
                                   back instead of reloading into an error. */
                                document.getElementById('dashUpdateVersion').textContent = _t.restart_hint;
                                btn.onclick = function() { location.reload(); };
                                btn.disabled = false;
                                btn.textContent = '\uD83D\uDD04 ' + _t.reload;
                            }
                        });
                }
                var countdown = setInterval(function() {
                    remaining--;
                    if (remaining > 0) {
                        document.getElementById('dashUpdateVersion').textContent = _t.restarting.replace('{seconds}', remaining);
                        btn.textContent = '\u23F3 ' + remaining + 's';
                    } else {
                        clearInterval(countdown);
                        pollThenReload();
                    }
                }, 1000);
            } else {
                /* Manual restart needed */
                document.getElementById('dashUpdateVersion').textContent = _t.restart_hint;
                btn.onclick = function() { location.reload(); };
                btn.disabled = false;
                btn.textContent = '\uD83D\uDD04 ' + _t.reload;
            }
        } else {
            document.getElementById('dashUpdateTitle').textContent = '\u274C ' + (data.error || _t.update_failed);
            btn.disabled = false;
            btn.textContent = '\u2B06\uFE0F ' + _t.update_now;
        }
    }).catch(function() {
        document.getElementById('dashUpdateTitle').textContent = '\u274C ' + _t.connection_error;
        btn.disabled = false;
        btn.textContent = '\u2B06\uFE0F ' + _t.update_now;
    });
    });
}
</script>
{% endif %}
{% endblock %}
