(() => {
  const wardSelect = document.getElementById('ward-select');
  const kTotal = document.getElementById('k-total');
  const kYes = document.getElementById('k-yes');
  const kNo = document.getElementById('k-no');
  const pieCtx = document.getElementById('pie').getContext('2d');
  // keep barCtx in case we re-enable later
  const barCtx = document.getElementById('bar') ? document.getElementById('bar').getContext('2d') : null;

  let pieChart, barChart;

  function percent(part, total) {
    if (!total) return '0%';
    return Math.round((part / total) * 100) + '%';
  }

  function buildPieLabels(yes, no) {
    const total = yes + no;
    const yesPct = total ? Math.round((yes / total) * 100) : 0;
    const noPct = total ? 100 - yesPct : 0;
    return [`Segregating (${yesPct}%)`, `Not segregating (${noPct}%)`];
  }

  function renderTableFromBreakdown(breakdown) {
  const tbody = document.getElementById('ward-table-body');
  const tfoot = document.getElementById('ward-table-foot');
  tbody.innerHTML = '';
  tfoot.innerHTML = '';

  // add sumDtdc here 👇
  let sumTotal = 0, sumYes = 0, sumNo = 0, sumDtdc = 0;

  breakdown.forEach((row) => {
    const tr = document.createElement('tr');
    const segregationPct = row.total ? Math.round((row.yes / row.total) * 100) : 0;
    tr.innerHTML = `
      <td style="padding:8px; border-bottom:1px solid #f0f0f0;">${row.ward}</td>
      <td style="padding:8px; border-bottom:1px solid #f0f0f0; text-align:right;">${row.total.toLocaleString()}</td>
      <td style="padding:8px; border-bottom:1px solid #f0f0f0; text-align:right;">${row.yes.toLocaleString()}</td>
      <td style="padding:8px; border-bottom:1px solid #f0f0f0; text-align:right;">${row.no.toLocaleString()}</td>
      <td style="padding:8px; border-bottom:1px solid #f0f0f0; text-align:right;">${(row.dtdc ?? 0).toLocaleString()}</td>
      <td style="padding:8px; border-bottom:1px solid #f0f0f0; text-align:right;">${segregationPct}%</td>
    `;
    tbody.appendChild(tr);

    sumTotal += row.total;
    sumYes   += row.yes;
    sumNo    += row.no;
    sumDtdc  += (row.dtdc ?? 0); // now safe
  });

  const totalPct = sumTotal ? Math.round((sumYes / sumTotal) * 100) : 0;
  tfoot.innerHTML = `
    <tr style="font-weight:700; border-top:2px solid #ddd;">
      <td style="padding:8px;">Total</td>
      <td style="padding:8px; text-align:right;">${sumTotal.toLocaleString()}</td>
      <td style="padding:8px; text-align:right;">${sumYes.toLocaleString()}</td>
      <td style="padding:8px; text-align:right;">${sumNo.toLocaleString()}</td>
      <td style="padding:8px; text-align:right;">${sumDtdc.toLocaleString()}</td>
      <td style="padding:8px; text-align:right;">${totalPct}%</td>
    </tr>
  `;
}


  function downloadCSVFromBreakdown(breakdown, wardLabel) {
    // build CSV: Ward,Total,Segregating,NotSegregating,Segregation%
    const rows = [];
    rows.push(['Ward', 'Total Houses', 'Segregating', 'Not Segregating','DTDC', 'Segregation %']);
    breakdown.forEach(r => {
      const pct = r.total ? Math.round((r.yes / r.total) * 100) + '%' : '0%';
      rows.push([r.ward, String(r.total), String(r.yes), String(r.no),String(r.dtdc ?? 0), pct]);
    });
    // totals
    const sumTotal = breakdown.reduce((s,v)=>s+v.total,0);
    const sumYes = breakdown.reduce((s,v)=>s+v.yes,0);
    const sumNo = breakdown.reduce((s,v)=>s+v.no,0);
    const sumDtdc  = breakdown.reduce((s,v)=>s+(v.dtdc ?? 0),0); // NEW
    const sumPct = sumTotal ? Math.round((sumYes / sumTotal) * 100) + '%' : '0%';
    rows.push(['Total', String(sumTotal), String(sumYes), String(sumNo),String(sumDtdc), sumPct]);

    const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    const namePart = wardLabel ? wardLabel.replace(/\s+/g,'_') : 'report';
    a.href = url;
    a.download = `ward_report_${namePart}.csv`;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  }
  
 // ===== Ward Report → PDF (capture visible element) =====
async function exportWardReportPDF() {
  if (!window.html2pdf) { alert('PDF engine not loaded'); return; }

  const table = document.getElementById('ward-table');
  if (!table) { alert('Ward table not found'); return; }

  // Prefer capturing the whole section that contains the table (more reliable)
  const target = table.closest('section') || table;

  // Force a solid background and ensure we have a size
  const oldBg   = target.style.background;
  const oldCol  = target.style.color;
  const oldMinW = target.style.minWidth;
  const oldMinH = target.style.minHeight;

  target.style.background = '#ffffff';
  target.style.color = '#000';
  target.style.minWidth = '1024px';
  target.style.minHeight = '10px';

  // Make sure fonts are ready
  if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch(e){} }

  // Quick sanity: if element is collapsed, expand temporarily
  const rect = target.getBoundingClientRect();
  if (rect.width < 10) target.style.minWidth = '1200px';
  if (rect.height < 10) target.style.minHeight = '200px';

  const sel = (document.getElementById('ward-select')?.value || 'all');
  const filename = `ward_report_${sel === 'all' ? 'all_wards' : sel}.pdf`;

  const opt = {
    margin:       16,
    filename,
    image:        { type: 'jpeg', quality: 0.98 },
    html2canvas:  { scale: 2, useCORS: true, backgroundColor: '#ffffff' },
    jsPDF:        { unit: 'pt', format: 'a4', orientation: 'landscape' },
    pagebreak:    { mode: ['avoid-all','css','legacy'] }
  };

  try {
    await html2pdf().set(opt).from(target).save();
  } catch (e) {
    console.error('[Ward PDF]', e);
    alert('PDF export failed.');
  } finally {
    // restore styles
    target.style.background = oldBg;
    target.style.color      = oldCol;
    target.style.minWidth   = oldMinW;
    target.style.minHeight  = oldMinH;
  }
}

const wardPdfBtn = document.getElementById('download-pdf');
if (wardPdfBtn) wardPdfBtn.addEventListener('click', exportWardReportPDF);





  async function loadData() {
    const ward = wardSelect.value;
    const r = await fetch(`api_dashboard.php?ward=${encodeURIComponent(ward)}`);
    const data = await r.json();

    // KPIs
    kTotal.textContent = data.totals.total.toLocaleString();
    kYes.textContent = data.totals.yes.toLocaleString();
    kNo.textContent = data.totals.no.toLocaleString();

    // Pie - labels include percentages
    const pieLabels = buildPieLabels(data.totals.yes, data.totals.no);
    const pieData = {
      labels: pieLabels,
      datasets: [{
        data: [data.totals.yes, data.totals.no],
        // backgroundColor omitted so Chart.js picks defaults
      }]
    };
    if (pieChart) pieChart.destroy();
    pieChart = new Chart(pieCtx, {
      type: 'pie',
      data: pieData,
      options: {
        plugins: {
          legend: { position: 'bottom' },
          tooltip: {
            callbacks: {
              label: function(context) {
                const value = context.parsed;
                const total = data.totals.yes + data.totals.no;
                const pct = total ? Math.round((value / total) * 100) : 0;
                return `${context.label}: ${value.toLocaleString()} (${pct}%)`;
              }
            }
          }
        },
        maintainAspectRatio: false
      }
    });

    // --- BAR chart: commented out for now (kept so it's easy to re-enable later) ---
    /*
    const barData = {
      labels: data.growth.labels,
      datasets: [{
        label: 'Households segregating',
        data: data.growth.yes
      }]
    };
    if (barChart) barChart.destroy();
    barChart = new Chart(barCtx, {
      type: 'bar',
      data: barData,
      options: {
        scales: { y: { beginAtZero: true, ticks: { precision:0 } } },
        plugins: { legend: { display: false } },
        maintainAspectRatio: false
      }
    });
    */

    // Table: use data.breakdown (an array) to render rows
    // For single ward selection the API returns breakdown as single row (ward)
    const breakdown = Array.isArray(data.breakdown) && data.breakdown.length ? data.breakdown : [{
      ward: ward,
      total: data.totals.total,
      yes: data.totals.yes,
      no: data.totals.no,
      dtdc: data.totals.dtdc ?? 0   // add this
      
    }];

    renderTableFromBreakdown(breakdown);

    // attach download action (updates every load so filename matches ward)
    const downloadBtn = document.getElementById('download-csv');
    downloadBtn.onclick = (e) => {
      const wardLabel = (ward === 'all') ? 'All_Wards' : ward;
      downloadCSVFromBreakdown(breakdown, wardLabel);
    };
  }

  wardSelect.addEventListener('change', loadData);
  window.addEventListener('load', loadData);
})();
