(function () {
  'use strict';

  const DONORBOX_CAMPAIGN_URL = 'https://donorbox.org/soutenir-index-2025-don';
  const TAX_REDUCTION_RATE = 0.66;

  const AMOUNTS = {
    oneOff: [200, 100, 50, 20],
    monthly: [50, 20, 10, 5],
  };

  const TRANSLATIONS = {
    fr: {
      afterTax: 'Soit {amount}&#8239;€ après impôts',
      perMonth: '€/mois',
      withTaxReduction: 'Avec 66&#8239;% de déduction fiscale',
    },
    en: {
      afterTax: 'That is {amount}&#8239;€ after tax',
      perMonth: '€/month',
      withTaxReduction: 'With 66&#8239;% tax deduction',
    },
  };

  function getLanguage() {
    return document.documentElement.lang || 'fr';
  }

  function translate(key, params = {}) {
    const lang = getLanguage();
    let text = TRANSLATIONS[lang][key] || TRANSLATIONS['fr'][key];
    Object.keys(params).forEach((param) => {
      text = text.replace(`{${param}}`, params[param]);
    });
    return text;
  }

  function calculateAfterTax(amount) {
    const result = amount * (1 - TAX_REDUCTION_RATE);
    const rounded = Math.round(result * 100) / 100;
    return rounded % 1 === 0 ? Math.round(rounded) : rounded.toFixed(2);
  }

  function formatAmount(amount) {
    return amount.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '\u202F');
  }

  function generateDonorboxUrl(amount, isMonthly) {
    const params = new URLSearchParams();
    params.append('default_interval', isMonthly ? 'm' : 'o');
    if (amount) {
      params.append('amount', amount);
    }

    // Récupérer les paramètres UTM de l'URL actuelle
    const currentUrlParams = new URLSearchParams(window.location.search);
    const utmParams = [
      'utm_source',
      'utm_medium',
      'utm_campaign',
      'utm_term',
      'utm_content',
    ];

    utmParams.forEach((utmParam) => {
      const value = currentUrlParams.get(utmParam);
      if (value) {
        params.append(utmParam, value);
      }
    });

    return `${DONORBOX_CAMPAIGN_URL}?${params.toString()}`;
  }

  function initTabs() {
    const tabButtons = document.querySelectorAll('.nav--tabs__btn');
    const containers = document.querySelectorAll('.btn--donation__container');

    tabButtons.forEach((button, index) => {
      button.addEventListener('click', () => {
        tabButtons.forEach((btn) => btn.classList.remove('is-selected'));
        containers.forEach((container) =>
          container.classList.remove('is-selected')
        );

        button.classList.add('is-selected');
        containers[index].classList.add('is-selected');
      });
    });
  }

  function initDonationButtons() {
    const oneOffContainer = document.querySelector(
      '[data-donnation="one-off"]'
    );
    const oneOffButtons = oneOffContainer.querySelectorAll('.btn--donation');

    oneOffButtons.forEach((button, index) => {
      if (index < AMOUNTS.oneOff.length) {
        const amount = AMOUNTS.oneOff[index];
        const afterTax = calculateAfterTax(amount);

        button.innerHTML = `
          <p class="bold">${formatAmount(amount)}&#8239;€</p>
          <p class="small">${translate('afterTax', {
            amount: formatAmount(afterTax),
          })}</p>
        `;

        button.addEventListener('click', () => {
          window.open(generateDonorboxUrl(amount, false), '_blank');
        });
      } else {
        button.addEventListener('click', () => {
          window.open(generateDonorboxUrl(null, false), '_blank');
        });
      }
    });

    const monthlyContainer = document.querySelector(
      '[data-donnation="monthly"]'
    );
    const monthlyButtons = monthlyContainer.querySelectorAll('.btn--donation');

    monthlyButtons.forEach((button, index) => {
      if (index < AMOUNTS.monthly.length) {
        const amount = AMOUNTS.monthly[index];
        const afterTax = calculateAfterTax(amount);

        button.innerHTML = `
          <p class="bold">${formatAmount(amount)}&#8239;${translate(
          'perMonth'
        )}</p>
          <p class="small">${translate('afterTax', {
            amount: formatAmount(afterTax),
          })}</p>
        `;

        button.addEventListener('click', () => {
          window.open(generateDonorboxUrl(amount, true), '_blank');
        });
      } else {
        button.addEventListener('click', () => {
          window.open(generateDonorboxUrl(null, true), '_blank');
        });
      }
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    initTabs();
    initDonationButtons();
  });
})();
