(() => {
  'use strict';

  const MODAL_ID = 'pyrkPollCalendarHardFixModal';
  const MONTHS = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  let activeInputId = null;
  let state = {year: new Date().getFullYear(), month: new Date().getMonth()};

  function esc(value) {
    return String(value ?? '').replace(/[&<>"']/g, ch => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[ch]));
  }

  function modalHtml() {
    return `
      <div id="${MODAL_ID}" class="pyrk-poll-calendar-modal" hidden aria-hidden="true">
        <div class="pyrk-poll-calendar-card" role="dialog" aria-modal="true" aria-labelledby="pyrkPollCalendarTitle">
          <div class="pyrk-poll-calendar-head">
            <div>
              <strong id="pyrkPollCalendarTitle">Select date</strong>
              <span>dd/mm/yyyy</span>
            </div>
            <button type="button" class="pyrk-poll-cal-close" data-pyrk-cal-close aria-label="Close">×</button>
          </div>

          <div class="pyrk-poll-calendar-toolbar">
            <button type="button" class="pyrk-poll-cal-nav" data-pyrk-cal-action="prevYear" aria-label="Previous year">«</button>
            <button type="button" class="pyrk-poll-cal-nav" data-pyrk-cal-action="prevMonth" aria-label="Previous month">‹</button>
            <strong class="pyrk-poll-calendar-current" id="pyrkPollCalendarCurrent"></strong>
            <button type="button" class="pyrk-poll-cal-nav" data-pyrk-cal-action="nextMonth" aria-label="Next month">›</button>
            <button type="button" class="pyrk-poll-cal-nav" data-pyrk-cal-action="nextYear" aria-label="Next year">»</button>
          </div>

          <div class="pyrk-poll-calendar-weekdays">
            <span>Sun</span><span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span>
          </div>

          <div class="pyrk-poll-calendar-grid" id="pyrkPollCalendarGrid"></div>

          <div class="pyrk-poll-calendar-foot">
            <button type="button" class="pyrk-poll-cal-foot light" data-pyrk-cal-action="today">Today</button>
            <button type="button" class="pyrk-poll-cal-foot light" data-pyrk-cal-action="clear">Clear</button>
            <button type="button" class="pyrk-poll-cal-foot done" data-pyrk-cal-close>Done</button>
          </div>
        </div>
      </div>`;
  }

  function ensureModal() {
    let modal = document.getElementById(MODAL_ID);
    if (!modal) {
      document.body.insertAdjacentHTML('beforeend', modalHtml());
      modal = document.getElementById(MODAL_ID);
    }
    return modal;
  }

  function parseDdMmYyyy(value) {
    const m = String(value || '').trim().match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
    if (!m) return null;
    const day = Number(m[1]);
    const month = Number(m[2]);
    const year = Number(m[3]);
    const date = new Date(year, month - 1, day);
    if (date.getFullYear() !== year || date.getMonth() !== month - 1 || date.getDate() !== day) return null;
    return date;
  }

  function formatDdMmYyyy(date) {
    return `${String(date.getDate()).padStart(2, '0')}/${String(date.getMonth() + 1).padStart(2, '0')}/${date.getFullYear()}`;
  }

  function activeInput() {
    return activeInputId ? document.getElementById(activeInputId) : null;
  }

  function setValue(value) {
    const input = activeInput();
    if (!input) return;
    input.value = value;
    input.dispatchEvent(new Event('input', {bubbles: true}));
    input.dispatchEvent(new Event('change', {bubbles: true}));
  }

  function isoKey(date) {
    return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
  }

  function render() {
    const modal = ensureModal();
    const grid = modal.querySelector('#pyrkPollCalendarGrid');
    const current = modal.querySelector('#pyrkPollCalendarCurrent');
    if (!grid || !current) return;

    current.textContent = `${MONTHS[state.month]} ${state.year}`;

    const selected = parseDdMmYyyy(activeInput()?.value || '');
    const selectedKey = selected ? isoKey(selected) : '';
    const todayKey = isoKey(new Date());

    const first = new Date(state.year, state.month, 1);
    const days = new Date(state.year, state.month + 1, 0).getDate();

    let html = '';
    for (let i = 0; i < first.getDay(); i++) {
      html += '<span class="pyrk-poll-calendar-empty"></span>';
    }

    for (let day = 1; day <= days; day++) {
      const date = new Date(state.year, state.month, day);
      const key = isoKey(date);
      const classes = [
        'pyrk-poll-calendar-day',
        key === selectedKey ? 'is-selected' : '',
        key === todayKey ? 'is-today' : ''
      ].filter(Boolean).join(' ');
      html += `<button type="button" class="${esc(classes)}" data-pyrk-calendar-date="${esc(formatDdMmYyyy(date))}">${day}</button>`;
    }

    grid.innerHTML = html;
  }

  function open(inputId) {
    activeInputId = inputId;
    const input = activeInput();
    const existing = parseDdMmYyyy(input?.value || '');
    const base = existing || new Date();
    state = {year: base.getFullYear(), month: base.getMonth()};

    const modal = ensureModal();
    const title = modal.querySelector('#pyrkPollCalendarTitle');
    if (title) title.textContent = inputId === 'pollEndsAt' ? 'Select end date' : 'Select start date';

    render();
    modal.hidden = false;
    modal.setAttribute('aria-hidden', 'false');
  }

  function close() {
    const modal = document.getElementById(MODAL_ID);
    if (!modal) return;
    modal.hidden = true;
    modal.setAttribute('aria-hidden', 'true');
  }

  function moveMonth(delta) {
    state.month += delta;
    while (state.month < 0) {
      state.month += 12;
      state.year -= 1;
    }
    while (state.month > 11) {
      state.month -= 12;
      state.year += 1;
    }
    render();
  }

  function moveYear(delta) {
    state.year += delta;
    render();
  }

  function handleAction(action) {
    if (action === 'prevMonth') moveMonth(-1);
    if (action === 'nextMonth') moveMonth(1);
    if (action === 'prevYear') moveYear(-1);
    if (action === 'nextYear') moveYear(1);
    if (action === 'today') {
      setValue(formatDdMmYyyy(new Date()));
      close();
    }
    if (action === 'clear') {
      setValue('');
      close();
    }
  }

  function formatTyping(input) {
    let value = String(input.value || '').replace(/[^\d]/g, '').slice(0, 8);
    if (value.length >= 5) value = `${value.slice(0, 2)}/${value.slice(2, 4)}/${value.slice(4)}`;
    else if (value.length >= 3) value = `${value.slice(0, 2)}/${value.slice(2)}`;
    input.value = value;
  }

  document.addEventListener('click', event => {
    const trigger = event.target.closest('[data-poll-calendar-target], .poll-date-trigger');
    if (trigger) {
      event.preventDefault();
      event.stopPropagation();
      const target = trigger.dataset.pollCalendarTarget || trigger.dataset.dateTarget || trigger.getAttribute('data-date-target');
      if (target) open(target);
      return;
    }

    const dateBtn = event.target.closest('[data-pyrk-calendar-date]');
    if (dateBtn) {
      event.preventDefault();
      setValue(dateBtn.dataset.pyrkCalendarDate || '');
      close();
      return;
    }

    const action = event.target.closest('[data-pyrk-cal-action]');
    if (action) {
      event.preventDefault();
      handleAction(action.dataset.pyrkCalAction);
      return;
    }

    if (event.target.closest('[data-pyrk-cal-close]')) {
      event.preventDefault();
      close();
      return;
    }

    const modal = document.getElementById(MODAL_ID);
    if (modal && event.target === modal) close();
  }, true);

  document.addEventListener('input', event => {
    const input = event.target.closest('#pollStartsAt, #pollEndsAt, .pyrk-poll-date-input');
    if (input) formatTyping(input);
  });

  document.addEventListener('keydown', event => {
    if (event.key === 'Escape') close();
  });

  window.PyrkPollCalendarHardFix = {open, close};
})();