/** Account picker for broadcast (adapted from ugbrand AccountPicker). */
window._ap = window._ap || {};

class AccountPicker {
  constructor(config) {
    this.container = document.getElementById(config.containerId);
    this.perPage = config.perPage || 20;
    this.perPageOptions = config.perPageOptions || [10, 20, 50];
    this.onSelectionChange = config.onSelectionChange || (() => {});
    this.accounts = [];
    this.projects = [];
    this.filtered = [];
    this.selected = new Set();
    this.page = 1;
    this.uid = 'ap_' + Math.random().toString(36).slice(2, 8);
    window._ap[this.uid] = this;
    this._buildHtml();
  }

  _buildHtml() {
    const u = this.uid;
    const ppOpts = this.perPageOptions.map(n =>
      `<option value="${n}"${n === this.perPage ? ' selected' : ''}>${n}</option>`
    ).join('');
    this.container.innerHTML = `
      <div class="ap-toolbar">
        <div class="ap-search-wrap">
          <input type="text" id="${u}_search" placeholder="🔍 Поиск" class="ap-search" />
          <span id="${u}_count" class="ap-count"></span>
        </div>
        <select id="${u}_project" class="ap-filter"><option value="">Все проекты</option><option value="0">Без проекта</option></select>
        <select id="${u}_status" class="ap-filter">
          <option value="">Все статусы</option>
          <option value="ready">✓ Готов</option>
          <option value="resting">😴 Отдых</option>
          <option value="spamblock">🤖 Спамблок</option>
          <option value="offline">○ Offline</option>
          <option value="problems">⚠ Проблемные</option>
        </select>
        <button type="button" class="ghost mini ap-reset" id="${u}_reset">Сбросить</button>
      </div>
      <div class="ap-table-head">
        <span class="ap-col-chk"><input type="checkbox" id="${u}_selall" title="Страница" /></span>
        <span class="ap-col-acc">Аккаунт</span>
        <span class="ap-col-st">Статус</span>
        <span class="ap-col-day">Сегодня</span>
        <span class="ap-col-prj">Проект</span>
      </div>
      <div id="${u}_rows" class="ap-rows"></div>
      <div class="ap-footer">
        <span id="${u}_selinfo" class="ap-selinfo">Выбрано: 0</span>
        <button type="button" class="ghost mini" id="${u}_selpage">Выбрать ${this.perPage}</button>
        <button type="button" class="ghost mini" id="${u}_selallf">Выбрать все (0)</button>
        <button type="button" class="ghost mini" id="${u}_clear">Сбросить</button>
        <div class="ap-pager">
          <button type="button" class="ghost mini" id="${u}_prev">‹</button>
          <span id="${u}_pageinfo">1</span>
          <button type="button" class="ghost mini" id="${u}_next">›</button>
          <select id="${u}_pp" class="ap-pp">${ppOpts}</select>
        </div>
      </div>`;

    this.container.querySelector(`#${u}_search`).oninput = () => this.filter();
    this.container.querySelector(`#${u}_project`).onchange = () => this.filter();
    this.container.querySelector(`#${u}_status`).onchange = () => this.filter();
    this.container.querySelector(`#${u}_reset`).onclick = () => this.resetFilters();
    this.container.querySelector(`#${u}_selall`).onchange = e => this.togglePageAll(e.target);
    this.container.querySelector(`#${u}_selpage`).onclick = () => this.selectPage();
    this.container.querySelector(`#${u}_selallf`).onclick = () => this.selectAllFiltered();
    this.container.querySelector(`#${u}_clear`).onclick = () => this.clearSelection();
    this.container.querySelector(`#${u}_prev`).onclick = () => this.goPage(-1);
    this.container.querySelector(`#${u}_next`).onclick = () => this.goPage(1);
    this.container.querySelector(`#${u}_pp`).onchange = e => {
      this.perPage = Number(e.target.value) || 20;
      this.page = 1;
      this.render();
    };
  }

  _statusKey(a) {
    if (a.spam_blocked) return 'spamblock';
    const ps = (a.pool_status || 'offline').toLowerCase();
    if (ps === 'online') return 'ready';
    if (ps === 'resting') return 'resting';
    return 'offline';
  }

  _statusHtml(a) {
    const k = this._statusKey(a);
    const map = {
      ready: ['tag-ok', 'Активный'],
      resting: ['tag-warn', 'Отдых'],
      spamblock: ['tag-bad', a.spam_label || 'Спамблок'],
      offline: ['tag-bad', 'Offline'],
    };
    const [cls, label] = map[k] || ['', k];
    return `<span class="tag ${cls}">${label}</span>`;
  }

  setProjects(projects) {
    this.projects = projects || [];
    const sel = this.container.querySelector(`#${this.uid}_project`);
    const cur = sel.value;
    sel.innerHTML = '<option value="">Все проекты</option><option value="0">Без проекта</option>'
      + this.projects.map(p => `<option value="${p.id}">${p.name}</option>`).join('');
    sel.value = cur;
  }

  setAccounts(accounts) {
    this.accounts = accounts || [];
    this.filter();
  }

  setSelectedPhones(phones) {
    this.selected = new Set(phones || []);
    this.render();
    this._emit();
  }

  getSelectedPhones() {
    return [...this.selected];
  }

  resetFilters() {
    const u = this.uid;
    this.container.querySelector(`#${u}_search`).value = '';
    this.container.querySelector(`#${u}_project`).value = '';
    this.container.querySelector(`#${u}_status`).value = '';
    this.filter();
  }

  filter() {
    const u = this.uid;
    const q = (this.container.querySelector(`#${u}_search`).value || '').toLowerCase().trim();
    const proj = this.container.querySelector(`#${u}_project`).value;
    const st = this.container.querySelector(`#${u}_status`).value;
    this.filtered = this.accounts.filter(a => {
      if (q) {
        const hay = `${a.phone} ${a.username || ''} ${a.project_name || ''}`.toLowerCase();
        if (!hay.includes(q)) return false;
      }
      if (proj !== '') {
        const pid = a.project_id != null ? String(a.project_id) : '0';
        if (proj === '0' ? a.project_id != null : pid !== proj) return false;
      }
      const sk = this._statusKey(a);
      if (st === 'problems') {
        if (!['spamblock', 'resting', 'offline'].includes(sk)) return false;
      } else if (st && sk !== st) return false;
      return true;
    });
    this.page = 1;
    this.render();
  }

  _pageItems() {
    const start = (this.page - 1) * this.perPage;
    return this.filtered.slice(start, start + this.perPage);
  }

  _totalPages() {
    return Math.max(1, Math.ceil(this.filtered.length / this.perPage));
  }

  goPage(delta) {
    this.page = Math.min(this._totalPages(), Math.max(1, this.page + delta));
    this.render();
  }

  togglePageAll(cb) {
    this._pageItems().forEach(a => {
      if (cb.checked) this.selected.add(a.phone);
      else this.selected.delete(a.phone);
    });
    this.render();
    this._emit();
  }

  selectPage() {
    this._pageItems().forEach(a => this.selected.add(a.phone));
    this.render();
    this._emit();
  }

  selectAllFiltered() {
    this.filtered.forEach(a => this.selected.add(a.phone));
    this.render();
    this._emit();
  }

  clearSelection() {
    this.selected.clear();
    this.render();
    this._emit();
  }

  togglePhone(phone, checked) {
    if (checked) this.selected.add(phone);
    else this.selected.delete(phone);
    this.render();
    this._emit();
  }

  _emit() {
    this.onSelectionChange(this.getSelectedPhones());
  }

  render() {
    const u = this.uid;
    const items = this._pageItems();
    const rows = this.container.querySelector(`#${u}_rows`);
    const esc = window.esc || (s => String(s ?? ''));
    rows.innerHTML = items.length ? items.map(a => {
      const checked = this.selected.has(a.phone) ? ' checked' : '';
      const rowCls = checked ? ' ap-row-selected' : '';
      const day = `${a.daily_sent || 0}/${a.daily_limit || 40}`;
      const un = a.username ? `@${esc(a.username)}` : '—';
      return `<label class="ap-row${rowCls}">
        <span class="ap-col-chk"><input type="checkbox"${checked} data-phone="${esc(a.phone)}" /></span>
        <span class="ap-col-acc"><b>${esc(a.phone)}</b><span class="sub">${un}</span></span>
        <span class="ap-col-st">${this._statusHtml(a)}</span>
        <span class="ap-col-day">${day}</span>
        <span class="ap-col-prj">${esc(a.project_name || '—')}</span>
      </label>`;
    }).join('') : '<div class="empty ap-empty">Нет аккаунтов по фильтру</div>';

    rows.querySelectorAll('input[type=checkbox]').forEach(chk => {
      chk.onchange = () => this.togglePhone(chk.dataset.phone, chk.checked);
    });

    const cnt = this.container.querySelector(`#${u}_count`);
    if (cnt) cnt.textContent = String(this.filtered.length);
    const selinfo = this.container.querySelector(`#${u}_selinfo`);
    if (selinfo) selinfo.textContent = `Выбрано: ${this.selected.size}`;
    const selallf = this.container.querySelector(`#${u}_selallf`);
    if (selallf) selallf.textContent = `Выбрать все (${this.filtered.length})`;
    const pageinfo = this.container.querySelector(`#${u}_pageinfo`);
    if (pageinfo) pageinfo.textContent = `${this.page} / ${this._totalPages()}`;
    const selall = this.container.querySelector(`#${u}_selall`);
    if (selall) {
      const allOnPage = items.length > 0 && items.every(a => this.selected.has(a.phone));
      selall.checked = allOnPage;
      selall.indeterminate = !allOnPage && items.some(a => this.selected.has(a.phone));
    }
  }
}

window.AccountPicker = AccountPicker;
