'use strict';
/* admin → permissions section (role-based teacher/student permissions) */
(function () {
  'use strict';
  let inited = false;
  let _permData = null;

  async function load() {
    try {
      _permData = await LS.getPermissions();
      renderPermissions();
    } catch(e) {
      document.getElementById('perm-teacher').innerHTML =
        `<p style="color:var(--danger);font-size:13px">Ошибка загрузки: ${esc(e.message)}</p>`;
    }
  }

  function renderPermissions() {
    if (!_permData) return;
    const { permissions, definitions } = _permData;
    ['teacher', 'student'].forEach(role => {
      const container = document.getElementById('perm-' + role);
      const defs = definitions.filter(d => d.role === role);
      container.innerHTML = defs.map(def => {
        const enabled = permissions[role]?.[def.key] ?? def.default;
        const isModified = (enabled ? 1 : 0) !== def.default;
        const modDot = isModified
          ? `<span class="perm-modified-dot" title="Отличается от значения по умолчанию"></span>`
          : '';
        return `
          <div class="perm-card${enabled ? ' enabled' : ''}" id="perm-card-${role}-${def.key.replace('.','_')}">
            <div class="perm-info">
              <div class="perm-label">${esc(def.label)}${modDot}</div>
              <div class="perm-desc">${esc(def.desc)}</div>
            </div>
            <label class="perm-toggle" title="${enabled ? 'Выключить' : 'Включить'}">
              <input type="checkbox" ${enabled ? 'checked' : ''}
                onchange="togglePermission('${esc(role)}','${esc(def.key)}',this.checked,this)">
              <span class="perm-track"></span>
              <span class="perm-thumb"></span>
            </label>
          </div>`;
      }).join('');
    });
  }

  async function togglePermission(role, key, enabled, checkbox) {
    if (!enabled) {
      const def = (_permData.definitions || []).find(d => d.role === role && d.key === key);
      if (def && def.requireConfirmOff) {
        const roleLabel = role === 'teacher' ? 'Учитель' : 'Ученик';
        const ok = await LS.confirm(
          `Выключение «${def.label}» затронет всех пользователей роли «${roleLabel}». Они потеряют доступ. Продолжить?`,
          { title: 'Подтвердите выключение права', confirmText: 'Выключить' }
        );
        if (!ok) { checkbox.checked = true; return; }
      }
    }
    checkbox.disabled = true;
    try {
      await LS.setPermission(role, key, enabled);
      if (!_permData.permissions[role]) _permData.permissions[role] = {};
      _permData.permissions[role][key] = enabled;
      const safeKey = key.replace('.', '_');
      const card = document.getElementById(`perm-card-${role}-${safeKey}`);
      if (card) card.classList.toggle('enabled', enabled);
      // Re-render to refresh the modified-dot indicator across all cards.
      renderPermissions();
      LS.toast(enabled ? 'Право включено' : 'Право отключено', 'success');
    } catch(e) {
      checkbox.checked = !enabled;
      LS.toast('Ошибка: ' + e.message, 'error');
    } finally {
      checkbox.disabled = false;
    }
  }

  function filterPermissions(query) {
    const q = (query || '').trim().toLowerCase();
    ['teacher', 'student'].forEach(role => {
      const block = document.querySelector(`#perm-${role}`)?.closest('.perm-role-block');
      const cards = document.querySelectorAll(`#perm-${role} .perm-card`);
      let visibleCount = 0;
      cards.forEach(card => {
        const label = (card.querySelector('.perm-label')?.textContent || '').toLowerCase();
        const desc  = (card.querySelector('.perm-desc')?.textContent  || '').toLowerCase();
        const show  = !q || label.includes(q) || desc.includes(q);
        card.style.display = show ? '' : 'none';
        if (show) visibleCount++;
      });
      if (block) block.style.display = visibleCount === 0 ? 'none' : '';
    });
  }

  window.togglePermission = togglePermission;
  window.filterPermissions = filterPermissions;

  window.AdminSections = window.AdminSections || {};
  window.AdminSections.permissions = {
    init: async () => { if (inited) return; inited = true; await load(); },
    reload: load,
  };
})();
