{% extends "base.html" %}
{% block title %}Мой Телеграм — TG Agent{% endblock %}
{% block content %}
<div class="d-flex align-items-center gap-3 mb-1">
    <h1 class="mb-0">Мой Телеграм</h1>
    <a href="/my-telegram/create-channel" class="btn btn-outline-primary btn-sm">+ Создать канал</a>
</div>

<div class="d-flex flex-column flex-md-row align-items-md-start gap-3 mb-4">
    {% if accounts %}
    <div class="d-flex flex-column gap-1">
        <a class="btn btn-outline-primary btn-sm align-self-start" href="/my-telegram/photos{% if selected_phone %}?phone={{ selected_phone|urlencode }}{% endif %}">Открыть Photo Loader</a>
        <small class="text-muted">Если аккаунт не выбран, откроется первый доступный профиль.</small>
    </div>
    {% else %}
    <div class="d-flex flex-column gap-1">
        <span class="btn btn-outline-secondary btn-sm disabled" aria-disabled="true">Открыть Photo Loader</span>
        <small class="text-muted">Сначала добавьте Telegram-аккаунт в настройках.</small>
    </div>
    {% endif %}

    {% if accounts %}
    <div class="mb-0" style="max-width:400px">
        <label class="form-label">Аккаунт</label>
        <select name="phone" class="form-select"
                hx-get="/my-telegram/"
                hx-include="this"
                hx-target="body"
                hx-push-url="true"
                hx-trigger="change"
                hx-indicator="#dialogs-loading">
            <option value="" {% if not selected_phone %}selected{% endif %}>Выберите аккаунт</option>
            {% for acc in accounts %}
            <option value="{{ acc }}" {% if acc == selected_phone %}selected{% endif %}>{{ acc }}</option>
            {% endfor %}
        </select>
        <span id="dialogs-loading" class="htmx-indicator d-inline-block mt-2">&#9203; Загрузка диалогов…</span>
        <form method="post" action="/my-telegram/refresh" class="mt-2" data-busy>
            <input type="hidden" name="phone" value="{{ selected_phone or '' }}">
            <button class="btn btn-outline-secondary btn-sm" type="submit" {% if not selected_phone %}disabled{% endif %}>Обновить диалоги</button>
        </form>
        {% if selected_phone %}
        <small class="text-muted d-block mt-2">
            Показан сохранённый список диалогов{% if dialogs_cached_at %} от {{ dialogs_cached_at|local_dt }}{% endif %}. Кнопка обновления заново загружает данные из Telegram.
        </small>
        {% endif %}
    </div>
    {% endif %}
</div>

{% if not accounts %}
<p>Нет подключённых аккаунтов. Добавьте аккаунт в <a href="/settings">Настройках</a>.</p>
{% else %}

{% if left or failed %}
<p class="mb-3">
    Отписались: <strong>{{ left }}</strong>{% if failed %}, не удалось: <strong>{{ failed }}</strong>{% endif %}
</p>
{% endif %}

{% if dialogs %}
{% set channels = dialogs | selectattr("channel_type", "in", ["channel", "monoforum", "scam", "fake", "restricted"]) | list %}
{% set groups = dialogs | selectattr("channel_type", "in", ["supergroup", "group", "gigagroup", "forum"]) | list %}
{% set dms = dialogs | selectattr("channel_type", "equalto", "dm") | list %}
{% set bots = dialogs | selectattr("channel_type", "equalto", "bot") | list %}
{% set own = dialogs | selectattr("is_own") | list %}

<p class="text-muted">Всего диалогов: <strong>{{ dialogs|length }}</strong></p>

<form method="post" action="/my-telegram/leave" id="leave-form" data-busy>
<input type="hidden" name="phone" value="{{ selected_phone }}">

<div id="leave-bar" class="d-none gap-3 align-items-center mb-3">
    <span id="leave-count">0 выбрано</span>
    <button type="submit" class="btn btn-danger btn-sm"
            onclick="return confirm('Отписаться от выбранных диалогов?')">
        Отписаться
    </button>
    <button type="button" class="btn btn-secondary btn-sm" onclick="clearSelection()">Сбросить</button>
</div>

<ul class="nav nav-tabs nav-fill mb-3" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" id="tab-channels" data-bs-toggle="tab" data-bs-target="#pane-channels" type="button" role="tab">Каналы ({{ channels|length }})</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-own" data-bs-toggle="tab" data-bs-target="#pane-own" type="button" role="tab">Созданные ({{ own|length }})</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-dms" data-bs-toggle="tab" data-bs-target="#pane-dms" type="button" role="tab">ДМ ({{ dms|length }})</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-groups" data-bs-toggle="tab" data-bs-target="#pane-groups" type="button" role="tab">Группы ({{ groups|length }})</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="tab-bots" data-bs-toggle="tab" data-bs-target="#pane-bots" type="button" role="tab">Боты ({{ bots|length }})</button>
    </li>
</ul>

<div class="tab-content">
    <div class="tab-pane fade" id="pane-own" role="tabpanel">
    {% if own %}
    <!-- Desktop -->
    <div class="table-responsive d-none d-md-block">
    <table class="table table-striped table-sm">
        <thead><tr>
            <th><input type="checkbox" class="form-check-input" id="select-all-own"
                       onchange="selectAll('own', this.checked)"></th>
            <th>Тип</th><th>Название</th><th>Username</th><th>В базе</th>
        </tr></thead>
        <tbody>
        {% for d in own %}
        <tr>
            <td><input type="checkbox" class="form-check-input cb-own" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}"
                       onchange="updateLeaveBar()"></td>
            <td><span class="badge-active">{{ d.channel_type }}</span></td>
            <td>{{ d.title }}</td>
            <td>{% if d.username %}<a href="https://t.me/{{ d.username }}" target="_blank" rel="noopener">@{{ d.username }}</a>{% else %}<span class="text-muted">—</span>{% endif %}</td>
            <td>{% if d.already_added %}<span class="badge-active">&#10003;</span>{% else %}<span class="text-muted">—</span>{% endif %}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    </div>
    <!-- Mobile -->
    <div class="d-md-none mobile-cards">
        {% for d in own %}
        <div class="card mb-2">
            <div class="card-body py-2 d-flex align-items-center gap-2">
                <input type="checkbox" class="form-check-input cb-own" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}" onchange="updateLeaveBar()">
                <div class="flex-fill min-w-0">
                    <div class="text-truncate"><strong>{{ d.title }}</strong></div>
                    <small class="text-muted">{{ d.channel_type }}{% if d.username %} &middot; @{{ d.username }}{% endif %}{% if d.already_added %} &middot; &#10003;{% endif %}</small>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}<p>Нет своих каналов/групп.</p>{% endif %}
    </div>

    <div class="tab-pane fade show active" id="pane-channels" role="tabpanel">
    {% if channels %}
    <!-- Desktop -->
    <div class="table-responsive d-none d-md-block">
    <table class="table table-striped table-sm">
        <thead><tr>
            <th><input type="checkbox" class="form-check-input" id="select-all-channels"
                       onchange="selectAll('channels', this.checked)"></th>
            <th>Тип</th><th>Название</th><th>Username</th><th>В базе</th>
        </tr></thead>
        <tbody>
        {% for d in channels %}
        <tr>
            <td><input type="checkbox" class="form-check-input cb-channels" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}"
                       onchange="updateLeaveBar()"></td>
            <td><span class="badge-active">{{ d.channel_type }}</span></td>
            <td>{{ d.title }}</td>
            <td>{% if d.username %}<a href="https://t.me/{{ d.username }}" target="_blank" rel="noopener">@{{ d.username }}</a>{% else %}<span class="text-muted">—</span>{% endif %}</td>
            <td>{% if d.already_added %}<span class="badge-active">&#10003;</span>{% else %}<span class="text-muted">—</span>{% endif %}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    </div>
    <!-- Mobile -->
    <div class="d-md-none mobile-cards">
        {% for d in channels %}
        <div class="card mb-2">
            <div class="card-body py-2 d-flex align-items-center gap-2">
                <input type="checkbox" class="form-check-input cb-channels" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}" onchange="updateLeaveBar()">
                <div class="flex-fill min-w-0">
                    <div class="text-truncate"><strong>{{ d.title }}</strong></div>
                    <small class="text-muted">{{ d.channel_type }}{% if d.username %} &middot; @{{ d.username }}{% endif %}{% if d.already_added %} &middot; &#10003;{% endif %}</small>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}<p>Нет каналов.</p>{% endif %}
    </div>

    <div class="tab-pane fade" id="pane-groups" role="tabpanel">
    {% if groups %}
    <!-- Desktop -->
    <div class="table-responsive d-none d-md-block">
    <table class="table table-striped table-sm">
        <thead><tr>
            <th><input type="checkbox" class="form-check-input" id="select-all-groups"
                       onchange="selectAll('groups', this.checked)"></th>
            <th>Тип</th><th>Название</th><th>Username</th><th>В базе</th>
        </tr></thead>
        <tbody>
        {% for d in groups %}
        <tr>
            <td><input type="checkbox" class="form-check-input cb-groups" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}"
                       onchange="updateLeaveBar()"></td>
            <td><span class="badge-active">{{ d.channel_type }}</span></td>
            <td>{{ d.title }}</td>
            <td>{% if d.username %}<a href="https://t.me/{{ d.username }}" target="_blank" rel="noopener">@{{ d.username }}</a>{% else %}<span class="text-muted">—</span>{% endif %}</td>
            <td>{% if d.already_added %}<span class="badge-active">&#10003;</span>{% else %}<span class="text-muted">—</span>{% endif %}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    </div>
    <!-- Mobile -->
    <div class="d-md-none mobile-cards">
        {% for d in groups %}
        <div class="card mb-2">
            <div class="card-body py-2 d-flex align-items-center gap-2">
                <input type="checkbox" class="form-check-input cb-groups" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}" onchange="updateLeaveBar()">
                <div class="flex-fill min-w-0">
                    <div class="text-truncate"><strong>{{ d.title }}</strong></div>
                    <small class="text-muted">{{ d.channel_type }}{% if d.username %} &middot; @{{ d.username }}{% endif %}{% if d.already_added %} &middot; &#10003;{% endif %}</small>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}<p>Нет групп.</p>{% endif %}
    </div>

    <div class="tab-pane fade" id="pane-dms" role="tabpanel">
    {% if dms %}
    <!-- Desktop -->
    <div class="table-responsive d-none d-md-block">
    <table class="table table-striped table-sm">
        <thead><tr>
            <th><input type="checkbox" class="form-check-input" id="select-all-dms"
                       onchange="selectAll('dms', this.checked)"></th>
            <th>Название</th><th>Username</th>
        </tr></thead>
        <tbody>
        {% for d in dms %}
        <tr>
            <td><input type="checkbox" class="form-check-input cb-dms" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}"
                       onchange="updateLeaveBar()"></td>
            <td>{{ d.title }}</td>
            <td>{% if d.username %}<a href="https://t.me/{{ d.username }}" target="_blank" rel="noopener">@{{ d.username }}</a>{% else %}<span class="text-muted">—</span>{% endif %}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    </div>
    <!-- Mobile -->
    <div class="d-md-none mobile-cards">
        {% for d in dms %}
        <div class="card mb-2">
            <div class="card-body py-2 d-flex align-items-center gap-2">
                <input type="checkbox" class="form-check-input cb-dms" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}" onchange="updateLeaveBar()">
                <div class="flex-fill min-w-0">
                    <div class="text-truncate"><strong>{{ d.title }}</strong></div>
                    {% if d.username %}<small class="text-muted">@{{ d.username }}</small>{% endif %}
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}<p>Нет личных диалогов.</p>{% endif %}
    </div>

    <div class="tab-pane fade" id="pane-bots" role="tabpanel">
    {% if bots %}
    <!-- Desktop -->
    <div class="table-responsive d-none d-md-block">
    <table class="table table-striped table-sm">
        <thead><tr>
            <th><input type="checkbox" class="form-check-input" id="select-all-bots"
                       onchange="selectAll('bots', this.checked)"></th>
            <th>Название</th><th>Username</th>
        </tr></thead>
        <tbody>
        {% for d in bots %}
        <tr>
            <td><input type="checkbox" class="form-check-input cb-bots" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}"
                       onchange="updateLeaveBar()"></td>
            <td>{{ d.title }}</td>
            <td>{% if d.username %}<a href="https://t.me/{{ d.username }}" target="_blank" rel="noopener">@{{ d.username }}</a>{% else %}<span class="text-muted">—</span>{% endif %}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
    </div>
    <!-- Mobile -->
    <div class="d-md-none mobile-cards">
        {% for d in bots %}
        <div class="card mb-2">
            <div class="card-body py-2 d-flex align-items-center gap-2">
                <input type="checkbox" class="form-check-input cb-bots" name="channel_ids" value="{{ d.channel_id }}:{{ d.channel_type }}" onchange="updateLeaveBar()">
                <div class="flex-fill min-w-0">
                    <div class="text-truncate"><strong>{{ d.title }}</strong></div>
                    {% if d.username %}<small class="text-muted">@{{ d.username }}</small>{% endif %}
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}<p>Нет ботов.</p>{% endif %}
    </div>
</div>

</form>

<script>
function updateLeaveBar() {
    var n = document.querySelectorAll('input[name="channel_ids"]:checked').length;
    document.getElementById('leave-count').textContent = n + ' выбрано';
    var bar = document.getElementById('leave-bar');
    if (n > 0) {
        bar.classList.remove('d-none');
        bar.classList.add('d-flex');
    } else {
        bar.classList.add('d-none');
        bar.classList.remove('d-flex');
    }
}
function selectAll(pane, checked) {
    document.querySelectorAll('.cb-' + pane).forEach(function(cb) {
        cb.checked = checked;
    });
    updateLeaveBar();
}
function clearSelection() {
    document.querySelectorAll('input[name="channel_ids"]').forEach(function(cb) {
        cb.checked = false;
    });
    document.querySelectorAll('[id^="select-all-"]').forEach(function(cb) {
        cb.checked = false;
    });
    updateLeaveBar();
}
</script>

{% elif selected_phone %}
<p>Нет диалогов.</p>
{% else %}
<p class="text-muted">Выберите аккаунт, чтобы загрузить список диалогов.</p>
{% endif %}

{% endif %}
{% endblock %}
