<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';
$user    = require_auth();
$isAdmin = is_admin($user);
?>
<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Вывод бота в топ — tgtop</title>
  <meta name="description" content="Сервис вывода Telegram-бота в топ поиска. Расчёт стоимости, анализ конкурентов, план продвижения.">
  <link rel="icon" href="/favicon.svg" type="image/svg+xml">
  <style>
    :root {
      --bg-1:#110d16; --bg-2:#1b1220;
      --panel:rgba(18,13,24,.86); --panel-2:rgba(30,21,39,.92);
      --ink:#f5efe4; --muted:#cbbd9d; --line:rgba(255,255,255,.08);
      --brand:#d2493f; --brand-2:#ff6552; --ok:#68d391; --error:#ff8b8b;
      --shadow:0 24px 80px rgba(0,0,0,.45); --radius:28px;
    }
    *{box-sizing:border-box}
    html,body{min-height:100%}
    body{margin:0;font-family:Georgia,"Palatino Linotype","Book Antiqua",serif;color:var(--ink);letter-spacing:.02em;
      background:radial-gradient(circle at 18% 16%,rgba(210,73,63,.12),transparent 26%),
        radial-gradient(circle at 82% 18%,rgba(255,101,82,.10),transparent 24%),
        radial-gradient(circle at 50% 100%,rgba(71,48,90,.42),transparent 34%),
        linear-gradient(160deg,var(--bg-1),var(--bg-2) 58%,#0c0912 100%);}
    body::before{content:"";position:fixed;inset:0;pointer-events:none;
      background-image:radial-gradient(circle at 12% 28%,rgba(255,255,255,.22) 0 1px,transparent 1.3px),
        radial-gradient(circle at 78% 20%,rgba(255,255,255,.18) 0 1px,transparent 1.2px),
        radial-gradient(circle at 30% 80%,rgba(255,255,255,.15) 0 1px,transparent 1.4px);opacity:.55;}
    a{color:inherit;text-decoration:none}
    .page{width:min(1180px,calc(100vw - 32px));margin:0 auto;padding:24px 0 48px}
    .nav{display:flex;justify-content:space-between;align-items:center;gap:16px;margin-bottom:20px;padding:14px 18px;border:1px solid var(--line);border-radius:20px;background:rgba(17,13,22,.68);backdrop-filter:blur(14px)}
    .nav-brand{display:flex;align-items:center;gap:12px;font-size:1.05rem;font-weight:700;letter-spacing:.06em}
    .nav-brand span{color:var(--muted);font-size:.85rem;font-weight:400}
    .nav-links{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
    .chip,.button,.mini-button{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:10px 16px;border-radius:999px;border:1px solid var(--line);transition:transform .18s ease,border-color .18s ease,background .18s ease;font-family:inherit;font-size:.9rem;cursor:pointer;color:var(--ink)}
    .chip:hover,.button:hover,.mini-button:hover{transform:translateY(-1px)}
    .button-primary{background:linear-gradient(135deg,var(--brand),var(--brand-2));border-color:transparent;color:#fff;box-shadow:0 12px 28px rgba(210,73,63,.28)}
    .button-muted,.mini-button{background:rgba(255,255,255,.03)}
    .card{padding:24px 26px;border-radius:var(--radius);border:1px solid var(--line);background:rgba(255,255,255,.025);backdrop-filter:blur(8px)}
    input,select,textarea{width:100%;padding:11px 14px;border-radius:14px;border:1px solid rgba(255,255,255,.09);background:rgba(6,5,9,.34);color:var(--ink);font-size:.95rem;font-family:inherit;outline:none;transition:border-color .18s}
    input:focus,select:focus,textarea:focus{border-color:rgba(210,73,63,.5)}
    label{display:block;font-size:.88rem;color:var(--muted);margin-bottom:4px}
    label > input,label > select,label > textarea{margin-top:6px}
    .field-help{display:block;font-size:.8rem;color:#888;margin-top:5px}
    .empty-state{padding:28px;text-align:center;color:var(--muted);font-size:.93rem;border:1px dashed rgba(255,255,255,.1);border-radius:20px}
    .tab-btn{padding:10px 18px;border-radius:999px;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.03);color:#cbbd9d;cursor:pointer;font-family:inherit;font-size:.9rem;transition:all .18s}
    .tab-btn.active{background:linear-gradient(135deg,#d2493f,#ff6552);border-color:transparent;color:#fff}
    .bot-card{padding:20px;border-radius:20px;border:1px solid rgba(255,255,255,.08);background:linear-gradient(180deg,rgba(255,255,255,.03),rgba(255,255,255,.01));margin-bottom:12px}
    .bot-avatar{width:60px;height:60px;border-radius:50%;object-fit:cover;border:2px solid rgba(255,255,255,.1)}
    .bot-avatar-ph{width:60px;height:60px;border-radius:50%;background:linear-gradient(135deg,#d2493f,#ff6552);display:flex;align-items:center;justify-content:center;font-size:1.4rem;flex-shrink:0}
    .task-card{padding:16px 18px;border-radius:16px;border:1px solid rgba(255,255,255,.08);background:rgba(255,255,255,.025);transition:border-color .2s}
    .task-card.done{border-color:rgba(104,211,145,.35);background:rgba(104,211,145,.05)}
    .day-dot{width:28px;height:28px;border-radius:50%;border:2px solid rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;font-size:.78rem;font-weight:700;flex-shrink:0}
    .day-dot.active{border-color:#ff6552;background:rgba(210,73,63,.2);color:#ff9980}
    .day-dot.done{border-color:#68d391;background:rgba(104,211,145,.15);color:#68d391}
    .msg-ok{padding:12px 14px;border-radius:14px;background:rgba(104,211,145,.12);border:1px solid rgba(104,211,145,.3);color:#d6ffe4}
    .msg-err{padding:12px 14px;border-radius:14px;background:rgba(255,107,107,.1);border:1px solid rgba(255,107,107,.26);color:#ffd9d9}
    .msg-warn{padding:12px 14px;border-radius:14px;background:rgba(255,193,7,.08);border:1px solid rgba(255,193,7,.3);color:#fff3cd}
  </style>
</head>
<body>
<div class="page">

  <!-- Nav -->
  <nav class="nav">
    <div class="nav-brand">
      🚀 tgtop <span>· Вывод бота в топ Telegram</span>
    </div>
    <div class="nav-links">
      <span style="color:#cbbd9d;font-size:.85rem"><?= htmlspecialchars($user['email']) ?></span>
      <a class="button button-muted" href="/logout.php" style="font-size:.85rem;padding:8px 14px">Выйти</a>
    </div>
  </nav>

  <!-- Header -->
  <div style="margin-bottom:24px">
    <p style="margin:0 0 4px;color:#cbbd9d;font-size:.82rem;text-transform:uppercase;letter-spacing:.1em">Telegram-продвижение</p>
    <h1 style="margin:0 0 8px;font-size:1.8rem">Вывод бота в топ</h1>
    <p style="margin:0;color:#cbbd9d;font-size:.95rem;max-width:62ch;line-height:1.65">
      Добавьте своего бота, следите за статистикой и ежедневно выполняйте шаги продвижения — через 3 дня бот выйдет в топ поиска Telegram.
    </p>
  </div>

  <!-- Tabs -->
  <div style="display:flex;gap:8px;margin-bottom:22px;flex-wrap:wrap">
    <button class="tab-btn active" id="tab-bots"     onclick="showTab('bots')">🤖 Мои боты</button>
    <button class="tab-btn"        id="tab-add"      onclick="showTab('add')">＋ Добавить бота</button>
    <button class="tab-btn"        id="tab-calc"     onclick="showTab('calc')">💰 Расчет Топ 1</button>
    <button class="tab-btn"        id="tab-requests" onclick="showTab('requests')">📊 Мои заявки</button>
    <button class="tab-btn"        id="tab-howto"    onclick="showTab('howto')">📖 Как создать бота</button>
  </div>

  <!-- ── Мои боты ─────────────────────────────────────────────────────────── -->
  <div id="pane-bots">
    <div style="display:flex;justify-content:flex-end;margin-bottom:14px">
      <button class="button button-muted" onclick="loadBots()" style="font-size:.88rem;padding:10px 16px">⟳ Обновить список</button>
    </div>
    <div id="bots-loading" style="color:#cbbd9d;padding:16px">Загрузка…</div>
    <div id="bots-list"></div>
  </div>

  <!-- ── Добавить бота ─────────────────────────────────────────────────────── -->
  <div id="pane-add" style="display:none">
    <div class="card" style="max-width:560px">
      <strong style="font-size:1rem;display:block;margin-bottom:16px">Добавить Telegram-бота</strong>
      <div style="display:grid;gap:14px">
        <label>
          Username бота <span style="color:#ff8b8b">*</span>
          <input type="text" id="add-username" placeholder="@mybotname или mybotname" style="margin-top:6px">
        </label>
        <label>
          Токен бота (необязательно)
          <input type="text" id="add-token" placeholder="123456:ABC-DEF..." style="margin-top:6px">
          <span class="field-help">Нужен для получения подробной информации о боте. Найдёте у @BotFather.</span>
        </label>
        <div style="display:flex;gap:10px;margin-top:4px">
          <button class="button button-primary" onclick="addBot()" id="btn-add-bot" style="flex:1">Добавить бота</button>
        </div>
        <div id="add-msg" style="display:none"></div>
      </div>
    </div>
  </div>

  <!-- ── Расчет стоимости Топ 1 ──────────────────────────────────────────────── -->
  <div id="pane-calc" style="display:none">
    <div style="max-width:680px;display:grid;gap:20px">

      <div class="card">
        <strong style="font-size:1rem;display:block;margin-bottom:6px">💰 Расчет стоимости вывода в Топ 1</strong>
        <p style="margin:0 0 16px;color:#cbbd9d;font-size:.9rem;line-height:1.6">
          Сделайте скриншот поиска Telegram по вашему ключевому слову (например, «1win»), загрузите его — ИИ прочитает список и рассчитает примерную стоимость вывода вашего бота на первое место.
        </p>
        <div style="display:grid;gap:12px">
          <label>
            Ключевое слово <span style="color:#ff8b8b">*</span>
            <input type="text" id="calc-keyword" placeholder="Например: 1win, криптобот, ai assistant" style="margin-top:6px">
          </label>
          <label>
            Скриншот поиска Telegram <span style="color:#ff8b8b">*</span>
            <div id="calc-drop" onclick="document.getElementById('calc-file').click()"
                 style="margin-top:6px;border:2px dashed rgba(255,255,255,.15);border-radius:16px;padding:28px;text-align:center;cursor:pointer;transition:border-color .2s;background:rgba(255,255,255,.02)">
              <div id="calc-drop-text" style="color:#cbbd9d;font-size:.9rem">📎 Нажмите или перетащите файл сюда<br><span style="font-size:.8rem;opacity:.7">JPG, PNG, WEBP · макс 10 МБ</span></div>
              <img id="calc-preview" src="" alt="" style="display:none;max-width:100%;max-height:280px;border-radius:10px;margin-top:10px">
            </div>
            <input type="file" id="calc-file" accept="image/jpeg,image/png,image/webp" style="display:none" onchange="previewCalcFile(this)">
          </label>
          <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
            <label>
              Доля Premium-подписчиков
              <select id="calc-prem-pct" style="margin-top:6px" onchange="if(window._calcResults)renderCalcTable(window._calcResults)">
                <option value="5">5%</option>
                <option value="10">10%</option>
                <option value="20">20%</option>
                <option value="30" selected>30% (по умолчанию)</option>
                <option value="40">40%</option>
                <option value="50">50%</option>
                <option value="80">80%</option>
                <option value="100">100%</option>
              </select>
            </label>
            <label>
              Период продвижения
              <select id="calc-period" style="margin-top:6px" onchange="if(window._calcResults)renderCalcTable(window._calcResults)">
                <option value="5">7 дней — $5 / 1000</option>
                <option value="8" selected>15 дней — $8 / 1000</option>
                <option value="15">30 дней — $15 / 1000</option>
                <option value="40">90 дней — $40 / 1000</option>
              </select>
            </label>
          </div>
          <button class="button button-primary" onclick="analyzeScreenshot()" id="btn-analyze" style="width:fit-content">🔍 Анализировать</button>
          <div id="calc-msg" style="display:none"></div>
        </div>
      </div>

      <!-- Results -->
      <div id="calc-results" style="display:none">
        <div class="card" style="margin-bottom:14px">
          <strong style="display:block;margin-bottom:12px">📋 Результаты анализа</strong>
          <div id="calc-table"></div>
        </div>
        <div class="card" style="background:linear-gradient(135deg,rgba(210,73,63,.1),rgba(255,101,82,.06));border-color:rgba(210,73,63,.3)">
          <div style="display:flex;align-items:flex-start;gap:14px;flex-wrap:wrap">
            <div style="font-size:2rem;flex-shrink:0">💎</div>
            <div style="flex:1">
              <p style="margin:0 0 4px;color:#cbbd9d;font-size:.84rem;text-transform:uppercase;letter-spacing:.08em">Примерная стоимость Топ 1</p>
              <div id="calc-price" style="font-size:2rem;font-weight:700;color:#ff9980;margin-bottom:8px">—</div>
              <div id="calc-formula" style="color:#cbbd9d;font-size:.84rem;line-height:1.6"></div>
            </div>
          </div>
          <div id="calc-rub-rate" style="font-size:.8rem;color:#888;margin-top:2px"></div>
          <div style="margin-top:14px;padding:14px 16px;border-radius:12px;background:rgba(255,200,100,.07);border:1px solid rgba(255,200,100,.2);font-size:.83rem;color:#f4c77b;line-height:1.7">
            ⚠️ <b>Обратите внимание — это примерный расчёт.</b><br>
            Точное процентное соотношение Telegram Premium-подписчиков у конкурента определить по скриншоту невозможно.
            Для вашего удобства наш сервис предоставляет эту <b>примерную таблицу расчёта стоимости</b> на основе выбранных вами параметров.<br>
            Реальная стоимость продвижения может отличаться в зависимости от фактической доли Premium-аудитории и текущих цен на услуги.
          </div>
        </div>
        <div style="margin-top:14px;text-align:center">
          <button class="button button-muted" onclick="openRequestFromCalc()" style="font-size:.88rem">📊 Запросить точный расчёт у модератора</button>
        </div>
      </div>
    </div>
  </div>

  <!-- ── Мои заявки на анализ ──────────────────────────────────────────────── -->
  <div id="pane-requests" style="display:none">
    <div style="display:flex;justify-content:flex-end;margin-bottom:14px">
      <button class="button button-muted" onclick="loadMyRequests()" style="font-size:.88rem;padding:10px 16px">⟳ Обновить</button>
    </div>
    <div id="requests-loading" style="color:#cbbd9d;padding:16px">Загрузка…</div>
    <div id="requests-list"></div>
  </div>

  <!-- ── Как создать бота ───────────────────────────────────────────────────── -->
  <div id="pane-howto" style="display:none">
    <div style="max-width:680px;display:grid;gap:14px">
      <?php
      $steps = [
        ['1', 'Откройте @BotFather', 'В Telegram найдите бота <b>@BotFather</b> и нажмите <b>Start</b>.'],
        ['2', 'Создайте нового бота', 'Отправьте команду <code>/newbot</code>. BotFather попросит придумать имя бота — это публичное название (например: «Мой помощник»).'],
        ['3', 'Придумайте username', 'Затем придумайте уникальный username — он должен заканчиваться на <b>bot</b> (например: <code>myhelper_bot</code>).'],
        ['4', 'Сохраните токен', 'BotFather выдаст токен вида <code>123456:ABC-DEF1234ghIkl-...</code>. Скопируйте его — он нужен для подключения.'],
        ['5', 'Заполните профиль', 'Через команды <code>/setdescription</code> и <code>/setabouttext</code> добавьте описание бота. Это важно для поиска.'],
        ['6', 'Добавьте бота здесь', 'Вернитесь на вкладку «Добавить бота» и введите username и токен. Система начнёт отслеживать статистику.'],
      ];
      foreach ($steps as [$num, $title, $text]):
      ?>
      <div class="card" style="display:flex;gap:16px;align-items:flex-start">
        <div style="flex-shrink:0;width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,#d2493f,#ff6552);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:1rem"><?= $num ?></div>
        <div>
          <strong style="display:block;margin-bottom:6px"><?= $title ?></strong>
          <p style="margin:0;color:#cbbd9d;line-height:1.65;font-size:.94rem"><?= $text ?></p>
        </div>
      </div>
      <?php endforeach; ?>
      <div style="margin-top:6px">
        <button class="button button-primary" onclick="showTab('add')">Добавить бота →</button>
      </div>
    </div>
  </div>

</div><!-- .page -->

<!-- ── Promotion Modal ─────────────────────────────────────────────────────── -->
<div id="promo-overlay" onclick="closePromo()" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:100;backdrop-filter:blur(6px)"></div>
<div id="promo-modal" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:101;
     width:min(640px,calc(100vw - 24px));max-height:90vh;overflow-y:auto;
     background:linear-gradient(180deg,#1c1428,#0f0a14);
     border:1px solid rgba(255,255,255,.1);border-radius:28px;padding:32px;box-shadow:0 32px 80px rgba(0,0,0,.6)">
  <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:18px;gap:12px">
    <div>
      <h2 style="margin:0 0 4px;font-size:1.3rem" id="promo-title">Продвижение</h2>
      <p style="margin:0;color:#cbbd9d;font-size:.88rem" id="promo-meta"></p>
    </div>
    <button onclick="closePromo()" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#cbbd9d;border-radius:999px;padding:8px 14px;cursor:pointer;font-size:.88rem;flex-shrink:0">✕ Закрыть</button>
  </div>
  <div id="promo-progress" style="display:flex;gap:8px;margin-bottom:22px"></div>
  <div id="promo-day-card" style="padding:16px 18px;border-radius:18px;border:1px solid rgba(210,73,63,.25);background:rgba(210,73,63,.08);margin-bottom:18px">
    <p style="margin:0 0 4px;color:#ff9980;font-size:.82rem;letter-spacing:.1em;text-transform:uppercase" id="promo-day-label"></p>
    <strong style="font-size:1.05rem" id="promo-day-title"></strong>
    <p style="margin:6px 0 0;color:#cbbd9d;font-size:.9rem" id="promo-day-desc"></p>
  </div>
  <div id="promo-tasks" style="display:grid;gap:12px"></div>
  <div id="promo-timer" style="display:none;margin-top:20px;padding:16px 18px;border-radius:18px;border:1px dashed rgba(255,255,255,.14);background:rgba(255,255,255,.02);text-align:center">
    <p style="margin:0 0 6px;color:#cbbd9d;font-size:.88rem">Следующий день откроется через</p>
    <strong id="promo-countdown" style="font-size:1.4rem;color:#f4c77b">--:--:--</strong>
  </div>
  <div id="promo-msg" style="display:none;margin-top:14px"></div>
</div>

<!-- ── Analysis Request Modal ──────────────────────────────────────────────── -->
<div id="req-overlay" onclick="closeReqModal()" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:200;backdrop-filter:blur(6px)"></div>
<div id="req-modal" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:201;
     width:min(520px,calc(100vw - 24px));max-height:90vh;overflow-y:auto;
     background:linear-gradient(180deg,#1c1428,#0f0a14);
     border:1px solid rgba(255,255,255,.1);border-radius:28px;padding:28px;box-shadow:0 32px 80px rgba(0,0,0,.6)">
  <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px">
    <h3 style="margin:0;font-size:1.1rem">📊 Запрос анализа у модератора</h3>
    <button onclick="closeReqModal()" style="background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#cbbd9d;border-radius:999px;padding:6px 12px;cursor:pointer;font-size:.85rem">✕</button>
  </div>
  <input type="hidden" id="req-bot-id" value="0">
  <p id="req-bot-label" style="color:#cbbd9d;font-size:.88rem;margin:0 0 14px"></p>
  <div style="display:grid;gap:12px">
    <label>
      Ключевое слово в поиске Telegram <span style="color:#ff8b8b">*</span>
      <input type="text" id="req-keyword" placeholder="Например: 1win, ai bot, crypto" style="margin-top:6px">
    </label>
    <label>
      Комментарий (необязательно)
      <textarea id="req-notes" rows="3" placeholder="Дополнительные пожелания или вопросы к модератору…"
        style="margin-top:6px;width:100%;padding:10px 12px;border-radius:12px;border:1px solid rgba(255,255,255,.09);background:rgba(6,5,9,.34);color:#f5efe4;font-size:.9rem;font-family:inherit;resize:vertical;box-sizing:border-box"></textarea>
    </label>
    <label style="cursor:pointer">
      Скриншот поиска (необязательно)
      <div style="margin-top:6px;display:flex;align-items:center;gap:10px">
        <button type="button" onclick="document.getElementById('req-file-input').click()"
          style="padding:8px 14px;border-radius:999px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.04);color:#cbbd9d;cursor:pointer;font-size:.84rem">📎 Прикрепить файл</button>
        <span id="req-file-name" style="color:#cbbd9d;font-size:.82rem"></span>
      </div>
      <input type="file" id="req-file-input" accept="image/jpeg,image/png,image/webp" style="display:none"
        onchange="document.getElementById('req-file-name').textContent = this.files[0]?.name || ''">
    </label>
    <button class="button button-primary" onclick="submitRequest()" id="btn-submit-req" style="margin-top:4px">Отправить заявку</button>
    <div id="req-msg" style="display:none"></div>
  </div>
</div>

<script>
let currentPromoData = null;
let countdownTimer   = null;

// ── Tabs ─────────────────────────────────────────────────────────────────────
function showTab(name) {
  ['bots','add','calc','requests','howto'].forEach(t => {
    document.getElementById('pane-' + t).style.display = t === name ? 'block' : 'none';
    document.getElementById('tab-'  + t).classList.toggle('active', t === name);
  });
  if (name === 'bots')     loadBots();
  if (name === 'requests') loadMyRequests();
}

// ── Bots list ────────────────────────────────────────────────────────────────
async function loadBots() {
  document.getElementById('bots-loading').style.display = 'block';
  document.getElementById('bots-list').innerHTML = '';
  try {
    const r = await fetch('/api/smm_bots.php?action=list');
    const d = await r.json();
    document.getElementById('bots-loading').style.display = 'none';
    if (!d.ok) { document.getElementById('bots-loading').textContent = 'Ошибка: ' + d.error; return; }
    if (!d.bots.length) {
      document.getElementById('bots-list').innerHTML = `<div class="empty-state">У вас пока нет добавленных ботов. <button onclick="showTab('add')" style="background:none;border:none;color:#ff9980;cursor:pointer;text-decoration:underline;font-size:inherit;padding:0">Добавить бота →</button></div>`;
      return;
    }
    d.bots.forEach(bot => renderBotCard(bot));
  } catch(e) {
    document.getElementById('bots-loading').textContent = 'Ошибка: ' + e.message;
  }
}

function renderBotCard(bot) {
  const wrap = document.createElement('div');
  wrap.className = 'bot-card';
  wrap.id = 'bot-' + bot.id;
  const hasPromo = bot.promotion && bot.promotion.status === 'active';
  const avatar = bot.avatar_url
    ? `<img class="bot-avatar" src="${esc(bot.avatar_url)}" alt="">`
    : `<div class="bot-avatar-ph">🤖</div>`;
  const updated = bot.stats_updated_at ? bot.stats_updated_at.slice(0,16).replace('T',' ') : '—';
  const added   = bot.added_at.slice(0,10);

  wrap.innerHTML = `
    <div style="display:flex;gap:16px;align-items:flex-start;flex-wrap:wrap">
      ${avatar}
      <div style="flex:1;min-width:0">
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:6px">
          <strong style="font-size:1.05rem">${esc(bot.bot_name || bot.username)}</strong>
          <span style="color:#cbbd9d;font-size:.88rem">@${esc(bot.username)}</span>
          ${hasPromo ? '<span style="background:rgba(104,211,145,.15);border:1px solid rgba(104,211,145,.3);color:#68d391;border-radius:999px;padding:3px 10px;font-size:.78rem">▶ Продвигается</span>' : ''}
        </div>
        <p style="margin:0 0 10px;color:#cbbd9d;font-size:.9rem;line-height:1.55">${esc(bot.bot_description || 'Нет описания')}</p>
        <div style="display:flex;gap:14px;flex-wrap:wrap;font-size:.82rem;color:#cbbd9d">
          <span>📅 Добавлен: <b>${added}</b></span>
          <span id="sub-display-${bot.id}" style="display:inline-flex;align-items:center;gap:5px">👥 Подписчиков: <b id="sub-val-${bot.id}">${bot.subscriber_count || '—'}</b><button onclick="editSubs(${bot.id},${bot.subscriber_count||0})" title="Указать вручную" style="background:none;border:none;color:#cbbd9d;cursor:pointer;padding:0 2px;opacity:.65;font-size:.82rem;line-height:1">✏️</button></span><span id="sub-form-${bot.id}" style="display:none;align-items:center;gap:5px"><input type="number" id="sub-inp-${bot.id}" min="0" style="width:82px;padding:3px 7px;border-radius:8px;border:1px solid rgba(255,255,255,.15);background:rgba(255,255,255,.06);color:#fff;font-size:.83rem"><button onclick="saveSubs(${bot.id})" style="background:rgba(104,211,145,.15);border:1px solid rgba(104,211,145,.3);color:#68d391;border-radius:8px;padding:3px 9px;cursor:pointer;font-size:.82rem;line-height:1.4">✓</button><button onclick="cancelSubs(${bot.id})" style="background:none;border:1px solid rgba(255,255,255,.1);color:#cbbd9d;border-radius:8px;padding:3px 7px;cursor:pointer;font-size:.82rem;line-height:1.4">✕</button></span>
          <span>🔄 Обновлено: <b>${updated}</b></span>
        </div>
        <div style="display:flex;gap:8px;flex-wrap:wrap;margin-top:14px">
          ${hasPromo
            ? `<button class="button button-primary" onclick="openPromo(${bot.id})" style="font-size:.88rem;padding:10px 16px">▶ Продолжить продвижение</button>`
            : `<button class="button button-primary" onclick="startPromo(${bot.id})" style="font-size:.88rem;padding:10px 16px">🚀 Запустить продвижение</button>`
          }
          <button class="button button-muted" onclick="refreshBot(${bot.id})" style="font-size:.88rem;padding:10px 14px">⟳ Обновить</button>
          <button onclick="openAnalysisModal(${bot.id},'${esc(bot.username)}')" style="font-size:.82rem;padding:8px 14px;border-radius:999px;border:1px solid rgba(104,211,145,.25);background:rgba(104,211,145,.07);color:#68d391;cursor:pointer">📊 На анализ</button>
          <button onclick="deleteBot(${bot.id})" style="font-size:.82rem;padding:8px 14px;border-radius:999px;border:1px solid rgba(255,107,107,.25);background:rgba(255,107,107,.07);color:#ff8b8b;cursor:pointer">Удалить</button>
        </div>
      </div>
    </div>`;
  document.getElementById('bots-list').appendChild(wrap);
}

// ── Add bot ───────────────────────────────────────────────────────────────────
async function addBot() {
  const username = document.getElementById('add-username').value.trim();
  const token    = document.getElementById('add-token').value.trim();
  const btn      = document.getElementById('btn-add-bot');
  const msg      = document.getElementById('add-msg');
  if (!username) { showMsg(msg, 'Введите username бота', false); return; }
  btn.disabled = true; btn.textContent = 'Добавляем…';
  msg.style.display = 'none';
  try {
    const r = await fetch('/api/smm_bots.php?action=add', {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({action:'add', username, token})
    });
    const d = await r.json();
    if (d.ok) {
      showMsg(msg, `✅ Бот @${d.info.username} добавлен!`, true);
      document.getElementById('add-username').value = '';
      document.getElementById('add-token').value = '';
      setTimeout(() => { showTab('bots'); }, 1500);
    } else {
      showMsg(msg, 'Ошибка: ' + d.error, false);
    }
  } catch(e) { showMsg(msg, 'Сетевая ошибка', false); }
  btn.disabled = false; btn.textContent = 'Добавить бота';
}

// ── Refresh / Delete bot ──────────────────────────────────────────────────────
async function refreshBot(botId) {
  try {
    const r = await fetch('/api/smm_bots.php?action=refresh', {
      method:'POST', headers:{'Content-Type':'application/json'},
      body: JSON.stringify({action:'refresh', bot_id: botId})
    });
    const d = await r.json();
    if (d.ok) { await loadBots(); } else { alert('Ошибка: ' + d.error); }
  } catch(e) { alert('Ошибка: ' + e.message); }
}

async function deleteBot(botId) {
  if (!confirm('Удалить бота? История продвижения также будет удалена.')) return;
  await fetch('/api/smm_bots.php?action=delete', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({action:'delete', bot_id: botId})
  });
  loadBots();
}

// ── Promotion ─────────────────────────────────────────────────────────────────
async function startPromo(botId) {
  const r = await fetch('/api/smm_bots.php?action=start_promotion', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({action:'start_promotion', bot_id: botId})
  });
  const d = await r.json();
  if (d.ok) { openPromo(botId); } else { alert('Ошибка: ' + d.error); }
}

async function openPromo(botId) {
  document.getElementById('promo-modal').style.display = 'block';
  document.getElementById('promo-overlay').style.display = 'block';
  document.getElementById('promo-tasks').innerHTML = '<div style="color:#cbbd9d;padding:12px">Загружаем задачи…</div>';
  document.getElementById('promo-msg').style.display = 'none';

  try {
    const r = await fetch(`/api/smm_bots.php?action=promotion_tasks&bot_id=${botId}`);
    const d = await r.json();
    if (!d.ok) {
      if (d.error === 'Продвижение не запущено') { await startPromo(botId); return; }
      document.getElementById('promo-tasks').innerHTML = '<div class="msg-err">'+d.error+'</div>';
      return;
    }
    if (d.status === 'completed') {
      document.getElementById('promo-title').textContent = '🎉 Продвижение завершено!';
      document.getElementById('promo-meta').textContent = 'Все 3 дня выполнены';
      document.getElementById('promo-tasks').innerHTML = '<div class="msg-ok">Поздравляем! Программа продвижения на 3 дня завершена.</div>';
      document.getElementById('promo-day-card').style.display = 'none';
      document.getElementById('promo-progress').innerHTML = '';
      loadBots();
      return;
    }
    currentPromoData = {...d, bot_id: botId};
    renderPromoModal(d);
  } catch(e) {
    document.getElementById('promo-tasks').innerHTML = '<div class="msg-err">'+e.message+'</div>';
  }
}

function renderPromoModal(d) {
  const totalDays = d.total_days || 3;
  const curDay    = parseInt(d.promotion.current_day);
  const promoId   = d.promotion.id;

  document.getElementById('promo-title').textContent = '🚀 Продвижение бота';
  document.getElementById('promo-meta').textContent  = `День ${curDay} из ${totalDays}`;

  const prog = document.getElementById('promo-progress');
  prog.innerHTML = '';
  for (let i = 1; i <= totalDays; i++) {
    const dot = document.createElement('div');
    dot.className = 'day-dot' + (i < curDay ? ' done' : i === curDay ? ' active' : '');
    dot.title = `День ${i}`;
    dot.textContent = i < curDay ? '✓' : i;
    prog.appendChild(dot);
    if (i < totalDays) {
      const line = document.createElement('div');
      line.style.cssText = 'flex:1;height:2px;background:rgba(255,255,255,.1);margin:auto 4px;border-radius:2px;max-width:40px';
      prog.appendChild(line);
    }
  }

  document.getElementById('promo-day-card').style.display = 'block';
  document.getElementById('promo-day-label').textContent  = `День ${curDay} из ${totalDays}`;
  document.getElementById('promo-day-title').textContent  = d.day?.title || '';
  document.getElementById('promo-day-desc').textContent   = d.day?.description || '';

  const tasksEl = document.getElementById('promo-tasks');
  tasksEl.innerHTML = '';
  if (!d.tasks?.length) {
    tasksEl.innerHTML = '<div class="empty-state">Задачи для этого дня не найдены.</div>';
  }
  d.tasks.forEach(task => {
    const isDone = d.completed.includes(task.id);
    const card = document.createElement('div');
    card.className = 'task-card' + (isDone ? ' done' : '');
    card.id = 'task-' + task.id;
    card.innerHTML = `
      <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap">
        <div style="flex:1;min-width:0">
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:6px;flex-wrap:wrap">
            <span style="width:22px;height:22px;border-radius:50%;background:${isDone ? 'rgba(104,211,145,.3)' : 'rgba(210,73,63,.25)'};display:inline-flex;align-items:center;justify-content:center;font-size:.78rem;font-weight:700;flex-shrink:0">${isDone ? '✓' : task.step_number}</span>
            <strong style="font-size:.97rem">${esc(task.title)}</strong>
            ${isDone ? '<span style="color:#68d391;font-size:.82rem">— Выполнено</span>' : ''}
          </div>
          <p style="margin:0 0 10px;color:#cbbd9d;font-size:.9rem;line-height:1.55">${esc(task.description)}</p>
          ${task.service_name ? `<div style="font-size:.82rem;color:#f4c77b;margin-bottom:8px">📦 Услуга: <b>${esc(task.service_name)}</b>${task.quantity_recommended ? ` · Рекомендуемое кол-во: <b>${task.quantity_recommended}</b>` : ''}</div>` : ''}
        </div>
        <div style="display:flex;flex-direction:column;gap:8px;align-items:flex-end;flex-shrink:0">
          ${task.service_name && !isDone ? `<a href="https://spellbook.academy/smm.php" target="_blank" class="button button-muted" style="font-size:.82rem;padding:8px 14px">Открыть SMM-панель →</a>` : ''}
          ${!isDone ? `<button class="button button-primary" onclick="completeTask(${promoId}, ${task.id})" style="font-size:.82rem;padding:8px 14px">✓ Выполнено</button>` : ''}
        </div>
      </div>`;
    tasksEl.appendChild(card);
  });

  if (d.next_day_at && d.hours_passed < 24) {
    const allDone = d.tasks.length > 0 && d.tasks.every(t => d.completed.includes(t.id));
    document.getElementById('promo-timer').style.display = allDone ? 'block' : 'none';
    if (allDone) startCountdown(new Date(d.next_day_at));
  } else {
    document.getElementById('promo-timer').style.display = 'none';
  }
}

async function completeTask(promoId, taskId) {
  const r = await fetch('/api/smm_bots.php?action=complete_task', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({action:'complete_task', promotion_id: promoId, task_id: taskId})
  });
  const d = await r.json();
  if (d.ok && currentPromoData) {
    openPromo(currentPromoData.bot_id);
  } else if (!d.ok) {
    alert('Ошибка: ' + d.error);
  }
}

function closePromo() {
  document.getElementById('promo-modal').style.display = 'none';
  document.getElementById('promo-overlay').style.display = 'none';
  if (countdownTimer) clearInterval(countdownTimer);
  currentPromoData = null;
  loadBots();
}

function startCountdown(target) {
  if (countdownTimer) clearInterval(countdownTimer);
  function tick() {
    const diff = Math.max(0, target - new Date());
    const h = String(Math.floor(diff / 3600000)).padStart(2,'0');
    const m = String(Math.floor((diff % 3600000) / 60000)).padStart(2,'0');
    const s = String(Math.floor((diff % 60000) / 1000)).padStart(2,'0');
    document.getElementById('promo-countdown').textContent = `${h}:${m}:${s}`;
    if (diff === 0) { clearInterval(countdownTimer); openPromo(currentPromoData?.bot_id); }
  }
  tick();
  countdownTimer = setInterval(tick, 1000);
}

// ── Subscriber count inline edit ─────────────────────────────────────────────
function editSubs(botId, current) {
  document.getElementById('sub-display-' + botId).style.display = 'none';
  const form = document.getElementById('sub-form-' + botId);
  form.style.display = 'inline-flex';
  document.getElementById('sub-inp-' + botId).value = current;
  document.getElementById('sub-inp-' + botId).focus();
}
function cancelSubs(botId) {
  document.getElementById('sub-form-' + botId).style.display = 'none';
  document.getElementById('sub-display-' + botId).style.display = 'inline-flex';
}
async function saveSubs(botId) {
  const val = parseInt(document.getElementById('sub-inp-' + botId).value);
  if (isNaN(val) || val < 0) { alert('Введите корректное число'); return; }
  const r = await fetch('/api/smm_bots.php?action=set_subscribers', {
    method:'POST', headers:{'Content-Type':'application/json'},
    body: JSON.stringify({bot_id: botId, subscriber_count: val})
  });
  const d = await r.json();
  if (d.ok) {
    document.getElementById('sub-val-' + botId).textContent = val || '—';
    cancelSubs(botId);
  } else { alert('Ошибка: ' + d.error); }
}

function showMsg(el, text, ok) {
  el.className = ok ? 'msg-ok' : 'msg-err';
  el.textContent = text;
  el.style.display = 'block';
}

function esc(s) {
  return String(s||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}

// ── Screenshot analysis (Расчет Топ 1) ───────────────────────────────────────
function previewCalcFile(input) {
  const file = input.files[0];
  if (!file) return;
  document.getElementById('calc-drop-text').style.display = 'none';
  const prev = document.getElementById('calc-preview');
  prev.src = URL.createObjectURL(file);
  prev.style.display = 'block';
  document.getElementById('calc-drop').style.borderColor = 'rgba(104,211,145,.5)';
}

async function analyzeScreenshot() {
  const keyword = document.getElementById('calc-keyword').value.trim();
  const file    = document.getElementById('calc-file').files[0];
  const msg     = document.getElementById('calc-msg');
  const btn     = document.getElementById('btn-analyze');
  if (!keyword) { showMsg(msg, 'Введите ключевое слово', false); return; }
  if (!file)    { showMsg(msg, 'Загрузите скриншот поиска', false); return; }

  btn.disabled = true; btn.textContent = '⏳ Анализируем…';
  msg.style.display = 'none';

  try {
    const fd = new FormData();
    fd.append('action', 'analyze_screenshot');
    fd.append('screenshot', file);
    const r = await fetch('/api/smm_bots.php?action=analyze_screenshot', { method:'POST', body: fd });
    const d = await r.json();
    if (!d.ok) { showMsg(msg, 'Ошибка: ' + d.error, false); return; }
    window._calcExcluded = [];
    renderCalcResults(d.results, keyword);
  } catch(e) { showMsg(msg, 'Ошибка: ' + e.message, false); }
  btn.disabled = false; btn.textContent = '🔍 Анализировать';
}

function renderCalcResults(results, keyword) {
  const msgEl   = document.getElementById('calc-msg');
  const priceEl = document.getElementById('calc-price');
  const frmEl   = document.getElementById('calc-formula');

  if (!results || !results.length) {
    msgEl.className = 'msg-err';
    msgEl.innerHTML = 'ИИ не смог распознать результаты поиска Telegram.<br>'
      + 'Нужен скриншот выдачи поиска Telegram, сделанный <b>с мобильного устройства</b> '
      + '(<u>не с ПК</u>) — так в нём отображается количество подписчиков.';
    msgEl.style.display = 'block';
    document.getElementById('calc-results').style.display = 'none';
    return;
  }

  const anyWithSubs = results.some(r => r.subscribers > 0);
  if (!anyWithSubs) {
    msgEl.className = 'msg-err';
    msgEl.innerHTML = 'На скриншоте не видно количество подписчиков ни у одного результата.<br>'
      + 'Убедитесь, что скриншот сделан <b>с мобильного устройства</b> (<u>не с ПК</u>) — '
      + 'только мобильный Telegram показывает счётчики подписчиков в поиске.';
    msgEl.style.display = 'block';
    document.getElementById('calc-results').style.display = 'none';
    return;
  }

  window._calcResults  = results;
  window._calcKeyword  = keyword;
  window._calcExcluded = window._calcExcluded || [];

  renderCalcTable(results, msgEl, priceEl, frmEl);
}

function renderCalcTable(results, msgEl, priceEl, frmEl) {
  msgEl  = msgEl  || document.getElementById('calc-msg');
  priceEl= priceEl|| document.getElementById('calc-price');
  frmEl  = frmEl  || document.getElementById('calc-formula');

  const excluded = window._calcExcluded || [];
  const active   = results.filter(r => !excluded.includes(r.position));

  const typeLabel = {channel:'Канал', group:'Группа', bot:'Бот'};
  let tableHtml = `<div style="overflow-x:auto"><table style="width:100%;border-collapse:collapse;font-size:.88rem">
    <thead><tr style="color:#cbbd9d;border-bottom:1px solid rgba(255,255,255,.1)">
      <th style="padding:8px 10px;text-align:left">#</th>
      <th style="padding:8px 10px;text-align:left">Название</th>
      <th style="padding:8px 10px;text-align:left">Тип</th>
      <th style="padding:8px 10px;text-align:right">Подписчики</th>
      <th style="padding:8px 10px"></th>
    </tr></thead><tbody>`;

  results.forEach(r => {
    const isExcl   = excluded.includes(r.position);
    const subs     = r.subscribers > 0 ? r.subscribers.toLocaleString('ru') : '—';
    const rowStyle = isExcl ? 'opacity:.4;text-decoration:line-through;' : '';
    tableHtml += `<tr style="border-bottom:1px solid rgba(255,255,255,.05);${rowStyle}">
      <td style="padding:8px 10px;color:#cbbd9d">${r.position}</td>
      <td style="padding:8px 10px"><b>${esc(r.name)}</b>${r.username ? '<br><span style="color:#cbbd9d;font-size:.8rem">'+esc(r.username)+'</span>':''}</td>
      <td style="padding:8px 10px;color:#cbbd9d">${esc(typeLabel[r.type]||r.type)}</td>
      <td style="padding:8px 10px;text-align:right;font-weight:600">${subs}</td>
      <td style="padding:8px 10px;text-align:center">
        <button onclick="toggleAdExclude(${r.position})" title="${isExcl?'Вернуть в расчёт':'Исключить из расчёта (реклама)'}" style="background:${isExcl?'rgba(255,193,7,.15)':'rgba(255,255,255,.07)'};border:1px solid ${isExcl?'rgba(255,193,7,.4)':'rgba(255,255,255,.15)'};color:${isExcl?'#ffe082':'#999'};border-radius:8px;padding:2px 8px;font-size:.8rem;cursor:pointer">
          ${isExcl ? '↩' : '✕'}
        </button>
      </td>
    </tr>`;
  });
  tableHtml += '</tbody></table></div>';
  tableHtml += '<p style="font-size:.78rem;color:#666;margin-top:6px">Нажмите ✕ чтобы исключить рекламный результат из расчёта.</p>';
  document.getElementById('calc-table').innerHTML = tableHtml;

  const sorted   = [...active].sort((a, b) => a.position - b.position);
  const calcFrom = sorted.find(r => r.subscribers > 0);

  if (!calcFrom) {
    msgEl.className = 'msg-err';
    msgEl.innerHTML = 'Нет результатов с данными о подписчиках для расчёта.';
    msgEl.style.display = 'block';
    priceEl.innerHTML = '';
    frmEl.innerHTML   = '';
    return;
  }

  const skipped = sorted.filter(r => r.position < calcFrom.position);

  const subs      = calcFrom.subscribers;
  const premPct   = parseInt(document.getElementById('calc-prem-pct')?.value || '30');
  const priceP1k  = parseFloat(document.getElementById('calc-period')?.value || '8');
  const premEst   = Math.round(subs * premPct / 100);
  const priceUsd  = (premEst * priceP1k / 1000).toFixed(0);
  const rubRate   = window._usdRubRate || 90;
  const priceRub  = Math.round(parseFloat(priceUsd) * rubRate).toLocaleString('ru');
  const periodLabel = {5:'7 дней', 8:'15 дней', 15:'30 дней', 40:'90 дней'}[priceP1k] || '';

  if (skipped.length > 0) {
    const skippedNames = skipped.map(r => `Топ ${r.position} (<b>${esc(r.name)}</b>)`).join(', ');
    msgEl.className = 'msg-warn';
    msgEl.innerHTML = `⚠️ ${skippedNames} — количество подписчиков не отображается, `
      + `расчёт невозможен. Нужно дождаться обновления статистики.<br>`
      + `<b>Расчёт выполнен по Топ ${calcFrom.position}.</b>`;
    msgEl.style.display = 'block';
  } else {
    msgEl.style.display = 'none';
  }

  priceEl.innerHTML = `~$${parseInt(priceUsd).toLocaleString('en')} <span style="font-size:1.1rem;color:#cbbd9d">≈ ${priceRub} ₽</span>`;
  frmEl.innerHTML =
    `Топ ${calcFrom.position}: <b>${esc(calcFrom.name)}</b> · ${subs.toLocaleString('ru')} подписчиков<br>` +
    `${subs.toLocaleString('ru')} × ${premPct}% Premium = <b>${premEst.toLocaleString('ru')} стартов</b><br>` +
    `${premEst.toLocaleString('ru')} × $${priceP1k} / 1000 (${periodLabel}) = <b>~$${parseInt(priceUsd).toLocaleString('en')}</b><br>` +
    `Курс USD/RUB: ${rubRate.toLocaleString('ru')} ₽`;

  document.getElementById('calc-results').style.display = 'block';
}

// ── USD/RUB rate ──────────────────────────────────────────────────────────────
async function loadUsdRate() {
  try {
    const r = await fetch('https://api.exchangerate-api.com/v4/latest/USD');
    const d = await r.json();
    window._usdRubRate = d.rates?.RUB || 90;
    const el = document.getElementById('calc-rub-rate');
    if (el) el.textContent = `Курс USD/RUB: ${window._usdRubRate.toFixed(2)} ₽ (обновлено только что)`;
  } catch {
    window._usdRubRate = 90;
  }
}
loadUsdRate();

function toggleAdExclude(position) {
  window._calcExcluded = window._calcExcluded || [];
  const idx = window._calcExcluded.indexOf(position);
  if (idx === -1) window._calcExcluded.push(position);
  else window._calcExcluded.splice(idx, 1);
  renderCalcTable(window._calcResults);
  document.getElementById('calc-results').style.display = 'block';
}

function openRequestFromCalc() {
  openAnalysisModal(0, '', window._calcKeyword || '');
}

// ── Analysis request modal ────────────────────────────────────────────────────
function openAnalysisModal(botId, username, keyword) {
  document.getElementById('req-bot-id').value    = botId;
  document.getElementById('req-keyword').value   = keyword || '';
  document.getElementById('req-bot-label').textContent = username ? '@' + username : '';
  document.getElementById('req-msg').style.display  = 'none';
  document.getElementById('req-file-name').textContent = '';
  document.getElementById('req-file-input').value = '';
  document.getElementById('req-modal').style.display   = 'block';
  document.getElementById('req-overlay').style.display = 'block';
}

function closeReqModal() {
  document.getElementById('req-modal').style.display   = 'none';
  document.getElementById('req-overlay').style.display = 'none';
}

async function submitRequest() {
  const botId   = document.getElementById('req-bot-id').value;
  const keyword = document.getElementById('req-keyword').value.trim();
  const notes   = document.getElementById('req-notes').value.trim();
  const file    = document.getElementById('req-file-input').files[0];
  const btn     = document.getElementById('btn-submit-req');
  const msg     = document.getElementById('req-msg');
  if (!keyword) { showMsg(msg, 'Введите ключевое слово', false); return; }

  btn.disabled = true; btn.textContent = 'Отправляем…';
  const fd = new FormData();
  fd.append('bot_id', botId);
  fd.append('keyword', keyword);
  fd.append('notes', notes);
  if (file) fd.append('screenshot', file);

  try {
    const r = await fetch('/api/smm_bots.php?action=request_analysis', { method:'POST', body: fd });
    const d = await r.json();
    if (d.ok) {
      showMsg(msg, '✅ Заявка отправлена! Модератор ответит в ближайшее время.', true);
      setTimeout(() => { closeReqModal(); showTab('requests'); }, 2000);
    } else { showMsg(msg, 'Ошибка: ' + d.error, false); }
  } catch(e) { showMsg(msg, 'Ошибка: ' + e.message, false); }
  btn.disabled = false; btn.textContent = 'Отправить заявку';
}

// ── My requests list ──────────────────────────────────────────────────────────
async function loadMyRequests() {
  document.getElementById('requests-loading').style.display = 'block';
  document.getElementById('requests-list').innerHTML = '';
  try {
    const r = await fetch('/api/smm_bots.php?action=my_requests');
    const d = await r.json();
    document.getElementById('requests-loading').style.display = 'none';
    if (!d.ok) { document.getElementById('requests-loading').textContent = 'Ошибка'; return; }
    if (!d.requests.length) {
      document.getElementById('requests-list').innerHTML = '<div class="empty-state">У вас пока нет заявок на анализ.</div>';
      return;
    }
    d.requests.forEach(req => {
      const answered = req.status === 'answered';
      const date = (req.created_at || '').slice(0,10);
      const priceBlock = (answered && req.admin_premium_count > 0)
        ? (() => {
            const p = (req.admin_premium_count * 8 / 1000).toFixed(0);
            const r = (parseFloat(p) * 90).toLocaleString('ru');
            return `<div style="margin-top:14px;padding:14px 16px;border-radius:14px;background:rgba(210,73,63,.08);border:1px solid rgba(210,73,63,.25)">
              <p style="margin:0 0 4px;color:#cbbd9d;font-size:.82rem">Расчёт стоимости Топ 1</p>
              <div style="font-size:1.6rem;font-weight:700;color:#ff9980">~$${parseInt(p).toLocaleString('en')} <span style="font-size:.9rem;color:#cbbd9d">≈ ${r} ₽</span></div>
              <div style="color:#cbbd9d;font-size:.82rem;margin-top:4px">${req.admin_premium_count.toLocaleString('ru')} Premium-стартов × $8/1000</div>
            </div>`;
          })()
        : '';
      const el = document.createElement('div');
      el.className = 'card';
      el.style.marginBottom = '12px';
      el.innerHTML = `
        <div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:10px">
          <div>
            <strong>🔑 «${esc(req.keyword)}»</strong>
            ${req.bot_username ? `<span style="color:#cbbd9d;font-size:.88rem;margin-left:8px">@${esc(req.bot_username)}</span>` : ''}
          </div>
          <span style="padding:3px 10px;border-radius:999px;font-size:.78rem;font-weight:600;${answered ? 'background:rgba(104,211,145,.15);border:1px solid rgba(104,211,145,.3);color:#68d391' : 'background:rgba(255,200,100,.1);border:1px solid rgba(255,200,100,.25);color:#f4c77b'}">${answered ? '✅ Отвечено' : '⏳ Ожидает'}</span>
        </div>
        ${req.notes ? `<p style="margin:0 0 8px;color:#cbbd9d;font-size:.88rem">${esc(req.notes)}</p>` : ''}
        <div style="color:#cbbd9d;font-size:.8rem;margin-bottom:${answered ? '10' : '0'}px">📅 Отправлено: ${date}</div>
        ${answered ? `<div style="padding:14px 16px;border-radius:14px;background:rgba(104,211,145,.06);border:1px solid rgba(104,211,145,.2);margin-top:10px">
          <p style="margin:0 0 6px;color:#68d391;font-size:.82rem;font-weight:600">💬 Ответ модератора</p>
          <p style="margin:0;color:#d6ffe4;font-size:.9rem;line-height:1.6;white-space:pre-wrap">${esc(req.admin_response)}</p>
        </div>${priceBlock}` : ''}`;
      document.getElementById('requests-list').appendChild(el);
    });
  } catch(e) {
    document.getElementById('requests-loading').textContent = 'Ошибка: ' + e.message;
  }
}

// Init
loadBots();
</script>
</body>
</html>
