{% extends "base.html" %}
{% block title %}Photo Loader — TG Agent{% endblock %}
{% set selectable_dialogs = dialogs | rejectattr("channel_type", "equalto", "bot") | list %}
{% set target_available = selectable_dialogs | length > 0 %}
{% macro target_group(dialog) -%}
    {%- if dialog.channel_type in ["channel", "monoforum", "scam", "fake", "restricted"] -%}channel
    {%- elif dialog.channel_type in ["supergroup", "group", "gigagroup", "forum"] -%}group
    {%- elif dialog.channel_type == "dm" -%}dm
    {%- else -%}other
    {%- endif -%}
{%- endmacro %}
{% macro target_group_label(group) -%}
    {%- if group == "channel" -%}Каналы
    {%- elif group == "group" -%}Группы и чаты
    {%- elif group == "dm" -%}Личные диалоги
    {%- else -%}Прочее
    {%- endif -%}
{%- endmacro %}
{% macro render_target_hidden_inputs() -%}
<input type="hidden" name="target_dialog_id" value="" data-target-field="id">
<input type="hidden" name="target_title" value="" data-target-field="title">
<input type="hidden" name="target_type" value="" data-target-field="type">
{%- endmacro %}
{% block content %}
<h1>Photo Loader</h1>

{% if not accounts %}
<p>Нет подключённых аккаунтов. Добавьте аккаунт в <a href="/settings">Настройках</a>.</p>
{% else %}
<div class="row g-4">
    {% if photo_feedback %}
    <div class="col-12">
        <div class="alert {% if photo_feedback.variant == 'success' %}alert-success{% else %}alert-danger{% endif %} photo-feedback-panel mb-0"
             role="alert"
             data-photo-feedback
             data-highlight-kind="{{ photo_feedback.highlight_kind }}">
            <div class="d-flex flex-column gap-1">
                <strong data-photo-feedback-title>{{ photo_feedback.title }}</strong>
                <span data-photo-feedback-body>{{ photo_feedback.body }}</span>
            </div>
        </div>
    </div>
    {% endif %}

    <div class="col-12">
        <div class="row g-2 align-items-end">
        <form method="get" action="/my-telegram/photos" class="col-md-4">
            <label class="form-label">Аккаунт</label>
            <select name="phone" class="form-select" onchange="this.form.submit()">
                {% for acc in accounts %}
                <option value="{{ acc }}" {% if acc == selected_phone %}selected{% endif %}>{{ acc }}</option>
                {% endfor %}
            </select>
        </form>
        <form method="post" action="/my-telegram/photos/refresh" class="col-md-auto" data-busy>
            <input type="hidden" name="phone" value="{{ selected_phone or '' }}">
            <button class="btn btn-outline-secondary" type="submit" {% if not selected_phone %}disabled{% endif %}>Обновить диалоги</button>
        </form>
        <div class="col-12">
            <small class="text-muted">
                Используется сохранённый список диалогов{% if dialogs_cached_at %} от {{ dialogs_cached_at|local_dt }}{% endif %}. Кнопка обновления заново загружает данные из Telegram.
            </small>
        </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <div class="d-flex flex-column flex-lg-row justify-content-between gap-3 align-items-lg-start">
                    <div>
                        <h2 class="h5 mb-1">Цель отправки</h2>
                        <p class="text-muted mb-0">Один выбор цели используется во всех формах ниже.</p>
                    </div>
                    <div class="photo-target-summary" data-target-summary>
                        {% if not target_available %}
                        <span class="text-muted">Нет доступных каналов, чатов или личных диалогов для отправки.</span>
                        {% else %}
                        <span class="text-muted">Цель не выбрана.</span>
                        {% endif %}
                    </div>
                </div>

                {% if target_available %}
                <div id="photo-target-picker"
                     class="mt-4"
                     data-target-picker
                     data-target-phone="{{ selected_phone }}">
                    <p class="text-muted small mb-3">Сначала выберите канал, чат или личный диалог. Выбор сохранится на текущую браузерную сессию.</p>
                    <div class="row g-3">
                        <div class="col-lg-5">
                            <label class="form-label" for="target-search">Поиск</label>
                            <input id="target-search" type="search" class="form-control" placeholder="Название канала, чата или контакта" data-target-search>
                        </div>
                        <div class="col-lg-7">
                            <label class="form-label d-block">Тип</label>
                            <div class="btn-group flex-wrap" role="group" aria-label="Фильтр по типу">
                                <button type="button" class="btn btn-outline-secondary active" data-target-filter="all">Все</button>
                                <button type="button" class="btn btn-outline-secondary" data-target-filter="channel">Каналы</button>
                                <button type="button" class="btn btn-outline-secondary" data-target-filter="group">Группы и чаты</button>
                                <button type="button" class="btn btn-outline-secondary" data-target-filter="dm">Личные диалоги</button>
                            </div>
                        </div>
                        <div class="col-12">
                            <div class="list-group photo-target-list" data-target-list>
                                {% for dialog in selectable_dialogs %}
                                {% set group = target_group(dialog) %}
                                <button type="button"
                                        class="list-group-item list-group-item-action d-flex justify-content-between align-items-start"
                                        data-target-option
                                        data-target-id="{{ dialog.channel_id }}"
                                        data-target-title="{{ dialog.title }}"
                                        data-target-type="{{ dialog.channel_type }}"
                                        data-target-group="{{ group }}"
                                        data-target-search-text="{{ (dialog.title ~ ' ' ~ dialog.channel_type)|lower }}">
                                    <span class="me-3 text-start">
                                        <strong class="d-block">{{ dialog.title }}</strong>
                                        <span class="text-muted small">{{ dialog.channel_type }}</span>
                                    </span>
                                    <span class="badge rounded-pill text-bg-secondary">{{ target_group_label(group) }}</span>
                                </button>
                                {% endfor %}
                            </div>
                            <p class="text-muted small mt-2 mb-0 d-none" data-target-empty>Ничего не найдено.</p>
                        </div>
                    </div>
                </div>
                {% else %}
                <div class="alert alert-secondary mt-4 mb-0" role="alert">
                    Для выбранного аккаунта нет доступных целей отправки. Проверьте список диалогов в разделе <a href="/my-telegram">Мой Телеграм</a>.
                </div>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Обычная загрузка</h2>
                <form method="post" action="/my-telegram/photos/send" enctype="multipart/form-data" class="row g-3" data-photo-target-form data-photo-submit-form>
                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                    {{ render_target_hidden_inputs() }}
                    <div class="col-12">
                        <label class="form-label">Канал / чат</label>
                        <div class="form-control bg-body-tertiary" data-target-display>
                            {% if target_available %}Цель не выбрана{% else %}Цель недоступна{% endif %}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Режим</label>
                        <select name="send_mode" class="form-select">
                            <option value="separate" selected>Отдельные посты</option>
                            <option value="album">Альбом</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Фото</label>
                        <input type="file" name="photos" class="form-control" accept=".jpg,.jpeg,.png,.webp" multiple required>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Подпись</label>
                        <textarea name="caption" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-primary" type="submit" data-photo-submit-button data-busy-label="Отправка..." disabled>Отправить</button>
                        <div class="photo-submit-status d-none" data-photo-submit-status aria-live="polite"></div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Отложенная загрузка</h2>
                <form method="post" action="/my-telegram/photos/schedule" enctype="multipart/form-data" class="row g-3" data-photo-target-form data-photo-submit-form>
                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                    {{ render_target_hidden_inputs() }}
                    <div class="col-12">
                        <label class="form-label">Канал / чат</label>
                        <div class="form-control bg-body-tertiary" data-target-display>
                            {% if target_available %}Цель не выбрана{% else %}Цель недоступна{% endif %}
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Режим</label>
                        <select name="send_mode" class="form-select">
                            <option value="separate" selected>Отдельные посты</option>
                            <option value="album">Альбом</option>
                        </select>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Время</label>
                        <input type="datetime-local" name="schedule_at" class="form-control" required>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Фото</label>
                        <input type="file" name="photos" class="form-control" accept=".jpg,.jpeg,.png,.webp" multiple required>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Подпись</label>
                        <textarea name="caption" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-outline-primary" type="submit" data-photo-submit-button data-busy-label="Создаём отложку..." disabled>Поставить в отложку</button>
                        <div class="photo-submit-status d-none" data-photo-submit-status aria-live="polite"></div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Batch delayed</h2>
                <p class="text-muted small">JSON-массив объектов вида <code>{"at":"2026-03-11T18:30","files":["/abs/1.jpg"],"mode":"album"}</code></p>
                <form method="post" action="/my-telegram/photos/batch" class="row g-3" data-photo-target-form data-photo-submit-form>
                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                    {{ render_target_hidden_inputs() }}
                    <div class="col-12">
                        <label class="form-label">Канал / чат</label>
                        <div class="form-control bg-body-tertiary" data-target-display>
                            {% if target_available %}Цель не выбрана{% else %}Цель недоступна{% endif %}
                        </div>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Общая подпись</label>
                        <textarea name="caption" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Manifest</label>
                        <textarea name="manifest_text" class="form-control font-monospace" rows="8" required>[
  {"at": "2026-03-11T18:30", "files": ["/abs/photo1.jpg", "/abs/photo2.jpg"], "mode": "album"}
]</textarea>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-outline-secondary" type="submit" data-photo-submit-button data-busy-label="Создаём batch..." disabled>Создать batch</button>
                        <div class="photo-submit-status d-none" data-photo-submit-status aria-live="polite"></div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Автозагрузка из папки</h2>
                <form method="post" action="/my-telegram/photos/auto" class="row g-3" data-photo-target-form data-photo-submit-form>
                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                    {{ render_target_hidden_inputs() }}
                    <div class="col-12">
                        <label class="form-label">Канал / чат</label>
                        <div class="form-control bg-body-tertiary" data-target-display>
                            {% if target_available %}Цель не выбрана{% else %}Цель недоступна{% endif %}
                        </div>
                    </div>
                    <div class="col-md-7">
                        <label class="form-label">Папка</label>
                        <input type="text" name="folder_path" class="form-control" placeholder="/absolute/path/to/folder" required>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label">Интервал (мин.)</label>
                        <input type="number" name="interval_minutes" class="form-control" value="60" min="1" required>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label">Режим</label>
                        <select name="send_mode" class="form-select">
                            <option value="separate" selected>Отдельные посты</option>
                            <option value="album">Альбом</option>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label">Подпись</label>
                        <textarea name="caption" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="col-12">
                        <button class="btn btn-outline-secondary" type="submit" data-photo-submit-button data-busy-label="Создаём авто-джоб..." disabled>Создать авто-джоб</button>
                        <div class="photo-submit-status d-none" data-photo-submit-status aria-live="polite"></div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-12">
        <form method="post" action="/my-telegram/photos/run-due" data-busy>
            <input type="hidden" name="phone" value="{{ selected_phone }}">
            <button class="btn btn-sm btn-secondary" type="submit">Запустить due photo tasks сейчас</button>
        </form>
    </div>

    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Последние batches</h2>
                {% if batches %}
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead><tr><th>ID</th><th>Target</th><th>Режим</th><th>Статус</th><th>Создан</th></tr></thead>
                        <tbody>
                        {% for batch in batches %}
                        <tr data-photo-result-row="batch"
                            data-photo-result-target="{{ batch.target_title or batch.target_dialog_id }}">
                            <td>{{ batch.id }}</td>
                            <td>{{ batch.target_title or batch.target_dialog_id }}</td>
                            <td>{{ batch.send_mode }}</td>
                            <td>{{ batch.status }}</td>
                            <td>{{ batch.created_at|local_dt }}</td>
                        </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <p class="mb-0 text-muted">Batch tasks пока нет.</p>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Auto Jobs</h2>
                {% if auto_jobs %}
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead><tr><th>ID</th><th>Папка</th><th>Интервал</th><th>Статус</th><th>Последний запуск</th><th></th></tr></thead>
                        <tbody>
                        {% for job in auto_jobs %}
                        <tr data-photo-result-row="auto"
                            data-photo-result-target="{{ job.target_title or job.target_dialog_id }}">
                            <td>{{ job.id }}</td>
                            <td class="font-monospace">{{ job.folder_path }}</td>
                            <td>{{ job.interval_minutes }} мин.</td>
                            <td>{{ "active" if job.is_active else "paused" }}</td>
                            <td>{{ job.last_run_at|local_dt }}</td>
                            <td class="d-flex gap-2">
                                <form method="post" action="/my-telegram/photos/auto/{{ job.id }}/toggle" data-busy>
                                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                                    <button class="btn btn-sm btn-outline-secondary" type="submit">Toggle</button>
                                </form>
                                <form method="post" action="/my-telegram/photos/auto/{{ job.id }}/delete" data-busy>
                                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                                    <button class="btn btn-sm btn-outline-danger" type="submit">Delete</button>
                                </form>
                            </td>
                        </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <p class="mb-0 text-muted">Auto jobs пока нет.</p>
                {% endif %}
            </div>
        </div>
    </div>

    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h2 class="h5">Последние photo items</h2>
                {% if items %}
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead><tr><th>ID</th><th>Target</th><th>Файлы</th><th>Время</th><th>Статус</th><th></th></tr></thead>
                        <tbody>
                        {% for item in items %}
                        <tr data-photo-result-row="item"
                            data-photo-result-target="{{ item.target_title or item.target_dialog_id }}">
                            <td>{{ item.id }}</td>
                            <td>{{ item.target_title or item.target_dialog_id }}</td>
                            <td>{{ item.file_paths|length }}</td>
                            <td>{{ (item.schedule_at or item.created_at)|local_dt }}</td>
                            <td>{{ item.status }}</td>
                            <td>
                                <form method="post" action="/my-telegram/photos/items/{{ item.id }}/cancel" data-busy>
                                    <input type="hidden" name="phone" value="{{ selected_phone }}">
                                    <button class="btn btn-sm btn-outline-danger" type="submit">Cancel</button>
                                </form>
                            </td>
                        </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <p class="mb-0 text-muted">Photo items пока нет.</p>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    var submitForms = Array.from(document.querySelectorAll("[data-photo-submit-form]"));
    var feedback = document.querySelector("[data-photo-feedback]");

    submitForms.forEach(function(form) {
        form.addEventListener("submit", function(event) {
            if (form.dataset.submitting === "true") {
                event.preventDefault();
                return;
            }

            var submitter = event.submitter || form.querySelector("[data-photo-submit-button]");
            if (!submitter) return;

            form.dataset.submitting = "true";
            submitter.disabled = true;
            submitter.classList.add("is-busy");
            submitter.innerHTML =
                '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>' +
                "<span>" + (submitter.dataset.busyLabel || "Выполняется...") + "</span>";

            var status = form.querySelector("[data-photo-submit-status]");
            if (status) {
                status.textContent = "Запрос отправлен, ожидаем ответ сервера...";
                status.classList.remove("d-none");
            }
        });
    });

    if (feedback) {
        var highlightKind = feedback.dataset.highlightKind;
        if (highlightKind) {
            var row = document.querySelector('[data-photo-result-row="' + highlightKind + '"]');
            if (row) {
                row.classList.add("photo-result-highlight");
                row.setAttribute("tabindex", "-1");
                row.focus({preventScroll: true});
                row.scrollIntoView({behavior: "smooth", block: "center"});
            }
        }
    }

    var picker = document.querySelector("[data-target-picker]");
    if (!picker) return;

    var searchInput = picker.querySelector("[data-target-search]");
    var options = Array.from(picker.querySelectorAll("[data-target-option]"));
    var filterButtons = Array.from(picker.querySelectorAll("[data-target-filter]"));
    var emptyState = picker.querySelector("[data-target-empty]");
    var summary = document.querySelector("[data-target-summary]");
    var forms = Array.from(document.querySelectorAll("[data-photo-target-form]"));
    var activeFilter = "all";
    var selectedPhone = picker.dataset.targetPhone || "";
    var storageKey = selectedPhone ? "photo_loader_target:" + selectedPhone : "";
    var emptyDisplayText = "Цель не выбрана";

    function updateForms(target) {
        forms.forEach(function(form) {
            var idField = form.querySelector('[data-target-field="id"]');
            var titleField = form.querySelector('[data-target-field="title"]');
            var typeField = form.querySelector('[data-target-field="type"]');
            var display = form.querySelector("[data-target-display]");
            var submitButton = form.querySelector("[data-photo-submit-button]");
            if (idField) idField.value = target ? target.id : "";
            if (titleField) titleField.value = target ? target.title : "";
            if (typeField) typeField.value = target ? target.type : "";
            if (display) display.textContent = target ? target.title : emptyDisplayText;
            if (submitButton) submitButton.disabled = !target;
        });
    }

    function updateSummary(target) {
        if (!summary) return;
        summary.replaceChildren();
        if (!target) {
            var empty = document.createElement("span");
            empty.className = "text-muted";
            empty.textContent = emptyDisplayText + ".";
            summary.append(empty);
            return;
        }

        var title = document.createElement("strong");
        title.textContent = target.title;

        var spacerAfterTitle = document.createTextNode(" ");

        var badge = document.createElement("span");
        badge.className = "badge text-bg-secondary";
        badge.textContent = target.groupLabel;

        var spacerAfterBadge = document.createTextNode(" ");

        var type = document.createElement("span");
        type.className = "text-muted small";
        type.textContent = target.type;

        summary.append(title, spacerAfterTitle, badge, spacerAfterBadge, type);
    }

    function saveTarget(target) {
        if (!storageKey) return;
        if (!target) {
            sessionStorage.removeItem(storageKey);
            return;
        }
        sessionStorage.setItem(storageKey, JSON.stringify({
            id: target.id,
            title: target.title,
            type: target.type
        }));
    }

    function resetSelectionUI() {
        options.forEach(function(option) {
            option.classList.remove("active");
        });
        updateForms(null);
        updateSummary(null);
    }

    function setActiveOption(button) {
        options.forEach(function(option) {
            option.classList.toggle("active", option === button);
        });
        var target = {
            id: button.dataset.targetId,
            title: button.dataset.targetTitle,
            type: button.dataset.targetType,
            groupLabel: button.querySelector(".badge").textContent
        };
        updateForms(target);
        updateSummary(target);
        saveTarget(target);
    }

    function findOptionById(id) {
        return options.find(function(option) {
            return option.dataset.targetId === String(id);
        }) || null;
    }

    function restoreTarget() {
        if (!storageKey) return false;
        var raw = sessionStorage.getItem(storageKey);
        if (!raw) return false;
        try {
            var saved = JSON.parse(raw);
            var option = findOptionById(saved.id);
            if (!option) {
                sessionStorage.removeItem(storageKey);
                return false;
            }
            setActiveOption(option);
            return true;
        } catch (_error) {
            sessionStorage.removeItem(storageKey);
            return false;
        }
    }

    function applyFilters() {
        var query = (searchInput.value || "").trim().toLowerCase();
        var visibleCount = 0;
        options.forEach(function(option) {
            var matchesType = activeFilter === "all" || option.dataset.targetGroup === activeFilter;
            var matchesText = !query || option.dataset.targetSearchText.indexOf(query) !== -1;
            var visible = matchesType && matchesText;
            option.classList.toggle("d-none", !visible);
            if (visible) visibleCount += 1;
        });
        emptyState.classList.toggle("d-none", visibleCount !== 0);
    }

    options.forEach(function(option) {
        option.addEventListener("click", function() {
            setActiveOption(option);
        });
    });

    filterButtons.forEach(function(button) {
        button.addEventListener("click", function() {
            activeFilter = button.dataset.targetFilter;
            filterButtons.forEach(function(item) {
                item.classList.toggle("active", item === button);
            });
            applyFilters();
        });
    });

    searchInput.addEventListener("input", applyFilters);

    resetSelectionUI();
    if (!restoreTarget()) {
        updateForms(null);
        updateSummary(null);
    }
    applyFilters();
})();
</script>
{% endif %}
{% endblock %}
