import './style.css';

const pad = (value) => String(value).padStart(2, '0');

document.querySelectorAll('.calio-accordion[data-multiple="0"]').forEach((root) => {
  root.querySelectorAll('details').forEach((item) => {
    item.addEventListener('toggle', () => {
      if (!item.open) return;
      root.querySelectorAll('details').forEach((other) => {
        if (other !== item) other.open = false;
      });
    });
  });
});

const runCountdown = (root) => {
  const target = root.dataset.date ? new Date(root.dataset.date).getTime() : NaN;
  if (!target) return;

  const expiredNode = root.nextElementSibling && root.nextElementSibling.classList.contains('calio-countdown-expired')
    ? root.nextElementSibling
    : null;

  const update = () => {
    const now = Date.now();
    const diff = Math.max(target - now, 0);

    const totalSeconds = Math.floor(diff / 1000);
    const days = Math.floor(totalSeconds / 86400);
    const hours = Math.floor((totalSeconds % 86400) / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    const map = { days, hours, minutes, seconds };
    Object.keys(map).forEach((key) => {
      const node = root.querySelector(`[data-unit="${key}"]`);
      if (node) node.textContent = pad(map[key]);
    });

    if (diff === 0 && expiredNode) {
      root.style.display = 'none';
      expiredNode.style.display = 'block';
    }
  };

  update();
  setInterval(update, 1000);
};

document.querySelectorAll('.calio-countdown').forEach(runCountdown);
