(function () {
  'use strict';
  var LS_THEME = 'phonebook.theme';

  function $(id) { return document.getElementById(id); }
  function el(tag, attrs, children) {
    var n = document.createElement(tag);
    if (attrs) for (var k in attrs) {
      if (k === 'class') n.className = attrs[k];
      else if (k === 'onclick') n.addEventListener('click', attrs[k]);
      else if (k === 'hidden') { if (attrs[k]) n.setAttribute('hidden',''); }
      else if (k in n) { try { n[k] = attrs[k]; } catch (_) { n.setAttribute(k, attrs[k]); } }
      else n.setAttribute(k, attrs[k]);
    }
    if (children) children.forEach(function (c) {
      if (c == null) return;
      if (typeof c === 'string') n.appendChild(document.createTextNode(c));
      else n.appendChild(c);
    });
    return n;
  }
  var FA = '۰۱۲۳۴۵۶۷۸۹';
  function toFa(n) { return String(n).replace(/\d/g, function (d) { return FA[+d]; }); }
  function normDigits(s) {
    if (!s) return '';
    return String(s)
      .replace(/[۰-۹]/g, function (c) { return '۰۱۲۳۴۵۶۷۸۹'.indexOf(c); })
      .replace(/[٠-٩]/g, function (c) { return '٠١٢٣٤٥٦٧٨٩'.indexOf(c); });
  }
  function buildHaystack(c) {
    var parts = [
      c.firstName, c.lastName, c.role,
      c.landline, c.internal, c.phone,
      c.telegram, c.rubika, c.eitaa, c.bale, c.whatsapp,
      c.email, c.description
    ];
    if (c.suggestedBy) parts.push(c.suggestedBy.name, c.suggestedBy.contact);
    return normDigits(parts.filter(Boolean).join(' ').toLowerCase());
  }

  function api(action, opts) {
    opts = opts || {};
    var url = '../api.php?action=' + encodeURIComponent(action);
    var init = { method: opts.method || 'GET', credentials: 'same-origin' };
    if (opts.body instanceof FormData) init.body = opts.body;
    else if (opts.body) { init.headers = { 'Content-Type': 'application/json' }; init.body = JSON.stringify(opts.body); }
    return fetch(url, init).then(function (r) {
      return r.json().then(function (j) { if (!j.ok) throw new Error(j.error || 'خطا'); return j; });
    });
  }

  function openModal(id) { var m = $(id); if (m) m.hidden = false; document.body.style.overflow = 'hidden'; }
  function closeModal(id) { var m = $(id); if (m) m.hidden = true; document.body.style.overflow = ''; }
  document.addEventListener('click', function (ev) {
    var t = ev.target;
    if (t.matches && t.matches('[data-close]')) {
      var modal = t.closest('.modal'); if (modal) closeModal(modal.id);
    }
  });
  document.addEventListener('keydown', function (ev) {
    if (ev.key === 'Escape') {
      document.querySelectorAll('.modal:not([hidden])').forEach(function (m) { closeModal(m.id); });
    }
  });

  // theme
  function applyTheme(t) {
    document.documentElement.setAttribute('data-theme', t);
    var btn = $('themeToggle'); if (btn) btn.textContent = t === 'dark' ? '☀️' : '🌙';
    try { localStorage.setItem(LS_THEME, t); } catch (_) {}
  }
  (function () {
    var t = 'dark';
    try { var s = localStorage.getItem(LS_THEME); if (s === 'dark' || s === 'light') t = s; } catch (_) {}
    applyTheme(t);
  })();
  document.addEventListener('click', function (ev) {
    if (ev.target && ev.target.id === 'themeToggle') {
      var c = document.documentElement.getAttribute('data-theme') || 'dark';
      applyTheme(c === 'dark' ? 'light' : 'dark');
    }
  });

  // ---------- state ----------
  var CONFIG = {};
  var CURRENT_TAB = 'pending';
  var CURRENT_ITEMS = [];
  var SEARCH_Q = '';

  // ---------- views ----------
  function showLogin() { $('loginView').hidden = false; $('panelView').hidden = true; }
  function enterPanel(label) {
    $('loginView').hidden = true;
    $('panelView').hidden = false;
    $('adminLabel').textContent = 'خوش آمدی، ' + (label || 'مدیر');
    // populate dept selects
    var sel = $('editDept');
    if (sel && sel.options.length <= 1) {
      (CONFIG.departments || []).forEach(function (d) {
        var o = document.createElement('option');
        o.value = d.id; o.textContent = d.icon + ' ' + d.label;
        sel.appendChild(o);
      });
    }
    loadTab(CURRENT_TAB);
    refreshCounts();
  }

  // ---------- login ----------
  $('loginForm').addEventListener('submit', function (ev) {
    ev.preventDefault();
    var pw = ev.target.password.value;
    var err = $('loginError'); err.style.display = 'none';
    var fd = new FormData(); fd.append('password', pw);
    api('admin-login', { method: 'POST', body: fd }).then(function (j) {
      enterPanel(j.label);
    }).catch(function (e) {
      err.textContent = e.message || 'ورود ناموفق';
      err.style.display = 'block';
    });
  });

  $('btnLogout').addEventListener('click', function () {
    api('admin-logout', { method: 'POST' }).finally(function () {
      CURRENT_ITEMS = []; CURRENT_TAB = 'pending';
      $('adminList').innerHTML = '';
      showLogin();
    });
  });

  // ---------- tabs ----------
  document.querySelectorAll('.admin-tab').forEach(function (btn) {
    btn.addEventListener('click', function () {
      document.querySelectorAll('.admin-tab').forEach(function (b) { b.classList.remove('is-active'); });
      btn.classList.add('is-active');
      CURRENT_TAB = btn.dataset.tab;
      loadTab(CURRENT_TAB);
    });
  });

  // ---------- search ----------
  (function () {
    var input = $('adminSearch');
    var clear = $('adminSearchClear');
    if (!input) return;
    var t = null;
    input.addEventListener('input', function () {
      SEARCH_Q = input.value || '';
      if (clear) clear.hidden = !SEARCH_Q;
      if (t) clearTimeout(t);
      t = setTimeout(renderList, 80);
    });
    if (clear) {
      clear.addEventListener('click', function () {
        input.value = ''; SEARCH_Q = '';
        clear.hidden = true;
        input.focus();
        renderList();
      });
    }
  })();

  function refreshCounts() {
    ['pending','approved','rejected'].forEach(function (st) {
      api('admin-list', { method: 'GET', body: null }).catch(function () { return { count: 0 }; });
    });
    // Use one call per status to keep it simple
    ['pending','approved','rejected'].forEach(function (st) {
      fetch('../api.php?action=admin-list&status=' + st, { credentials: 'same-origin' })
        .then(function (r) { return r.json(); })
        .then(function (j) {
          if (!j.ok) return;
          var map = { pending: 'cntPending', approved: 'cntApproved', rejected: 'cntRejected' };
          var n = $(map[st]); if (n) n.textContent = toFa(j.count || 0);
        });
    });
  }

  function loadTab(status) {
    var list = $('adminList'); list.innerHTML = '<div style="padding:20px; text-align:center; color:var(--text-dim);">در حال بارگذاری…</div>';
    fetch('../api.php?action=admin-list&status=' + status, { credentials: 'same-origin' })
      .then(function (r) { return r.json(); })
      .then(function (j) {
        if (!j.ok) throw new Error(j.error || 'خطا');
        CURRENT_ITEMS = j.contacts || [];
        CURRENT_ITEMS.forEach(function (c) { c.__hs = buildHaystack(c); });
        renderList();
      })
      .catch(function (e) { list.innerHTML = '<div style="padding:20px; text-align:center; color:var(--danger);">' + (e.message || 'خطا') + '</div>'; });
  }

  function currentFiltered() {
    if (!SEARCH_Q) return CURRENT_ITEMS;
    var q = normDigits(String(SEARCH_Q).toLowerCase().trim());
    if (!q) return CURRENT_ITEMS;
    var tokens = q.split(/\s+/).filter(Boolean);
    return CURRENT_ITEMS.filter(function (c) {
      var hs = c.__hs || buildHaystack(c);
      for (var i = 0; i < tokens.length; i++) if (hs.indexOf(tokens[i]) === -1) return false;
      return true;
    });
  }

  function initials(c) {
    var fn = (c.firstName || '').trim(), ln = (c.lastName || '').trim();
    return (fn && ln) ? (fn[0] + ln[0]) : (fn[0] || ln[0] || '?');
  }
  function fullName(c) { return ((c.firstName || '') + ' ' + (c.lastName || '')).trim() || '—'; }
  function deptLabel(id) {
    var d = (CONFIG.departments || []).find(function (x) { return x.id === id; });
    return d ? (d.icon + ' ' + d.label) : '';
  }

  function renderList() {
    var list = $('adminList'); list.innerHTML = '';
    var items = currentFiltered();
    var rc = $('adminResultCount');
    if (rc) {
      if (SEARCH_Q) {
        rc.textContent = 'نمایش ' + toFa(items.length) + ' از ' + toFa(CURRENT_ITEMS.length) + ' مخاطب';
      } else {
        rc.textContent = CURRENT_ITEMS.length ? (toFa(CURRENT_ITEMS.length) + ' مخاطب') : '';
      }
    }
    if (!items.length) {
      $('adminEmpty').hidden = false;
      var em = $('adminEmpty');
      var h3 = em.querySelector('h3'), p = em.querySelector('p');
      if (SEARCH_Q && CURRENT_ITEMS.length) {
        if (h3) h3.textContent = 'نتیجه‌ای یافت نشد';
        if (p) p.textContent = 'عبارت جستجو را تغییر دهید یا پاک کنید.';
      } else {
        if (h3) h3.textContent = 'خالی است';
        if (p) p.textContent = 'در این بخش هنوز مخاطبی وجود ندارد.';
      }
      return;
    }
    $('adminEmpty').hidden = true;

    items.forEach(function (c) {
      var card = el('div', { class: 'admin-card' });

      var av = el('div', { class: 'avatar' });
      if (c.photo) av.appendChild(el('img', { src: '../' + c.photo, alt: '' }));
      else av.appendChild(el('div', { class: 'avatar-fallback' }, [initials(c)]));
      card.appendChild(av);

      var body = el('div', { class: 'admin-card-body' });
      body.appendChild(el('div', { class: 'admin-card-name' }, [fullName(c)]));
      if (c.role) body.appendChild(el('div', { class: 'admin-card-role' }, [c.role]));

      var meta = el('div', { class: 'admin-card-meta' });
      if (c.department) meta.appendChild(el('span', {}, [deptLabel(c.department)]));
      if (c.landline) meta.appendChild(el('span', {}, ['📞 ' + c.landline]));
      if (c.phone) meta.appendChild(el('span', {}, ['📱 ' + c.phone]));
      if (c.telegram) meta.appendChild(el('span', {}, ['✈️ @' + c.telegram]));
      if (c.rubika) meta.appendChild(el('span', {}, ['🇮🇷 @' + c.rubika]));
      if (c.eitaa) meta.appendChild(el('span', {}, ['⛰️ @' + c.eitaa]));
      if (c.email) meta.appendChild(el('span', {}, ['📧 ' + c.email]));
      meta.appendChild(el('span', { class: 'status-pill ' + (c.status || 'pending') }, [
        c.status === 'approved' ? '✅ تأیید شده' : c.status === 'rejected' ? '❌ رد شده' : '⏳ در انتظار'
      ]));
      if (c.suggestedBy && c.suggestedBy.name) meta.appendChild(el('span', {}, ['پیشنهاددهنده: ' + c.suggestedBy.name + (c.suggestedBy.contact ? ' (' + c.suggestedBy.contact + ')' : '')]));
      body.appendChild(meta);

      if (c.description) body.appendChild(el('div', { style: 'color:var(--text-dim); font-size:12px; margin-top:4px;' }, [c.description]));
      card.appendChild(body);

      var actions = el('div', { class: 'admin-card-actions' });
      if (c.status !== 'approved') {
        actions.appendChild(el('button', { class: 'btn-success', onclick: function () { decide(c.id, 'approve'); } }, ['✅ تأیید']));
      }
      if (c.status !== 'rejected') {
        actions.appendChild(el('button', { class: 'btn-secondary', onclick: function () { decide(c.id, 'reject'); } }, ['❌ رد']));
      }
      actions.appendChild(el('button', { class: 'btn-secondary', onclick: function () { openEdit(c); } }, ['✏️ ویرایش']));
      actions.appendChild(el('button', { class: 'btn-danger', onclick: function () {
        if (confirm('این مخاطب کاملاً حذف شود؟')) decide(c.id, 'delete');
      } }, ['🗑 حذف']));
      card.appendChild(actions);

      list.appendChild(card);
    });
  }

  function decide(id, d) {
    var fd = new FormData(); fd.append('id', id); fd.append('decision', d);
    api('admin-decision', { method: 'POST', body: fd }).then(function () {
      loadTab(CURRENT_TAB); refreshCounts();
    }).catch(function (e) { alert(e.message); });
  }

  // ---------- create/edit ----------
  $('btnNewContact').addEventListener('click', function () {
    var form = $('editForm'); form.reset();
    $('editId').value = '';
    $('editTitle').textContent = '➕ مخاطب جدید';
    openModal('editModal');
  });

  function openEdit(c) {
    var form = $('editForm'); form.reset();
    $('editTitle').textContent = '✏️ ویرایش مخاطب';
    $('editId').value = c.id || '';
    ['firstName','lastName','role','department','landline','internal','phone',
     'telegram','rubika','eitaa','bale','email','description'].forEach(function (k) {
      if (form.elements[k]) form.elements[k].value = c[k] || '';
    });
    openModal('editModal');
  }

  $('editForm').addEventListener('submit', function (ev) {
    ev.preventDefault();
    var form = ev.target;
    var btn = form.querySelector('button[type="submit"]');
    btn.disabled = true; btn.textContent = 'در حال ذخیره…';
    var fd = new FormData(form);
    api('admin-save', { method: 'POST', body: fd }).then(function (j) {
      closeModal('editModal');
      $('successMessage').textContent = j.message || 'ذخیره شد';
      openModal('successModal');
      loadTab(CURRENT_TAB); refreshCounts();
    }).catch(function (e) { alert(e.message); })
      .finally(function () { btn.disabled = false; btn.textContent = 'ذخیره'; });
  });

  // ---------- init ----------
  function loadConfig() {
    return fetch('../api.php?action=config', { credentials: 'same-origin' })
      .then(function (r) { return r.json(); }).then(function (j) { if (j.ok) CONFIG = j; });
  }
  function checkAuth() {
    return fetch('../api.php?action=admin-status', { credentials: 'same-origin' })
      .then(function (r) { return r.json(); })
      .then(function (j) {
        if (j.ok && j.admin) enterPanel(j.label);
        else showLogin();
      });
  }
  loadConfig().then(checkAuth);
})();
