// public/assets/house_report.js
(() => {
  const $  = (s, ctx=document) => ctx.querySelector(s);
  const $$ = (s, ctx=document) => Array.from(ctx.querySelectorAll(s));

  // Controls
  const wardDD    = $('#hr-ward');
  const input     = $('#house-search');
  const houseDD   = $('#house-select');
  const listBox   = $('#house-suggest');
  const pickBtn   = $('#house-pick-btn');
  const dlCSVBtn  = $('#house-download-csv');

  // Display
  const cardInfo  = $('#house-card');
  const tbl       = $('#house-table');
  const thead     = $('#house-thead');
  const tbody     = $('#house-rows');

  let picked = null;   // single-house payload
  let allItems = [];   // all-houses payload

  // ---- helpers ----
  const log = (...a)=>console.log('[HouseReport]',...a);
  const err = (...a)=>console.error('[HouseReport]',...a);
  function showError(msg){ if(cardInfo) cardInfo.innerHTML = `<div class="muted" style="color:#b02a37">${msg}</div>`; }
  function debounce(fn, ms=250){ let t; return (...a)=>{ clearTimeout(t); t=setTimeout(()=>fn(...a),ms); }; }

  async function apiJSON(qs){
    const url = `api_house_report.php${qs}`;
    const r = await fetch(url, { cache: 'no-store' });
    const txt = await r.text();
    if (!r.ok) throw new Error(txt || `HTTP ${r.status}`);
    return JSON.parse(txt);
  }

  // ---- renderers ----
  function resetToSingleHeader(){
    thead.innerHTML = `
      <tr>
        <th style="text-align:center; width:80px;">Round</th>
        <th style="text-align:center;">Training</th>
        <th style="text-align:center;">Waste Segregation</th>
        <th style="text-align:center;">DTDC</th>
      </tr>`;
    tbody.innerHTML = '';
    if (cardInfo) cardInfo.innerHTML = '';
  }

  function renderSingleCard(d){
    const nm = d.resident_name || d.name || '—';
    cardInfo.innerHTML = `
      <div class="info-grid">
        <div><div class="label">HOUSE NO</div><div class="value">${d.house_no}</div></div>
        <div><div class="label">RESIDENT</div><div class="value">${nm}</div></div>
        <div><div class="label">MOBILE</div><div class="value">${d.mobile || '—'}</div></div>
        <div><div class="label">WARD</div><div class="value">${d.ward || '—'}</div></div>
      </div>`;
  }

  function renderSingleTable(d){
    const rows = [['T1','WS1','DC1'],['T2','WS2','DC2'],['T3','WS3','DC3']];
    tbody.innerHTML = rows.map(([t,ws,dc])=>{
      const train = d.training[t], wsv=d.waste[ws], dcv=d.dtdc[dc];
      return `
        <tr>
          <td style="text-align:center;">${t}</td>
          <td style="text-align:center; font-weight:600; ${train==='done'?'color:#2fa84f':'color:#b02a37'}">${train}</td>
          <td style="text-align:center;">${wsv}</td>
          <td style="text-align:center;">${dcv}</td>
        </tr>`;
    }).join('');
  }

  function renderAllTable(items){
    thead.innerHTML = `
      <tr>
        <th>House No</th>
        <th>Ward</th>
        <th>Training 1</th><th>WS 1</th><th>DTDC 1</th>
        <th>Training 2</th><th>WS 2</th><th>DTDC 2</th>
        <th>Training 3</th><th>WS 3</th><th>DTDC 3</th>
      </tr>`;
    tbody.innerHTML = items.map(it=>{
      const link = `<a href="#" data-id="${it.id}" class="house-link">${it.house_no}</a>`;
      return `
        <tr>
          <td>${link}</td>
          <td>${it.ward || ''}</td>
          <td>${it.T1.training}</td><td>${it.T1.ws}</td><td>${it.T1.dc}</td>
          <td>${it.T2.training}</td><td>${it.T2.ws}</td><td>${it.T2.dc}</td>
          <td>${it.T3.training}</td><td>${it.T3.ws}</td><td>${it.T3.dc}</td>
        </tr>`;
    }).join('');

    // link -> single house
    $$('#house-rows .house-link').forEach(a=>{
      a.addEventListener('click', (e)=>{
        e.preventDefault();
        const id = a.getAttribute('data-id');
        if (id) {
          if (houseDD) houseDD.value = ''; // switch to single mode
          fetchDetail({ house_id: id });
          cardInfo && cardInfo.scrollIntoView({ behavior:'smooth', block:'start' });
        }
      });
    });

    if (cardInfo) cardInfo.innerHTML = '';
  }

  // ---- fetchers ----
  async function fetchAllDetails(){
    const w = (wardDD && wardDD.value) || 'all';
    try{
      const data = await apiJSON(`?mode=all_details&ward=${encodeURIComponent(w)}`);
      allItems = data.items || [];
      picked = null;
      renderAllTable(allItems);
      log('all_details', w, allItems.length);
    }catch(e){
      allItems=[]; picked=null;
      showError(`All-houses failed: ${e.message}`);
    }
  }

  async function fetchDetail(params){
    if (listBox) listBox.style.display='none';
    try{
      const qs = new URLSearchParams({mode:'detail', ...params}).toString();
      const data = await apiJSON(`?${qs}`);
      picked = data; allItems=[];
      resetToSingleHeader();
      renderSingleCard(data);
      renderSingleTable(data);
      log('detail', data.house_no);
    }catch(e){
      picked=null; allItems=[];
      showError(`Not found: ${e.message}`);
    }
  }

  async function loadHousesForWard(w){
    if (!houseDD) return;
    // keep two base options: blank + All houses
    houseDD.innerHTML = `
      <option value="">Select house…</option>
      <option value="*">All houses</option>
    `;
    if (!w || w === 'all') return; // All wards => user can select All houses or type

    try{
      const data = await apiJSON(`?mode=houses_by_ward&ward=${encodeURIComponent(w)}`);
      (data.houses || []).forEach(h=>{
        const opt = document.createElement('option');
        opt.value = h.id;                 // pass id for detail
        opt.textContent = h.house_no;
        opt.dataset.house_no = h.house_no;
        houseDD.appendChild(opt);
      });
      // DO NOT auto-select anything; leave blank by default
    }catch(e){
      showError(`House list failed: ${e.message}`);
    }
  }

  // ---- events ----
  wardDD && wardDD.addEventListener('change', async ()=>{
    if (input) input.value='';
    if (listBox) listBox.style.display='none';
    picked=null; allItems=[];
    resetToSingleHeader();
    await loadHousesForWard(wardDD.value);
    // no auto-fetch here (only when user selects "All houses")
  });

  houseDD && houseDD.addEventListener('change', ()=>{
    const v = houseDD.value;
    if (v === '*'){ if (input) input.value=''; fetchAllDetails(); return; }
    if (v){ // specific house by id
      const opt = houseDD.selectedOptions[0];
      if (input) input.value = opt?.dataset?.house_no || '';
      fetchDetail({ house_id: v });
      return;
    }
    // blank: clear view
    resetToSingleHeader();
  });

  // Enter to search typed house_no
  input && input.addEventListener('keydown', (e)=>{
    if (e.key === 'Enter'){
      e.preventDefault();
      const v = input.value.trim();
      if (!v) return;
      if (houseDD) houseDD.value = ''; // force single-house mode
      fetchDetail({ house: v });
    }
  });

  // CSV export
  function downloadCSV(rows, name){
    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');
    a.href = url; a.download = name;
    document.body.appendChild(a); a.click(); a.remove();
    URL.revokeObjectURL(url);
  }

  dlCSVBtn && dlCSVBtn.addEventListener('click', ()=>{
    if (allItems.length){
      const header = ['House No','Ward','Training 1','WS 1','DTDC 1','Training 2','WS 2','DTDC 2','Training 3','WS 3','DTDC 3'];
      const rows = [header];
      allItems.forEach(it=>{
        rows.push([ it.house_no, it.ward || '',
          it.T1.training, it.T1.ws, it.T1.dc,
          it.T2.training, it.T2.ws, it.T2.dc,
          it.T3.training, it.T3.ws, it.T3.dc ]);
      });
      downloadCSV(rows, `house_report_${((wardDD&&wardDD.value)||'all')}_all_houses.csv`);
      return;
    }
    if (!picked) return;
    const rows = [
      ['House No', picked.house_no],
      ['Resident', (picked.resident_name || picked.name || '')],
      ['Mobile', picked.mobile || ''],
      ['Ward', picked.ward || ''],
      [],
      ['Round','Training','Waste Segregation','DTDC'],
      ['T1', picked.training.T1, picked.waste.WS1, picked.dtdc.DC1],
      ['T2', picked.training.T2, picked.waste.WS2, picked.dtdc.DC2],
      ['T3', picked.training.T3, picked.waste.WS3, picked.dtdc.DC3],
    ];
    downloadCSV(rows, `house_report_${picked.house_no}.csv`);
  });

  // ---- INIT ----
  (async function init(){
    await loadHousesForWard((wardDD && wardDD.value) || 'all');
    // NOTE: no auto-fetch on load
  })();
})();

// ===== House Report → PDF (capture visible section) =====
(() => {
  const btn = document.getElementById('house-download-pdf');
  if (!btn) return;

  btn.addEventListener('click', async () => {
    if (!window.html2pdf) { alert('PDF engine not loaded'); return; }

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

    // Capture the whole House Report panel (most reliable)
    const panel = table.closest('section') || table;

    // Detect All vs Single (by header)
    const firstTh = document.querySelector('#house-thead th');
    const isAll = firstTh && firstTh.textContent.trim().toLowerCase().startsWith('house no');

    // Save & force styles
    const oldBg   = panel.style.background;
    const oldCol  = panel.style.color;
    const oldMinW = panel.style.minWidth;
    const oldMinH = panel.style.minHeight;

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

    if (document.fonts && document.fonts.ready) { try { await document.fonts.ready; } catch(e){} }

    const rect = panel.getBoundingClientRect();
    if (rect.width < 10) panel.style.minWidth = '1200px';
    if (rect.height < 10) panel.style.minHeight = '300px';

    const wardDD = document.getElementById('hr-ward');
    const wardVal = wardDD ? (wardDD.value || 'all') : 'all';

    const filename = isAll
      ? `house_report_${wardVal}_all_houses.pdf`
      : 'house_report_single.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(panel).save();
    } catch (e) {
      console.error('[House PDF]', e);
      alert('PDF export failed.');
    } finally {
      panel.style.background = oldBg;
      panel.style.color      = oldCol;
      panel.style.minWidth   = oldMinW;
      panel.style.minHeight  = oldMinH;
    }
  });
})();
