const baseUrl = 'https://test.sticonnect.info/';

function fetchDashboardData(callback) {
  fetch(baseUrl + 'dashboard_counts')
    .then(r => r.json())
    .then(data => {
      callback(data);
    })
    .catch(err => console.error('Error fetching dashboard data:', err));
}

function fetchEventsData(callback) {
  fetch(baseUrl + 'getallEvents')
    .then(r => r.json())
    .then(data => {
      callback(data);
    })
    .catch(err => console.error('Error fetching events data:', err));
}

document.addEventListener('DOMContentLoaded', () => {
  fetchDashboardData(processDashboardData);
  fetchEventsData(processEventsData);
});

function processDashboardData(data) {
  if ('project_count' in data) $('#project_count').text(data.project_count);

  if ('institutions_count' in data) {
    let totalInstitutions = 0;
    let institutionsBreakup = '';
    for (let country in data.institutions_count) {
      const count = parseInt(data.institutions_count[country]) || 0;
      totalInstitutions += count;
      institutionsBreakup += `${country}: ${count}<br>`;
    }
    $('#institutions_count').text(totalInstitutions);
    $('.institution_card small.fontbold').html(institutionsBreakup);
  }

  if ('ministry_count' in data) {
    let totalMinistries = 0;
    let ministriesBreakup = '';
    for (let country in data.ministry_count) {
      const count = parseInt(data.ministry_count[country]) || 0;
      totalMinistries += count;
      ministriesBreakup += `${country}: ${count}<br>`;
    }
    $('#ministries_count').text(totalMinistries);
    $('.ministry_card small.fontbold').html(ministriesBreakup);
  }

  if ('minuteDetails' in data && Array.isArray(data.minuteDetails)) {
    let totalProjectValue = 0;
    let minuteDetailsBreakup = '';
    data.minuteDetails.forEach(item => {
      const totalCost = parseInt(item.total_cost) || 0;
      totalProjectValue += totalCost;
      const formattedCost = totalCost.toLocaleString('en-IN');
      minuteDetailsBreakup += `${item.country_name}: ${formattedCost} ${item.financeEstimatedCurrency}<br>`;
    });
    $('#project_value_count').text(totalProjectValue.toLocaleString('en-IN'));
    $('.projectvalue_card small.fontbold').html(minuteDetailsBreakup);
  }

  if ('completed_project_count' in data) $('#completed_project_count').text(data.completed_project_count);
  if ('in_progress_project_count' in data) $('#in_progress_project_count').text(data.in_progress_project_count);
  if ('yet_to_start_project_count' in data) $('#yet_to_start_project_count').text(data.yet_to_start_project_count);
  $('#project_value_count').text(((+data.project_value_count)||0).toLocaleString('en-US') + ' USD');

  if (Array.isArray(data.goals)) renderGoalsCarousel(data.goals);
}

function getRandomColor() {
  return `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6,'0')}`;
}

function renderGoalsCarousel(goals) {
  const carousel = document.getElementById('goals-carousel');
  const dots = document.getElementById('goals-carousel-dots');
  carousel.innerHTML = '';
  dots.innerHTML = '';
  window.goalCharts = {};

  goals.forEach((goal, idx) => {
    const chartDivId = `goal-chart-${idx}`, chartLabelId = `goal-labels-${idx}`;
    carousel.innerHTML += `
      <div class="goals-carousel-slide${idx === 0 ? " active" : ""}">
        <div class="card mb-4">
          <div class="card-header">${goal.goal_name}</div>
          <div class="card-body">
            <div class="row g-3 align-items-center">
              <div class="col-md-5"><canvas id="${chartDivId}"></canvas></div>
              <div class="col-md-7 d-flex align-items-center">
                <div class="goals-scroll-content"><div id="${chartLabelId}"></div></div>
              </div>
            </div>
          </div>
        </div>
      </div>`;
    dots.innerHTML += `<span class="carousel-dot${idx === 0 ? ' active' : ''}" data-slide="${idx}"></span>`;
  });

  goals.forEach((goal, idx) => {
    setTimeout(() => {
      const labels = goal.sub_goal_object.map(sg => sg.sub_goal_name);
      const data = goal.sub_goal_object.map(sg => parseInt(sg.sub_goal_count, 10));
      drawDoughnutChart(labels, data, goal.goal_name, `goal-chart-${idx}`, `goal-labels-${idx}`);
    }, 0);
  });

  initGoalsCarouselEvents(goals.length);
}

function drawDoughnutChart(labels, data, label, chartDivId, chartLabelId) {
  if (window.goalCharts[chartDivId]) window.goalCharts[chartDivId].destroy();
  const colors = data.map(getRandomColor);
  const ctx = document.getElementById(chartDivId);
  if (!ctx) return;

  window.goalCharts[chartDivId] = new Chart(ctx, {
    type: 'doughnut',
    data: { labels, datasets: [{label, data, backgroundColor: colors, hoverOffset: 4}] },
    options: {
      plugins: {
        legend: { display: false },
        datalabels: { display: true, color: 'white'},
        tooltip: { enabled: true, callbacks: {
          label: ctx => {
            const value = ctx.raw, total = ctx.dataset.data.reduce((a,b)=>a+b,0);
            const pct = ((value / total) * 100).toFixed(2);
            return ` ${value} Projects (${pct}%)`;
          }
        }},
      },
      animation: false
    },
    plugins: [ChartDataLabels]
  });

  const container = document.getElementById(chartLabelId);
  container.innerHTML = '';
  const total = data.reduce((a,b)=>a+b,0);
  labels.forEach((lbl, i) => {
    const row = document.createElement('div');
    row.classList.add('goal-label-row');
    const box = document.createElement('div');
    box.classList.add('goal-color-box');
    box.style.setProperty('--box-color', colors[i]);
    const span = document.createElement('span');
    span.innerHTML = `<strong>${lbl}</strong>: ${data[i]} Projects (${((data[i]/total)*100).toFixed(2)}%)`;
    row.appendChild(box);
    row.appendChild(span);
    container.appendChild(row);
  });
}

function initGoalsCarouselEvents(goalCount) {
  let idx = 0;
  const slides = document.querySelectorAll('.goals-carousel-slide');
  const dots = document.querySelectorAll('.carousel-dot');

  function updateSlide(index) {
    slides.forEach((s,i)=>{ s.style.display=i===index ? 'block':'none'; s.classList.toggle('active',i===index); });
    dots.forEach((d,i)=> d.classList.toggle('active',i===index));
    idx = index;
  }

  document.querySelector('.goals-carousel-next').onclick = e => { e.stopPropagation(); updateSlide((idx+1)%goalCount);};
  document.querySelector('.goals-carousel-prev').onclick = e => { e.stopPropagation(); updateSlide((idx-1+goalCount)%goalCount);};
  dots.forEach(dot => dot.onclick = e => { e.stopPropagation(); updateSlide(+dot.getAttribute('data-slide')); });

  updateSlide(0);
}

function processEventsData(events) {
  if (Array.isArray(events)) {
    renderEvents(events);
    initFilters();
    initEventsCarousel();
    document.querySelector('.filters button[data-filter="upcoming"]').click();
  }
}

function renderEvents(events) {
  const container = $('#event-cards').empty();
  const now = new Date();
  events.forEach(event => {
    const endDate = new Date(event.end_date);
    const status = endDate >= now ? 'upcoming' : 'completed';
    const type = (event.type || 'General').toLowerCase();
    const formatDate = date => {
      const d = new Date(date);
      const monthNames = [
        "January","February","March","April","May","June",
        "July","August","September","October","November","December"
      ];
      return `${d.getDate()} ${monthNames[d.getMonth()]} ${d.getFullYear()}`;
    };
    container.append(`
      <div class="event-card p-3" data-type="${type}" data-status="${status}">
        <h3>${event.name}</h3>
        <div class="badge-container">
          <span class="badge">${status.charAt(0).toUpperCase()+status.slice(1)}</span>
        </div>
        <p><strong><i class="fas fa-calendar"></i></strong> ${formatDate(event.start_date)} - ${formatDate(event.end_date)}</p>
        <p><strong><i class="fas fa-map-marker-alt"></i></strong> ${event.venue}</p>
        <p>${event.description}</p>
      </div>
    `);
  });
}

    function getFilteredCards() {
        const activeBtn = document.querySelector('.filters button.active');
        const activeFilter = activeBtn ? activeBtn.getAttribute('data-filter') : 'all';
        const cards = Array.from(document.querySelectorAll('.event-card'));
        if (activeFilter === 'all') return cards;
        return cards.filter(card => {
        const status = (card.dataset.status || '').toLowerCase();
        const type = (card.dataset.type || '').toLowerCase();
        return activeFilter === status || activeFilter === type;
        });
    }

// function initFilters() {
//   document.querySelectorAll('.filters button').forEach(btn => {
//     btn.addEventListener('click', e => {
//       e.stopPropagation();
//       const filter = btn.getAttribute('data-filter');
//       document.querySelectorAll('.filters button').forEach(b=>b.classList.remove('active'));
//       btn.classList.add('active');
//       document.querySelectorAll('.event-card').forEach(card => {
//         card.style.display = (filter==='all'||card.dataset.status===filter) ? 'block':'none';
//       });
//     });
//   });
// }

// function initEventsCarousel() {
//   let idx = 0;
//   const slides = document.querySelectorAll('.event-card');
//   function showSlide(index) {
//     slides.forEach((s,i)=>s.style.display=i===index?'block':'none');
//     idx = index;
//   }
//   document.querySelector('.events-carousel-next').onclick = e=>{ e.stopPropagation(); showSlide((idx+1)%slides.length); };
//   document.querySelector('.events-carousel-prev').onclick = e=>{ e.stopPropagation(); showSlide((idx-1+slides.length)%slides.length); };
//   showSlide(0);
// }

function initFilters() {
document.querySelectorAll('.filters button').forEach(btn => {
btn.addEventListener('click', e => {
e.stopPropagation();
document.querySelectorAll('.filters button').forEach(b=>b.classList.remove('active'));
btn.classList.add('active');
currentIndex = 0;
showCards();
});
});
}

let currentIndex = 0;
const visibleCount = 3;


function showCards() {
const filteredCards = getFilteredCards();
document.querySelectorAll('.event-card').forEach(card => {
card.style.display = 'none';
});


filteredCards.slice(currentIndex, currentIndex + visibleCount).forEach(card => {
card.style.display = 'block';
});


document.querySelector('.events-carousel-prev').disabled = currentIndex === 0;
document.querySelector('.events-carousel-next').disabled = currentIndex + visibleCount >= filteredCards.length;
}


function initEventsCarousel() {
document.querySelector('.events-carousel-prev').addEventListener('click', e => {
e.stopPropagation();
if (currentIndex > 0) {
currentIndex--;
showCards();
}
});


document.querySelector('.events-carousel-next').addEventListener('click', e => {
e.stopPropagation();
const filteredCards = getFilteredCards();
if (currentIndex + visibleCount < filteredCards.length) {
currentIndex++;
showCards();
}
});


showCards();
}

document.querySelectorAll('.card .arrow').forEach(arrow => {
  arrow.addEventListener('click', e => {
    e.stopPropagation();
    const card = arrow.closest('.card');
    card.classList.toggle('expanded');
    arrow.textContent = card.classList.contains('expanded') ? '▴' : '▾';
  });
});

const sections = ['metrics', 'insights', 'events'];

const originalContent = {};
sections.forEach(id => {
  originalContent[id] = document.getElementById(id).innerHTML;
});

function restoreDashboardUK() {
  sections.forEach(id => {
    document.getElementById(id).innerHTML = originalContent[id];
  });

  fetchDashboardData(processDashboardData);
  fetchEventsData(processEventsData);

  setTimeout(() => {
    document.querySelectorAll('.metrics-cards .card .arrow').forEach(arrow => {
      arrow.addEventListener('click', () => {
        const card = arrow.closest('.card');
        card.classList.toggle('expanded');
        arrow.textContent = card.classList.contains('expanded') ? '▴' : '▾';
      });
    });
  }, 0);
}

function showUpdateSoon(countryKey) {
  const pretty = countryKey.charAt(0).toUpperCase() + countryKey.slice(1);
const html = `
      <div class="fullscreen-notice">
        <div class="notice-title">India - ${pretty}</div>
        <div class="notice-main">Will be updated soon</div>
        <div class="notice-sub">We're working on the <strong>India - ${pretty}</strong> section - check back later.</div>
      </div>
    `;
  document.getElementById(sections[0]).innerHTML = html;
  sections.slice(1).forEach(id => {
    document.getElementById(id).innerHTML = '';
  });
}

const selectcountry = document.getElementById('countrySelect');
selectcountry.addEventListener('change', (e) => {
  const val = (e.target.value || "").trim().toLowerCase();
  if (!val || val === 'uk') {
    restoreDashboardUK();
  } else {
    showUpdateSoon(val);
  }
});

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