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

{% block extra_css %}
<link href="{% static 'css/dist/styles.css' %}" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto">
    <h1 class="text-2xl font-bold text-gray-800 mb-6">{% trans "Settings" %}</h1>

    <form method="post">
        {% csrf_token %}

        <div class="flex flex-col gap-6">

        <!-- Telegram Notifications -->
        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-1">{% trans "Telegram Notifications" %}</h2>
            <p class="text-sm text-gray-500 mb-4">
                {% trans "Global Telegram credentials used by all apps (Price Monitor, NetScan, etc.) to send alerts." %}
                {% trans "Create a bot via" %} <a href="https://t.me/BotFather" target="_blank" class="text-blue-500 hover:underline">@BotFather</a>
                {% trans "and get your chat ID from" %} <a href="https://t.me/userinfobot" target="_blank" class="text-blue-500 hover:underline">@userinfobot</a>.
            </p>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">{% trans "Bot Token" %}</label>
                    <input
                        type="password"
                        id="telegram_bot_token"
                        name="telegram_bot_token"
                        value="{{ site_settings.telegram_bot_token }}"
                        placeholder="123456:ABC-DEF1234..."
                        class="w-full border border-gray-300 rounded-md px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                    <p class="mt-1 text-xs text-gray-400">{% trans "Stored encrypted at rest." %}</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">{% trans "Chat ID" %}</label>
                    <input
                        type="text"
                        id="telegram_chat_id"
                        name="telegram_chat_id"
                        value="{{ site_settings.telegram_chat_id }}"
                        placeholder="-100123456789"
                        class="w-full border border-gray-300 rounded-md px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                    >
                    <p class="mt-1 text-xs text-gray-400">{% trans "User ID or group chat ID." %}</p>
                </div>
            </div>

            <div class="mt-4 flex justify-end">
                <button
                    type="button"
                    id="telegram-test-button"
                    class="px-4 py-2 bg-white text-blue-600 border border-blue-200 rounded-md text-sm font-medium hover:bg-blue-50"
                >
                    {% trans "Send Test Message" %}
                </button>
            </div>
            <p id="telegram-test-status" class="mt-2 text-xs text-gray-400"></p>
        </div>

        <!-- Public Sharing Domain -->
        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-1">{% trans "Public Sharing Domain" %}</h2>
            <p class="text-sm text-gray-500 mb-4">
                {% trans "Domain (with protocol) used for public file sharing links. Leave blank to use the same domain as the app." %}
                <br>
                <span class="font-mono text-xs text-gray-400">{% trans "Example:" %} https://go.example.com</span>
            </p>
            <input
                type="url"
                name="public_sharing_domain"
                id="public_sharing_domain"
                value="{{ site_settings.public_sharing_domain }}"
                placeholder="https://go.example.com"
                class="w-full border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
            {% if site_settings.public_sharing_domain %}
            <p class="mt-2 text-xs text-green-600">
                {% trans "Active. Public links will use:" %}
                <span class="font-mono">{{ site_settings.public_sharing_domain }}/public/files/…</span>
            </p>
            {% else %}
            <p class="mt-2 text-xs text-gray-400">
                {% trans "Not set. Public links will use the app's own domain." %}
            </p>
            {% endif %}
        </div>

        <!-- Screenshot Worker Concurrency -->
        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-1">{% trans "Max Concurrent Screenshot Jobs" %}</h2>
            <p class="text-sm text-gray-500 mb-4">
                {% trans "Maximum number of Chromium browser instances running simultaneously for screenshots. Reduce this if the container runs out of memory (OOM)." %}
            </p>
            <div class="flex items-center gap-3">
                <input
                    type="number"
                    name="max_concurrent_screenshot_jobs"
                    id="max_concurrent_screenshot_jobs"
                    value="{{ site_settings.max_concurrent_screenshot_jobs }}"
                    min="1"
                    max="20"
                    class="w-32 border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                <span class="text-sm text-gray-400">{% trans "instances" %}</span>
            </div>
            <p class="mt-2 text-xs text-gray-400">{% trans "Recommended: 1–3 for containers with limited RAM." %}</p>
        </div>

        <!-- Schedule Pending Pages Interval -->
        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-1">{% trans "Page Processing Interval" %}</h2>
            <p class="text-sm text-gray-500 mb-4">
                {% trans "How often (in seconds) the scheduler checks for pending pages and queues them for metadata extraction." %}
            </p>
            <div class="flex items-center gap-3">
                <input
                    type="number"
                    name="schedule_pending_pages_interval"
                    id="schedule_pending_pages_interval"
                    value="{{ site_settings.schedule_pending_pages_interval }}"
                    min="10"
                    max="3600"
                    class="w-32 border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                <span class="text-sm text-gray-400">{% trans "seconds" %}</span>
            </div>
            <p class="mt-2 text-xs text-gray-400">{% trans "Default: 120. Range: 10–3600. Changes take effect immediately." %}</p>
        </div>

        <!-- Schedule Pending Screenshots Interval -->
        <div class="bg-white rounded-lg shadow p-6">
            <h2 class="text-lg font-semibold text-gray-700 mb-1">{% trans "Screenshot Retry Interval" %}</h2>
            <p class="text-sm text-gray-500 mb-4">
                {% trans "How often (in seconds) the scheduler checks for stuck or pending screenshots and retries them." %}
            </p>
            <div class="flex items-center gap-3">
                <input
                    type="number"
                    name="schedule_pending_screenshots_interval"
                    id="schedule_pending_screenshots_interval"
                    value="{{ site_settings.schedule_pending_screenshots_interval }}"
                    min="10"
                    max="3600"
                    class="w-32 border border-gray-300 rounded-md px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                >
                <span class="text-sm text-gray-400">{% trans "seconds" %}</span>
            </div>
            <p class="mt-2 text-xs text-gray-400">{% trans "Default: 120. Range: 10–3600. Changes take effect immediately." %}</p>
        </div>

        </div><!-- /grid -->

        <div class="flex justify-end mt-6">
            <button
                type="submit"
                name="save_settings"
                value="1"
                style="background:#1d4ed8;color:#fff;padding:.5rem 1.5rem;border-radius:.375rem;font-size:.875rem;font-weight:500;cursor:pointer;"
                onmouseover="this.style.background='#1e40af'"
                onmouseout="this.style.background='#1d4ed8'"
            >
                {% trans "Save Settings" %}
            </button>
        </div>
    </form>

    <!-- Shared Posts Management -->
    <div class="bg-white rounded-lg shadow p-6 mt-6"
         x-data="sharedPostsMgr()"
         x-init="init()">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h2 class="text-lg font-semibold text-gray-700">{% trans "Shared Posts" %}</h2>
                <p class="text-sm text-gray-500 mt-0.5">{% trans "Posts currently accessible via public links. Disable to return to 404." %}</p>
            </div>
            <button x-show="posts.length > 0" @click="revokeAll()"
                    :disabled="busy"
                    class="flex items-center gap-1.5 px-3 py-1.5 text-sm text-red-600 border border-red-200 rounded-md hover:bg-red-50 disabled:opacity-50 transition">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/>
                </svg>
                {% trans "Revoke All" %}
            </button>
        </div>

        <!-- Empty state -->
        <div x-show="posts.length === 0 && !loading" class="py-6 text-center text-sm text-gray-400">
            {% trans "No posts are currently shared publicly." %}
        </div>

        <!-- Loading -->
        <div x-show="loading" class="py-6 text-center text-sm text-gray-400">
            {% trans "Loading…" %}
        </div>

        <!-- List -->
        <ul x-show="!loading" class="divide-y divide-gray-100">
            <template x-for="post in posts" :key="post.id">
                <li class="flex items-center gap-3 py-3">
                    <div class="flex-1 min-w-0">
                        <a :href="'/ui/posts/' + post.id + '/'"
                           class="font-medium text-gray-800 hover:text-blue-600 text-sm truncate block" x-text="post.title"></a>
                        <a :href="post.publicUrl" target="_blank"
                           class="text-xs text-gray-400 hover:text-gray-600 font-mono" x-text="post.publicUrl"></a>
                    </div>
                    <button @click="revoke(post)" :disabled="busy"
                            class="flex-shrink-0 flex items-center gap-1 px-2.5 py-1 text-xs text-red-600 border border-red-200 rounded hover:bg-red-50 disabled:opacity-50 transition">
                        <svg class="w-3.5 h-3.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>
                        {% trans "Revoke" %}
                    </button>
                </li>
            </template>
        </ul>
    </div>

</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', () => {
    const button = document.getElementById('telegram-test-button');
    const status = document.getElementById('telegram-test-status');

    if (!button || !status) return;

    button.addEventListener('click', async () => {
        const csrf = document.querySelector('[name=csrfmiddlewaretoken]')?.value
                     || document.cookie.match(/csrftoken=([^;]+)/)?.[1] || '';
        const token = document.getElementById('telegram_bot_token')?.value || '';
        const chatId = document.getElementById('telegram_chat_id')?.value || '';

        button.disabled = true;
        status.className = 'mt-2 text-xs text-gray-500';
        status.textContent = '{% trans "Sending test message…" %}';

        try {
            const resp = await fetch('{% url "test-telegram" %}', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': csrf,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ token, chat_id: chatId }),
            });
            const result = await resp.json();
            if (result.ok) {
                status.className = 'mt-2 text-xs text-green-600';
                status.textContent = '{% trans "Test message sent." %}';
            } else {
                status.className = 'mt-2 text-xs text-red-600';
                status.textContent = result.error || '{% trans "Telegram test failed." %}';
            }
        } catch (error) {
            status.className = 'mt-2 text-xs text-red-600';
            status.textContent = error.message || '{% trans "Telegram test failed." %}';
        } finally {
            button.disabled = false;
        }
    });
});

function sharedPostsMgr() {
    return {
        posts: [],
        loading: false,
        busy: false,
        init() {
            {% for p in public_posts %}
            this.posts.push({
                id: {{ p.pk }},
                title: '{{ p.title|escapejs }}',
                publicUrl: window.location.origin + '{% url "public-post" p.pk %}',
            });
            {% endfor %}
        },
        async _toggle(postId, enable) {
            const csrf = document.cookie.match(/csrftoken=([^;]+)/)?.[1] || '';
            await fetch('/ui/posts/' + postId + '/share/', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrf },
                body: JSON.stringify({ enable }),
            });
        },
        async revoke(post) {
            this.busy = true;
            try {
                await this._toggle(post.id, false);
                this.posts = this.posts.filter(p => p.id !== post.id);
            } finally {
                this.busy = false;
            }
        },
        async revokeAll() {
            if (!confirm('{% trans "Revoke public access for all shared posts?" %}')) return;
            this.busy = true;
            try {
                await Promise.all(this.posts.map(p => this._toggle(p.id, false)));
                this.posts = [];
            } finally {
                this.busy = false;
            }
        },
    };
}
</script>
{% endblock %}
