(function () {
  'use strict';
  var configNode = document.getElementById('abcCalendarConfig');
  var calendar = document.getElementById('abcCalendar');
  if (!configNode || !calendar) return;

  var cfg;
  try { cfg = JSON.parse(configNode.textContent || '{}'); } catch (e) { return; }

  var dayMs = 86400000;
  var mode = 'reminder';
  var weekdays = ['أحد', 'اثن', 'ثلا', 'أرب', 'خمي', 'جمع', 'سبت'];
  var inputs = {
    cycleDay: document.getElementById('abcCycleDay'),
    generationLead: document.getElementById('abcGenerationLead'),
    dueAfter: document.getElementById('abcDueAfter'),
    graceDays: document.getElementById('abcGraceDays'),
    limitAfter: document.getElementById('abcLimitAfter'),
    cutAfter: document.getElementById('abcCutAfter'),
    remindersEnabled: document.getElementById('abcRemindersEnabled'),
    limitEnabled: document.getElementById('abcLimitEnabled'),
    cutEnabled: document.getElementById('abcCutEnabled'),
    offsets: document.getElementById('abcReminderOffsets')
  };

  function localDate(value) {
    if (value instanceof Date) return new Date(value.getFullYear(), value.getMonth(), value.getDate());
    var parts = String(value || '').split('-').map(Number);
    return new Date(parts[0], (parts[1] || 1) - 1, parts[2] || 1);
  }
  function iso(date) {
    var y = date.getFullYear();
    var m = String(date.getMonth() + 1).padStart(2, '0');
    var d = String(date.getDate()).padStart(2, '0');
    return y + '-' + m + '-' + d;
  }
  function addDays(date, days) {
    var next = new Date(date.getFullYear(), date.getMonth(), date.getDate());
    next.setDate(next.getDate() + Number(days || 0));
    return next;
  }
  function diffDays(date, base) {
    return Math.round((localDate(date).getTime() - localDate(base).getTime()) / dayMs);
  }
  function n(input, fallback) {
    var value = parseInt(input && input.value, 10);
    return Number.isFinite(value) ? value : fallback;
  }
  function reminderOffsets() {
    return String(inputs.offsets.value || '').split(',').map(Number).filter(Number.isFinite)
      .filter(function (value, index, all) { return value >= -28 && value <= 60 && all.indexOf(value) === index; })
      .sort(function (a, b) { return a - b; });
  }
  function setOffsets(values) {
    inputs.offsets.value = values.sort(function (a, b) { return a - b; }).join(',');
  }
  function previewStart() {
    var base = localDate(cfg.previewStart);
    var wantedDay = Math.max(1, Math.min(28, n(inputs.cycleDay, cfg.cycleDay || 1)));
    base.setDate(wantedDay);
    return base;
  }
  function schedule() {
    var cycle = previewStart();
    var due = addDays(cycle, Math.max(0, n(inputs.dueAfter, 0)));
    var grace = addDays(due, Math.max(0, n(inputs.graceDays, 0)));
    var reminders = reminderOffsets().map(function (offset) {
      return { type: 'reminder', label: 'رسالة تنبيه', date: addDays(due, offset), offset: offset };
    });
    return {
      cycle: cycle,
      generation: addDays(cycle, -Math.max(0, n(inputs.generationLead, 0))),
      due: due,
      grace: grace,
      reminders: reminders,
      limit: addDays(grace, Math.max(0, n(inputs.limitAfter, 0))),
      cut: addDays(grace, Math.max(0, n(inputs.cutAfter, 0)))
    };
  }
  function allEvents(plan) {
    var events = [
      { type: 'generation', label: 'إنشاء الفاتورة', date: plan.generation, enabled: true },
      { type: 'cycle', label: 'بداية الدورة', date: plan.cycle, enabled: true },
      { type: 'due', label: 'الاستحقاق', date: plan.due, enabled: true },
      { type: 'grace', label: 'نهاية السماح', date: plan.grace, enabled: true }
    ];
    if (inputs.remindersEnabled.checked) events = events.concat(plan.reminders.map(function (event) { event.enabled = true; return event; }));
    events.push({ type: 'limit', label: 'طلب التخفيض', date: plan.limit, enabled: inputs.limitEnabled.checked });
    events.push({ type: 'cut', label: 'طلب القطع', date: plan.cut, enabled: inputs.cutEnabled.checked });
    return events;
  }
  function eventIcon(type) {
    return { generation: 'fa-file-text-o', cycle: 'fa-calendar-check-o', due: 'fa-clock-o', reminder: 'fa-bell-o', grace: 'fa-shield', limit: 'fa-tachometer', cut: 'fa-ban' }[type] || 'fa-circle';
  }
  function renderChips() {
    var target = document.getElementById('abcReminderChips');
    if (!target) return;
    var values = reminderOffsets();
    target.innerHTML = values.length ? values.map(function (offset) {
      var label = offset === 0 ? 'يوم الاستحقاق' : (offset < 0 ? 'قبل الاستحقاق بـ ' + Math.abs(offset) + ' يوم' : 'بعد الاستحقاق بـ ' + offset + ' يوم');
      return '<span>' + label + '</span>';
    }).join('') : '<span>لم يحدد أي يوم</span>';
  }
  function renderTimeline(events) {
    var target = document.getElementById('abcTimeline');
    if (!target) return;
    target.innerHTML = events.map(function (event) {
      return '<article class="' + (event.enabled ? '' : 'is-disabled') + '"><b><i class="fa ' + eventIcon(event.type) + '"></i>' + event.label + '</b><time dir="ltr">' + iso(event.date) + '</time></article>';
    }).join('');
  }
  function render() {
    var plan = schedule();
    var events = allEvents(plan);
    var visible = events.filter(function (event) { return event.enabled; });
    var times = visible.map(function (event) { return event.date.getTime(); });
    var start = new Date(Math.min.apply(Math, times));
    var end = new Date(Math.max.apply(Math, times));
    start = new Date(start.getFullYear(), start.getMonth(), 1);
    end = new Date(end.getFullYear(), end.getMonth(), 1);

    var byDate = {};
    visible.forEach(function (event) {
      var key = iso(event.date);
      (byDate[key] = byDate[key] || []).push(event);
    });

    var html = '';
    var month = new Date(start.getFullYear(), start.getMonth(), 1);
    var guard = 0;
    while (month <= end && guard < 12) {
      var monthName = new Intl.DateTimeFormat('ar', { month: 'long', year: 'numeric' }).format(month);
      html += '<section class="abc-month"><h4>' + monthName + '</h4><div class="abc-week">' +
        weekdays.map(function (name) { return '<span>' + name + '</span>'; }).join('') +
        '</div><div class="abc-days">';
      var firstWeekday = month.getDay();
      for (var empty = 0; empty < firstWeekday; empty++) html += '<button type="button" class="abc-day is-empty" tabindex="-1"></button>';
      var lastDay = new Date(month.getFullYear(), month.getMonth() + 1, 0).getDate();
      for (var day = 1; day <= lastDay; day++) {
        var date = new Date(month.getFullYear(), month.getMonth(), day);
        var key = iso(date);
        var dateEvents = byDate[key] || [];
        html += '<button type="button" class="abc-day ' + (key === cfg.today ? 'is-today' : '') + '" data-date="' + key + '"><time>' + day + '</time><span class="abc-day__events">' +
          dateEvents.map(function (event) { return '<span class="abc-event abc-event--' + event.type + '">' + event.label + '</span>'; }).join('') +
          '</span></button>';
      }
      html += '</div></section>';
      month = new Date(month.getFullYear(), month.getMonth() + 1, 1);
      guard++;
    }
    calendar.innerHTML = html;
    renderChips();
    renderTimeline(events);
  }
  function setMode(nextMode) {
    mode = nextMode;
    document.querySelectorAll('[data-calendar-mode]').forEach(function (button) {
      button.classList.toggle('is-active', button.getAttribute('data-calendar-mode') === mode);
    });
    var hint = document.getElementById('abcCalendarHint');
    if (hint) hint.textContent = {
      reminder: 'رسالة التسديد مثبتة تلقائياً على يوم الاستحقاق.',
      limit: 'الوضع الحالي: تحديد يوم طلب تخفيض السرعة بعد انتهاء السماح.',
      cut: 'الوضع الحالي: تحديد يوم طلب القطع بعد انتهاء السماح.'
    }[mode];
  }
  document.querySelectorAll('[data-calendar-mode]').forEach(function (button) {
    button.addEventListener('click', function () { setMode(button.getAttribute('data-calendar-mode')); });
  });
  calendar.addEventListener('click', function (event) {
    var day = event.target.closest('[data-date]');
    if (!day) return;
    var date = localDate(day.getAttribute('data-date'));
    var plan = schedule();
    if (mode === 'reminder') {
      return;
    } else if (mode === 'limit') {
      var limitOffset = diffDays(date, plan.grace);
      if (limitOffset < 0) return;
      inputs.limitAfter.value = limitOffset;
      inputs.limitEnabled.checked = true;
    } else if (mode === 'cut') {
      var cutOffset = diffDays(date, plan.grace);
      if (cutOffset < 0) return;
      inputs.cutAfter.value = cutOffset;
      inputs.cutEnabled.checked = true;
    }
    render();
  });
  Object.keys(inputs).forEach(function (key) {
    var input = inputs[key];
    if (!input || key === 'offsets') return;
    input.addEventListener('input', render);
    input.addEventListener('change', render);
  });
  var quotaForm = document.getElementById('abcQuotaRunForm');
  if (quotaForm) quotaForm.addEventListener('submit', function (event) {
    if (!window.confirm('سيتم فحص الاستهلاك وقد تتغير سرعة بعض المشتركين على MikroTik. هل تريد المتابعة؟')) event.preventDefault();
  });
  var exceptionalForm = document.getElementById('abcExceptionalCycleForm');
  if (exceptionalForm) exceptionalForm.addEventListener('submit', function (event) {
    if (exceptionalForm.dataset.confirmed === '1') {
      exceptionalForm.classList.add('is-submitting');
      return;
    }
    event.preventDefault();
    var title = 'إنشاء دورة فواتير استثنائية';
    var message = 'سيتم إنشاء فواتير فوراً لجميع المشتركين النشطين وبدء مهل التنبيه والتخفيض والقطع المحفوظة. لن يتغير موعد دورة الفواتير التلقائية.';
    var finish = function (approved) {
      if (!approved) return;
      exceptionalForm.dataset.confirmed = '1';
      exceptionalForm.classList.add('is-submitting');
      var submitButton = exceptionalForm.querySelector('button[type="submit"]');
      if (submitButton) {
        submitButton.disabled = true;
        var label = submitButton.querySelector('span');
        var hint = submitButton.querySelector('small');
        if (label) label.textContent = 'جارٍ إنشاء الدورة';
        if (hint) hint.textContent = 'يرجى عدم إغلاق الصفحة';
      }
      exceptionalForm.submit();
    };
    if (typeof window.uaConfirm === 'function') {
      window.uaConfirm(title, message, { confirmText: 'إنشاء الدورة', cancelText: 'إلغاء', kind: 'warning' }).then(finish);
    } else {
      finish(window.confirm(message));
    }
  });
  document.querySelectorAll('.abc-toast button').forEach(function (button) {
    button.addEventListener('click', function () { button.closest('.abc-toast').remove(); });
  });
  render();
})();
