(function () {
  'use strict';

  var body = document.body;
  if (!body || body.getAttribute('data-ua-link-approval-prompt') !== '1') return;

  var endpoint = 'api/link_approval_prompt.php';
  var currentId = 0;
  var csrf = '';
  var busy = false;
  var snoozedUntil = 0;

  var overlay = document.createElement('div');
  overlay.className = 'ua-link-permission';
  overlay.hidden = true;
  overlay.innerHTML = ''
    + '<section class="ua-link-permission__dialog" role="alertdialog" aria-modal="true" aria-labelledby="uaLinkPermissionTitle">'
    + '  <div class="ua-link-permission__mark"><i class="fa fa-link" aria-hidden="true"></i></div>'
    + '  <div class="ua-link-permission__eyebrow">طلب إذن جديد</div>'
    + '  <h2 id="uaLinkPermissionTitle">الموافقة على ربط نسخة</h2>'
    + '  <p class="ua-link-permission__copy">تطلب نسخة جديدة الاتصال بهذه النسخة الرئيسية. راجع بياناتها قبل منح الإذن.</p>'
    + '  <div class="ua-link-permission__identity"><strong data-link-name></strong><span data-link-type></span></div>'
    + '  <dl class="ua-link-permission__details">'
    + '    <div><dt>طريقة الاتصال</dt><dd data-link-mode></dd></div>'
    + '    <div><dt>عنوان الجهاز</dt><dd data-link-ip dir="ltr"></dd></div>'
    + '    <div class="ua-link-permission__wide"><dt>عنوان النسخة الرئيسية المدخل</dt><dd data-link-url dir="ltr"></dd></div>'
    + '  </dl>'
    + '  <p class="ua-link-permission__status" data-link-status hidden></p>'
    + '  <footer class="ua-link-permission__actions">'
    + '    <button class="ua-link-permission__approve" type="button"><i class="fa fa-check"></i><span>موافقة وربط</span></button>'
    + '    <button class="ua-link-permission__reject" type="button"><i class="fa fa-times"></i><span>رفض</span></button>'
    + '    <button class="ua-link-permission__later" type="button">لاحقاً</button>'
    + '  </footer>'
    + '</section>';
  document.body.appendChild(overlay);

  var dialog = overlay.querySelector('.ua-link-permission__dialog');
  var statusBox = overlay.querySelector('[data-link-status]');
  var approveButton = overlay.querySelector('.ua-link-permission__approve');
  var rejectButton = overlay.querySelector('.ua-link-permission__reject');

  function text(selector, value) {
    var node = overlay.querySelector(selector);
    if (node) node.textContent = value || '—';
  }

  function setBusy(value) {
    busy = value;
    approveButton.disabled = value;
    rejectButton.disabled = value;
    overlay.classList.toggle('is-busy', value);
  }

  function showRequest(request) {
    currentId = Number(request.id || 0);
    text('[data-link-name]', request.instance_name);
    text('[data-link-type]', request.install_type_label);
    text('[data-link-mode]', request.connection_mode_label);
    text('[data-link-ip]', request.remote_addr);
    text('[data-link-url]', request.server_url || request.reported_url);
    statusBox.hidden = true;
    statusBox.textContent = '';
    overlay.hidden = false;
    requestAnimationFrame(function () {
      overlay.classList.add('is-open');
      approveButton.focus();
    });
  }

  function hidePrompt() {
    overlay.classList.remove('is-open');
    window.setTimeout(function () { overlay.hidden = true; }, 180);
  }

  function poll() {
    if (busy || Date.now() < snoozedUntil) return;
    fetch(endpoint, { credentials: 'same-origin', headers: { Accept: 'application/json' } })
      .then(function (response) { return response.json(); })
      .then(function (payload) {
        if (!payload || !payload.ok) return;
        csrf = payload.csrf || csrf;
        if (payload.request) {
          if (Number(payload.request.id) !== currentId || overlay.hidden) showRequest(payload.request);
        } else if (!overlay.hidden) {
          currentId = 0;
          hidePrompt();
        }
      })
      .catch(function () {});
  }

  function decide(decision) {
    if (busy || !currentId) return;
    setBusy(true);
    statusBox.hidden = false;
    statusBox.textContent = decision === 'approve' ? 'جارٍ اعتماد الربط...' : 'جارٍ رفض الطلب...';
    var form = new URLSearchParams();
    form.set('request_id', String(currentId));
    form.set('decision', decision);
    form.set('ua_csrf', csrf);
    fetch(endpoint, {
      method: 'POST', credentials: 'same-origin',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', Accept: 'application/json' },
      body: form.toString()
    })
      .then(function (response) { return response.json(); })
      .then(function (payload) {
        if (!payload || !payload.ok) throw new Error(payload && payload.message ? payload.message : 'تعذر تنفيذ القرار.');
        statusBox.textContent = payload.message;
        statusBox.classList.add('is-success');
        currentId = 0;
        window.setTimeout(function () { hidePrompt(); setBusy(false); poll(); }, 650);
      })
      .catch(function (error) {
        statusBox.textContent = error.message || 'تعذر تنفيذ القرار.';
        statusBox.classList.remove('is-success');
        setBusy(false);
      });
  }

  approveButton.addEventListener('click', function () { decide('approve'); });
  rejectButton.addEventListener('click', function () { decide('reject'); });
  overlay.querySelector('.ua-link-permission__later').addEventListener('click', function () {
    snoozedUntil = Date.now() + 60000;
    hidePrompt();
  });
  dialog.addEventListener('click', function (event) { event.stopPropagation(); });

  poll();
  window.setInterval(poll, 6000);
}());

