document.addEventListener('DOMContentLoaded', () => {
  const addressInput = document.getElementById('addressInput');
  const submitBtn = document.getElementById('submitBtn');
  const suggestionsDiv = document.getElementById('suggestions');
  const resultDiv = document.getElementById('result');

  const backendUrl = 'http://127.0.0.1:5001'; // change if your backend runs elsewhere

  function formatCurrency(val){
    if (val === null || val === undefined) return '-';
    return '$' + Number(val).toLocaleString();
  }

  function clearResult(){ resultDiv.innerHTML = ''; }
  function clearSuggestions(){ suggestionsDiv.innerHTML = ''; }

  function renderSuggestions(list){
    clearSuggestions();
    if (!Array.isArray(list) || list.length === 0) return;
    const card = document.createElement('div');
    card.className = 'result-card';
    const ul = document.createElement('ul');
    ul.style.listStyle='none';
    ul.style.margin='0';
    ul.style.padding='0';
    list.forEach(item => {
      const li = document.createElement('li');
      li.style.padding = '6px 8px';
      li.style.borderBottom = '1px solid #eef2f7';
      li.style.cursor = 'pointer';
      li.textContent = item.label || item.street || '';
      li.addEventListener('click', () => {
        addressInput.value = item.label || item.street || '';
        clearSuggestions();
        submitBtn.click();
      });
      ul.appendChild(li);
    });
    card.appendChild(ul);
    suggestionsDiv.appendChild(card);
  }

  function showLoading(){
    clearResult();
    const c = document.createElement('div');
    c.className = 'result-card loading';
    c.textContent = 'Loading…';
    resultDiv.appendChild(c);
  }

  function showError(msg){
    clearResult();
    const c = document.createElement('div');
    c.className = 'result-card';
    c.innerHTML = `<div class="error">${msg}</div>`;
    resultDiv.appendChild(c);
  }

  function renderResults(data){
    clearResult();

    if (!data || !data.results || data.results.length === 0){
      const card = document.createElement('div');
      card.className = 'result-card';
      card.innerHTML = '<div class="no-results">No results found for that address.</div>';
      resultDiv.appendChild(card);
      return;
    }

    const subject = data.results[0];
    const estimate = data.estimate || {};

    const card = document.createElement('div');
    card.className = 'result-card';

    const title = document.createElement('div');
    title.innerHTML = `<div style="font-weight:700">${subject.street || data.address}</div><div class="small">${subject.city || ''} ${subject.state || ''} ${subject.zip_code || ''}</div>`;
    card.appendChild(title);

    const est = document.createElement('div');
    est.className = 'estimate';
    if (estimate && estimate.estimated_price){
      est.textContent = formatCurrency(estimate.estimated_price);
    } else if (estimate && estimate.display){
      est.textContent = estimate.display.replace(/\n/g, ' — ');
    } else {
      est.textContent = 'No estimate';
    }
    card.appendChild(est);

    if (estimate && estimate.note){
      const note = document.createElement('div');
      note.className = 'meta';
      note.textContent = estimate.note;
      card.appendChild(note);
    }

    const fields = document.createElement('div');
    fields.className = 'fields';
    const beds = document.createElement('div'); beds.className='field'; beds.innerHTML = `<div style="font-weight:700">${subject.beds ?? '-'}</div><div class="small">beds</div>`;
    const baths = document.createElement('div'); baths.className='field'; baths.innerHTML = `<div style="font-weight:700">${subject.baths ?? '-'}</div><div class="small">baths</div>`;
    const sqft = document.createElement('div'); sqft.className='field'; sqft.innerHTML = `<div style="font-weight:700">${subject.sqft ?? '-'}</div><div class="small">sqft</div>`;
    fields.appendChild(beds); fields.appendChild(baths); fields.appendChild(sqft);
    card.appendChild(fields);

    const listPrice = document.createElement('div');
    listPrice.className='meta';
    listPrice.textContent = 'List price: ' + (subject.list_price ? formatCurrency(subject.list_price) : '-');
    card.appendChild(listPrice);

    if (subject.property_url){
      const link = document.createElement('a');
      link.href = subject.property_url;
      link.target = '_blank';
      link.rel = 'noopener noreferrer';
      link.className = 'button-link';
      link.textContent = 'View property';
      card.appendChild(link);
    }

    // Comps if available
    if (Array.isArray(data.estimate?.comps) && data.estimate.comps.length){
      const h = document.createElement('div'); h.className='meta'; h.style.marginTop='8px'; h.textContent = 'Comparable sales'; card.appendChild(h);
      const ul = document.createElement('ul'); ul.className='comp-list';
      data.estimate.comps.forEach(cmp => {
        const li = document.createElement('li');
        const price = cmp.list_price ? formatCurrency(cmp.list_price) : '-';
        li.textContent = `${cmp.street || ''} — ${price} — ${cmp.sqft ? cmp.sqft + ' sqft' : ''}`;
        ul.appendChild(li);
      });
      card.appendChild(ul);
    }

    resultDiv.appendChild(card);
  }

  submitBtn.addEventListener('click', async () => {
    const address = addressInput.value.trim();
    if (!address){ showError('Please enter an address'); return; }

    try{
      showLoading();
      const res = await fetch(backendUrl + '/address', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({address})
      });

      if (!res.ok) throw new Error('HTTP error! status: ' + res.status);
      const data = await res.json();
      renderResults(data);
    }catch(err){
      showError(err.message);
    }
  });

  // Allow pressing Enter in the input to trigger
  addressInput.addEventListener('keyup', (e)=>{ if (e.key === 'Enter') submitBtn.click(); });

  // Autocomplete: debounce input and call /suggest
  let timer = null;
  addressInput.addEventListener('input', (e) => {
    clearResult();
    clearSuggestions();
    const v = e.target.value.trim();
    if (timer) clearTimeout(timer);
    if (v.length < 2) return;
    timer = setTimeout(async () => {
      try{
        const res = await fetch(backendUrl + '/suggest?q=' + encodeURIComponent(v));
        if (!res.ok) return;
        const payload = await res.json();
        renderSuggestions(payload.suggestions || []);
      }catch(err){
        // ignore suggestion errors
        console.error('suggest error', err);
      }
    }, 300);
  });
});