const DONORBOX_CONFIG = {
  proxyUrl: '/api/donorbox-proxy.php',
};

function formatCurrency(amount) {
  const rounded = Math.round(amount * 100) / 100;
  const hasDecimals = rounded % 1 !== 0;

  const formatted = rounded.toLocaleString('fr-FR', {
    minimumFractionDigits: 0,
    maximumFractionDigits: hasDecimals ? 2 : 0,
  });

  return formatted.replace(/[\s\u00A0\u202F]/g, '\u202F') + '\u202F€';
}

async function fetchDonorboxData() {
  try {
    const response = await fetch(DONORBOX_CONFIG.proxyUrl, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error ${response.status}: ${response.statusText}`);
    }

    const data = await response.json();

    if (data.error) {
      throw new Error(data.error);
    }

    return data;
  } catch (error) {
    console.error('Error fetching Donorbox data:', error);
    throw error;
  }
}

function updateGaugeDisplay(campaignData) {
  const collected = campaignData.total_raised || 0;
  const goal = campaignData.goal_amt || 50000;
  const percentage = Math.min((collected / goal) * 100, 100);

  const gaugeElement = document.getElementById('gauge');
  if (gaugeElement) {
    gaugeElement.style.setProperty(
      '--pourcent',
      `${percentage > 2.5 ? percentage : 2.5}%`
    );
  }

  const collectedElement = document.querySelector(
    '#gauge--infos__donateurs .value'
  );
  if (collectedElement) {
    collectedElement.textContent = formatCurrency(collected);
  }

  const goalElement = document.querySelector('#gauge--infos__objectif .value');
  if (goalElement) {
    goalElement.textContent = formatCurrency(goal);
  }

  const donorsCount = campaignData.donations_count || 0;
  const donorsElement = document.querySelector('#gauge--infos__donors .value');
  if (donorsElement) {
    donorsElement.textContent = donorsCount;
  }

  console.log('Gauge updated:', {
    collected: formatCurrency(collected),
    goal: formatCurrency(goal),
    percentage: `${percentage.toFixed(1)}%`,
  });
}

async function initDonorboxGauge() {
  try {
    console.log('Fetching Donorbox data...');
    const campaignData = await fetchDonorboxData();
    updateGaugeDisplay(campaignData);
  } catch (error) {
    console.error('Failed to update gauge:', error);
  }
}

function setupAutoRefresh(intervalMinutes = 5) {
  const intervalMs = intervalMinutes * 60 * 1000;
  setInterval(initDonorboxGauge, intervalMs);
  console.log(`Auto-refresh configured: every ${intervalMinutes} minutes`);
}

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    initDonorboxGauge();
    setupAutoRefresh(5);
  });
} else {
  initDonorboxGauge();
  setupAutoRefresh(5);
}
